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: a
176/// debug build panicked on the addition and a release build wrapped the key and
177/// reported 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, which is what it did before, left the rule enforced
550        // against the frame and 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                match decode_kvp_delta(&mut inner) {
829                    Ok(nested) => check_track_property_values(&nested)?,
830                    // Not a Key-Value-Pair run. See the note above: reading the
831                    // block is a permission, so one that cannot be read is
832                    // carried rather than refused.
833                    Err(_) => return Ok(()),
834                }
835            }
836            KvpValue::Bytes(_) => {}
837        }
838    }
839    Ok(())
840}
841
842/// Decode the Track Properties that fill the tail of a control message.
843///
844/// [`decode_kvp_delta`] with the Property registry's value rules applied. The
845/// two are separate because that function also reads Setup Options, which are a
846/// third namespace numbering its entries independently of this one.
847fn decode_track_properties(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
848    let properties = decode_kvp_delta(buf)?;
849    check_track_property_values(&properties)?;
850    Ok(properties)
851}
852
853/// Encode a control message's Track Properties.
854///
855/// Held to the same value ranges as the decoder. A value this codec refuses to
856/// read is one it must not write: the peer that receives it is required to close
857/// the session, so the sender's first sign of trouble would be the session
858/// going.
859fn encode_track_properties(
860    properties: &[KeyValuePair],
861    buf: &mut impl BufMut,
862) -> Result<(), CodecError> {
863    check_track_property_values(properties)?;
864    encode_kvp_delta(properties, buf)
865}
866
867/// The Setup Option types this draft defines.
868///
869/// Section 10.3.1 assigns PATH, AUTHORIZATION TOKEN, MAX_AUTH_TOKEN_CACHE_SIZE, AUTHORITY,
870/// MAX_FILTER_RANGES, MOQT_IMPLEMENTATION and MAX_REQUEST_UPDATES.
871///
872/// The list exists for one rule and one direction. Section 10.3: "Receivers
873/// MUST allow duplicates of unknown Setup Options." A receiver may therefore
874/// refuse a repeat only of a type it can name, and an option outside this list
875/// is one an extension defined and this codec has no business closing a session
876/// over. Nothing else reads it - unknown options are still decoded and carried,
877/// as "Receivers MUST ignore unrecognized Setup Options" requires.
878const KNOWN_SETUP_OPTIONS: &[u64] = &[0x01, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
879
880/// The one Setup Option whose definition allows more than one instance.
881///
882/// Section 10.3.1.4: "The AUTHORIZATION TOKEN Setup Option (Option Type 0x03)
883/// is functionally equivalent to the AUTHORIZATION TOKEN message parameter...
884/// The endpoint can specify one or more tokens in SETUP that the peer can use to
885/// authorize MOQT session establishment." That is the "unless the option
886/// definition explicitly allows multiple instances" carve-out, and it is the
887/// only one on this draft.
888const REPEATABLE_SETUP_OPTION: u64 = 0x03;
889
890/// Decode the Setup Options of a SETUP message.
891///
892/// Section 10.3: "Senders MUST NOT repeat the same Option Type in a message
893/// unless the option definition explicitly allows multiple instances. Receivers
894/// MUST allow duplicates of unknown Setup Options."
895///
896/// The second sentence is why this is not the mirror of
897/// [`encode_setup_options`]: a repeat of a type this draft names is refused, and
898/// a repeat of any other type is carried. Types ascend and are delta-encoded, so
899/// a repeat is always a zero delta against the option before it.
900fn decode_setup_options(buf: &mut impl Buf) -> Result<Vec<KeyValuePair>, CodecError> {
901    let options = decode_kvp_delta(buf)?;
902    for (i, option) in options.iter().enumerate() {
903        let key = option.key.into_inner();
904        if key == REPEATABLE_SETUP_OPTION || !KNOWN_SETUP_OPTIONS.contains(&key) {
905            continue;
906        }
907        if options[..i].iter().any(|earlier| earlier.key == option.key) {
908            return Err(CodecError::DuplicateParameter(key));
909        }
910    }
911    check_authorization_tokens(&options)?;
912    Ok(options)
913}
914
915/// Encode the Setup Options of a SETUP message.
916///
917/// The sender's half of the same sentence, and it is the wider half: "Senders
918/// MUST NOT repeat the same Option Type in a message" names no exception for
919/// types the sender does not recognise, so every repeat is refused here except
920/// the one the draft allows. A caller holding an option this codec has never
921/// heard of still may not send it twice.
922///
923/// The token is in this namespace as well, and is held to its structure here for
924/// the reason [`encode_parameters`] gives.
925fn encode_setup_options(options: &[KeyValuePair], buf: &mut impl BufMut) -> Result<(), CodecError> {
926    check_authorization_tokens(options)?;
927    for (i, option) in options.iter().enumerate() {
928        if option.key.into_inner() == REPEATABLE_SETUP_OPTION {
929            continue;
930        }
931        if options[..i].iter().any(|earlier| earlier.key == option.key) {
932            return Err(CodecError::DuplicateParameter(option.key.into_inner()));
933        }
934    }
935    encode_kvp_delta(options, buf)
936}
937
938// ============================================================
939// Message Types
940// ============================================================
941
942#[derive(Debug, Clone, Copy, PartialEq, Eq)]
943#[repr(u64)]
944pub enum MessageType {
945    RequestUpdate = 0x02,
946    Subscribe = 0x03,
947    SubscribeOk = 0x04,
948    RequestError = 0x05,
949    PublishNamespace = 0x06,
950    /// REQUEST_OK (0x07). PUBLISH_OK is now an alias of this type.
951    RequestOk = 0x07,
952    Namespace = 0x08,
953    PublishDone = 0x0B,
954    TrackStatus = 0x0D,
955    NamespaceDone = 0x0E,
956    PublishSkipped = 0x0F,
957    GoAway = 0x10,
958    Fetch = 0x16,
959    FetchOk = 0x18,
960    Publish = 0x1D,
961    /// PUBLISH_STATE_NOTIFY (0x22), new in draft-20 (Section 10.10).
962    PublishStateNotify = 0x22,
963    /// SUBSCRIBE_NAMESPACE (renumbered to 0x50 in draft-18).
964    SubscribeNamespace = 0x50,
965    /// SUBSCRIBE_TRACKS (new message in draft-18).
966    SubscribeTracks = 0x51,
967    Setup = 0x2F00,
968}
969
970impl MessageType {
971    pub fn from_id(id: u64) -> Option<Self> {
972        match id {
973            0x02 => Some(MessageType::RequestUpdate),
974            0x03 => Some(MessageType::Subscribe),
975            0x04 => Some(MessageType::SubscribeOk),
976            0x05 => Some(MessageType::RequestError),
977            0x06 => Some(MessageType::PublishNamespace),
978            0x07 => Some(MessageType::RequestOk),
979            0x08 => Some(MessageType::Namespace),
980            0x0B => Some(MessageType::PublishDone),
981            0x0D => Some(MessageType::TrackStatus),
982            0x0E => Some(MessageType::NamespaceDone),
983            0x0F => Some(MessageType::PublishSkipped),
984            0x10 => Some(MessageType::GoAway),
985            0x16 => Some(MessageType::Fetch),
986            0x18 => Some(MessageType::FetchOk),
987            0x1D => Some(MessageType::Publish),
988            0x22 => Some(MessageType::PublishStateNotify),
989            0x50 => Some(MessageType::SubscribeNamespace),
990            0x51 => Some(MessageType::SubscribeTracks),
991            0x2F00 => Some(MessageType::Setup),
992            _ => None,
993        }
994    }
995
996    pub fn id(&self) -> u64 {
997        *self as u64
998    }
999
1000    /// This type's name in the shared vector corpus: the `message_type` its
1001    /// draft's `codec/messages/*.json` files carry, in `snake_case`.
1002    pub fn name(&self) -> &'static str {
1003        match self {
1004            MessageType::RequestUpdate => "request_update",
1005            MessageType::Subscribe => "subscribe",
1006            MessageType::SubscribeOk => "subscribe_ok",
1007            MessageType::RequestError => "request_error",
1008            MessageType::PublishNamespace => "publish_namespace",
1009            MessageType::RequestOk => "request_ok",
1010            MessageType::Namespace => "namespace",
1011            MessageType::PublishDone => "publish_done",
1012            MessageType::TrackStatus => "track_status",
1013            MessageType::NamespaceDone => "namespace_done",
1014            MessageType::PublishSkipped => "publish_skipped",
1015            MessageType::GoAway => "goaway",
1016            MessageType::Fetch => "fetch",
1017            MessageType::FetchOk => "fetch_ok",
1018            MessageType::Publish => "publish",
1019            MessageType::PublishStateNotify => "publish_state_notify",
1020            MessageType::SubscribeNamespace => "subscribe_namespace",
1021            MessageType::SubscribeTracks => "subscribe_tracks",
1022            MessageType::Setup => "setup",
1023        }
1024    }
1025}
1026
1027// ============================================================
1028// Session Lifecycle Messages
1029// ============================================================
1030
1031/// Unified SETUP (0x2F00).
1032#[derive(Debug, Clone, PartialEq, Eq)]
1033pub struct Setup {
1034    pub options: Vec<KeyValuePair>,
1035}
1036
1037/// GOAWAY (0x10). In draft-20 the Request ID field is removed, so the
1038/// control-stream and request-stream forms are identical on the wire.
1039#[derive(Debug, Clone, PartialEq, Eq)]
1040pub struct GoAway {
1041    pub new_session_uri: Vec<u8>,
1042    pub timeout: VarInt,
1043}
1044
1045// ============================================================
1046// Consolidated Response Messages
1047// ============================================================
1048
1049/// REQUEST_OK (0x07). Used as a generic OK response and as the alias for
1050/// PUBLISH_OK / REQUEST_UPDATE_OK / TRACK_STATUS_OK / SUBSCRIBE_NAMESPACE_OK
1051/// / PUBLISH_NAMESPACE_OK.
1052///
1053/// `track_properties` is only populated for TRACK_STATUS_OK; for every
1054/// other shape it MUST be empty (length implicit from the message length).
1055#[derive(Debug, Clone, PartialEq, Eq)]
1056pub struct RequestOk {
1057    pub parameters: Vec<KeyValuePair>,
1058    pub track_properties: Vec<KeyValuePair>,
1059}
1060
1061/// Optional Redirect structure carried in REQUEST_ERROR with code 0x34.
1062#[derive(Debug, Clone, PartialEq, Eq)]
1063pub struct Redirect {
1064    pub connect_uri: Vec<u8>,
1065    pub track_namespace: TrackNamespace,
1066    pub track_name: Vec<u8>,
1067}
1068
1069/// REQUEST_ERROR (0x05). Adds an optional Redirect structure when
1070/// `error_code` is REDIRECT (0x34).
1071#[derive(Debug, Clone, PartialEq, Eq)]
1072pub struct RequestError {
1073    pub error_code: VarInt,
1074    pub retry_interval: VarInt,
1075    pub reason_phrase: Vec<u8>,
1076    pub redirect: Option<Redirect>,
1077}
1078
1079/// REQUEST_ERROR error codes with dedicated meaning.
1080///
1081/// Note: DUPLICATE_SUBSCRIPTION (0x19) is removed in draft-20, as multiple
1082/// concurrent subscriptions per Track are now allowed.
1083pub mod request_error_codes {
1084    /// A Mandatory Track Property the receiver does not understand.
1085    pub const UNSUPPORTED_EXTENSION: u64 = 0x33;
1086    /// Response carries a [`super::Redirect`] structure.
1087    pub const REDIRECT: u64 = 0x34;
1088    /// New in draft-20: SUBSCRIBE_TRACKS filter parameters conflict among too
1089    /// many subscribers to aggregate the subscription upstream.
1090    pub const CONFLICTING_FILTERS: u64 = 0x35;
1091    /// New in draft-20: a Range Filter parameter is invalid or exceeds
1092    /// MAX_FILTER_RANGES.
1093    pub const INVALID_FILTER: u64 = 0x36;
1094}
1095
1096// ============================================================
1097// Subscribe Messages
1098// ============================================================
1099
1100#[derive(Debug, Clone, PartialEq, Eq)]
1101pub struct Subscribe {
1102    pub request_id: VarInt,
1103    pub track_namespace: TrackNamespace,
1104    pub track_name: Vec<u8>,
1105    pub parameters: Vec<KeyValuePair>,
1106}
1107
1108/// SUBSCRIBE_OK (0x04).
1109#[derive(Debug, Clone, PartialEq, Eq)]
1110pub struct SubscribeOk {
1111    pub track_alias: VarInt,
1112    pub parameters: Vec<KeyValuePair>,
1113    pub track_properties: Vec<KeyValuePair>,
1114}
1115
1116#[derive(Debug, Clone, PartialEq, Eq)]
1117pub struct RequestUpdate {
1118    pub request_id: VarInt,
1119    pub parameters: Vec<KeyValuePair>,
1120}
1121
1122// ============================================================
1123// Publish Messages
1124// ============================================================
1125
1126#[derive(Debug, Clone, PartialEq, Eq)]
1127pub struct Publish {
1128    pub request_id: VarInt,
1129    pub track_namespace: TrackNamespace,
1130    pub track_name: Vec<u8>,
1131    pub track_alias: VarInt,
1132    pub parameters: Vec<KeyValuePair>,
1133    pub track_properties: Vec<KeyValuePair>,
1134}
1135
1136/// PUBLISH_DONE (0x0B). The wire layout is unchanged from draft-19; what
1137/// draft-20 changed is the `Stream Count` sentinel, what the count includes,
1138/// and the removal of status code 0x3.
1139#[derive(Debug, Clone, PartialEq, Eq)]
1140pub struct PublishDone {
1141    /// The reason the publisher is ending the subscription.
1142    ///
1143    /// Not validated against the registry, on decode or on encode, and that is
1144    /// the draft's instruction rather than an omission. Draft-20 Section 14:
1145    /// "Receipt of an unknown error code in any error context (Session
1146    /// Termination, REQUEST_ERROR, PUBLISH_DONE, or Data Stream Reset) MUST be
1147    /// treated as equivalent to INTERNAL_ERROR for that context. An endpoint
1148    /// MUST NOT close the session because it received an unknown error code in
1149    /// a REQUEST_ERROR or PUBLISH_DONE." Refusing the frame would take that
1150    /// choice away from the caller, so an unassigned code is carried up and
1151    /// [`super::error_codes::PublishDoneStatusCode::from_u64`] answers `None`
1152    /// for it.
1153    ///
1154    /// That reaches 0x3 in particular. Draft-19 assigned it to
1155    /// `SUBSCRIPTION_ENDED`; draft-20 removed the row and the behaviour behind
1156    /// it together (Section 5.1.2: "A publisher does not end a subscription
1157    /// solely because the Largest Object advances past the end of the current
1158    /// Location Filter"). A draft-20 receiver reads a 0x3 as INTERNAL_ERROR.
1159    pub status_code: VarInt,
1160    /// The number of streams the publisher opened for this subscription.
1161    ///
1162    /// Draft-20 Section 10.12 widens what is counted: the total now includes
1163    /// "streams that contained no Objects (e.g., an empty Subgroup) and
1164    /// including any fill fetch streams (see Section 5.1.3)". Draft-19 counted
1165    /// no fill streams because it had none.
1166    ///
1167    /// See [`publish_done_codes::STREAM_COUNT_UNKNOWN`] for the sentinel.
1168    pub stream_count: VarInt,
1169    pub reason_phrase: Vec<u8>,
1170}
1171
1172/// Numeric values for the [`PublishDone`] fields.
1173pub mod publish_done_codes {
1174    /// Draft-18 onwards: TOO_FAR_BEHIND is 0x05 (was 0x06 in draft-17).
1175    pub const TOO_FAR_BEHIND: u64 = 0x05;
1176    /// Draft-18 onwards: EXPIRED is 0x06 (was 0x05 in draft-17).
1177    pub const EXPIRED: u64 = 0x06;
1178
1179    /// The value [`super::PublishDone::stream_count`] carries when the
1180    /// publisher cannot state an exact count.
1181    ///
1182    /// Draft-20 Section 10.12: "If the publisher is unable to set Stream Count
1183    /// to the exact number of streams opened for the subscription, it MUST set
1184    /// Stream Count to 2^64 - 1." Draft-19 said `2^62 - 1`, which is where the
1185    /// QUIC varint tops out; MoQT's own varint (Section 1.4.1) is a
1186    /// leading-ones-length prefix reaching a full 64 bits in nine bytes, so
1187    /// this value is encodable at all — as `ff` followed by eight `ff` bytes.
1188    ///
1189    /// **The sentinel is now indistinguishable from a well-formed exact
1190    /// count.** With `2^62 - 1` there was headroom above the marker; there is
1191    /// none above this one, so a publisher that really opened `2^64 - 1`
1192    /// streams cannot say so and a receiver cannot tell the two apart. The
1193    /// draft does not remark on it. Not a practical problem, and worth knowing
1194    /// before writing a comparison against this constant.
1195    pub const STREAM_COUNT_UNKNOWN: u64 = u64::MAX;
1196}
1197
1198// ============================================================
1199// Publish Namespace Messages
1200// ============================================================
1201
1202#[derive(Debug, Clone, PartialEq, Eq)]
1203pub struct PublishNamespace {
1204    pub request_id: VarInt,
1205    pub track_namespace: TrackNamespace,
1206    pub parameters: Vec<KeyValuePair>,
1207}
1208
1209// ============================================================
1210// Namespace Messages
1211// ============================================================
1212
1213#[derive(Debug, Clone, PartialEq, Eq)]
1214pub struct Namespace {
1215    pub namespace_suffix: TrackNamespace,
1216}
1217
1218#[derive(Debug, Clone, PartialEq, Eq)]
1219pub struct NamespaceDone {
1220    pub namespace_suffix: TrackNamespace,
1221}
1222
1223// ============================================================
1224// Subscribe Namespace / Tracks Messages
1225// ============================================================
1226
1227/// SUBSCRIBE_NAMESPACE (0x50). Subscribes to NAMESPACE / NAMESPACE_DONE
1228/// advertisements for namespaces matching `namespace_prefix`. The
1229/// `subscribe_options` byte from draft-17 is removed; namespace subscriptions
1230/// only produce NAMESPACE / NAMESPACE_DONE.
1231#[derive(Debug, Clone, PartialEq, Eq)]
1232pub struct SubscribeNamespace {
1233    pub request_id: VarInt,
1234    pub namespace_prefix: TrackNamespace,
1235    pub parameters: Vec<KeyValuePair>,
1236}
1237
1238/// SUBSCRIBE_TRACKS (0x51, new in draft-18). Subscribes to PUBLISH messages
1239/// for tracks whose namespace matches `namespace_prefix`. Carries the
1240/// FORWARD parameter (which previously lived on SUBSCRIBE_NAMESPACE).
1241#[derive(Debug, Clone, PartialEq, Eq)]
1242pub struct SubscribeTracks {
1243    pub request_id: VarInt,
1244    pub namespace_prefix: TrackNamespace,
1245    pub parameters: Vec<KeyValuePair>,
1246}
1247
1248// ============================================================
1249// Track Status Messages
1250// ============================================================
1251
1252#[derive(Debug, Clone, PartialEq, Eq)]
1253pub struct TrackStatus {
1254    pub request_id: VarInt,
1255    pub track_namespace: TrackNamespace,
1256    pub track_name: Vec<u8>,
1257    pub parameters: Vec<KeyValuePair>,
1258}
1259
1260// ============================================================
1261// Fetch Messages
1262// ============================================================
1263
1264/// FETCH (0x16), rebuilt in draft-20 (Section 10.13, Figure 16).
1265///
1266/// ```text
1267/// FETCH Message {
1268///   Type (vi64) = 0x16,
1269///   Length (16),
1270///   Request ID (vi64),
1271///   Track Namespace (..),
1272///   Track Name Length (vi64),
1273///   Track Name (..),
1274///   Number of Parameters (vi64),
1275///   Parameters (..) ...
1276/// }
1277/// ```
1278///
1279/// # What went, and why draft-19's shape cannot be ported
1280///
1281/// Draft-19's FETCH opened with a `Fetch Type` that chose between a Standalone
1282/// Fetch — a namespace, a name and an inline `Start Location` / `End Location`
1283/// pair — and a Joining Fetch of two varints. Draft-20 deleted the field, both
1284/// structures, the Fetch Type registry and the whole joining mechanism, and
1285/// promoted the namespace and the name to fields of FETCH itself, in the
1286/// positions they held inside the old Standalone Fetch. What is left is
1287/// byte-identical to [`Subscribe`] apart from the type code.
1288///
1289/// The range now travels in the `LOCATION_FILTER` parameter (Section 5.1.2). A
1290/// FETCH with none covers `{0,0}` through Largest Object, inclusive.
1291///
1292/// # `INVALID_RANGE` and a relative start
1293///
1294/// Section 10.13 keeps draft-19's rule: "If no Objects have been published for
1295/// the track or Start Location is greater than the Largest Object" then "the
1296/// publisher MUST return REQUEST_ERROR with error code INVALID_RANGE". A
1297/// relative start —
1298/// the one-field `LOCATION_FILTER` with `StartGroup = 0`, which resolves to the
1299/// Next Group — is by construction greater than Largest Object, so read
1300/// literally the rule rejects every relative-start FETCH. That is plainly not
1301/// the intent and the text carves out nothing, so **this codec does not apply
1302/// the Start-greater-than-Largest test to a relative start**, and neither
1303/// should a caller. Nothing here can enforce either reading: the test needs
1304/// Largest Object, which is track state rather than anything in this frame, so
1305/// the decision belongs to the endpoint and is recorded here because this is
1306/// where the filter arrives.
1307///
1308/// **The codepoint did not change.** A draft-19 decoder fed one of these reads
1309/// the `Number of Track Namespace Fields` count as a `Fetch Type` and
1310/// mis-parses without complaint; there is no in-band version signal to catch
1311/// it. That is why draft-20 has a FETCH decoder of its own rather than sharing
1312/// draft-19's.
1313#[derive(Debug, Clone, PartialEq, Eq)]
1314pub struct Fetch {
1315    pub request_id: VarInt,
1316    pub track_namespace: TrackNamespace,
1317    pub track_name: Vec<u8>,
1318    pub parameters: Vec<KeyValuePair>,
1319}
1320
1321/// FETCH_OK (0x18). `end_of_track` is uint8.
1322///
1323/// Byte-identical to draft-19; the field that changed meaning is
1324/// [`FetchOk::end_object`].
1325#[derive(Debug, Clone, PartialEq, Eq)]
1326pub struct FetchOk {
1327    pub end_of_track: u8,
1328    pub end_group: VarInt,
1329    /// The Object ID of the **last Object the response covers**, inclusive.
1330    ///
1331    /// This is the silent off-by-one of the revision, and it is absent from
1332    /// draft-20's own change log. Draft-19 Section 10.13 defined the pair as
1333    /// "the end of the range covered by the FETCH response, using the same
1334    /// encoding as the FETCH request End Location (the last Object, plus 1; or
1335    /// 0 to indicate the entire Group)". Draft-20 Section 10.14 drops that
1336    /// parenthesis entirely, and Sections 5.1.2 and 10.13 both say the Location
1337    /// filter "specifies an inclusive range of Locations".
1338    ///
1339    /// So both draft-19 conventions are gone: there is no plus one, and an
1340    /// Object of 0 now means object 0 rather than the whole group. The bytes
1341    /// are identical between the two drafts and the meaning is not, and nothing
1342    /// on the wire distinguishes them — an encoder ported forward with its
1343    /// arithmetic intact fetches one object too many, and one whose end lands
1344    /// on object 0 fetches a single object where it used to fetch a group.
1345    ///
1346    /// **Ambiguous, and the draft leaves it so.** When the request's filter
1347    /// omitted `EndObject`, so the
1348    /// filter meant "all objects in the End Group", Section 10.14 does not say
1349    /// what to report — and with the `0`-means-whole-group encoding gone there
1350    /// is no way left to spell it. The same applies to a relative start. The
1351    /// reading this codec's corpus takes, and the only sane one, is the Object
1352    /// ID of the last Object actually covered; the draft does not say so, and
1353    /// nothing here can enforce it, because resolving it needs the track rather
1354    /// than the frame.
1355    pub end_object: VarInt,
1356    pub parameters: Vec<KeyValuePair>,
1357    pub track_properties: Vec<KeyValuePair>,
1358}
1359
1360// ============================================================
1361// Publish State Notify
1362// ============================================================
1363
1364/// PUBLISH_STATE_NOTIFY (0x22), new in draft-20 (Section 10.10, Figure 13).
1365///
1366/// ```text
1367/// PUBLISH_STATE_NOTIFY Message {
1368///   Type (vi64) = 0x22,
1369///   Length (16),
1370///   Number of Parameters (vi64),
1371///   Parameters (..) ...
1372/// }
1373/// ```
1374///
1375/// **There is no Request ID field.** The message is identified by the
1376/// subscription's bidirectional request stream it arrives on, the way
1377/// SUBSCRIBE_OK, PUBLISH_DONE and FETCH_OK are.
1378///
1379/// The rules a codec cannot check, because they are about the session rather
1380/// than the frame, and which the caller therefore owns (Section 10.10):
1381///
1382/// * it is sent by the **publisher only**, on a **subscription's** stream.
1383///   Receiving one for any other request type, or from the subscriber, MUST
1384///   close the session with a PROTOCOL_VIOLATION;
1385/// * it is **unilateral** — the receiver does not answer with REQUEST_OK or
1386///   REQUEST_ERROR — and it is not counted against the `MAX_REQUEST_UPDATES`
1387///   Setup Option;
1388/// * it carries only the parameters whose values changed, and an absent
1389///   parameter is unchanged;
1390/// * a publisher MUST NOT use it to change a subscriber-controlled parameter
1391///   unless the subscriber asked for the change;
1392/// * the publisher **MUST** include `LARGEST_OBJECT` (0x09) if known, so the
1393///   subscriber can locate the point in the track where the change took
1394///   effect. Nothing here enforces that: a missing required parameter is not
1395///   something this decoder detects, and a message that omits it is still a
1396///   well-formed frame.
1397#[derive(Debug, Clone, PartialEq, Eq)]
1398pub struct PublishStateNotify {
1399    pub parameters: Vec<KeyValuePair>,
1400}
1401
1402// ============================================================
1403// Publish Skipped
1404// ============================================================
1405
1406/// PUBLISH_SKIPPED (0x0F, renamed from PUBLISH_BLOCKED in draft-20; wire
1407/// layout is unchanged).
1408#[derive(Debug, Clone, PartialEq, Eq)]
1409pub struct PublishSkipped {
1410    pub namespace_suffix: TrackNamespace,
1411    pub track_name: Vec<u8>,
1412}
1413
1414// ============================================================
1415// Unified Message Enum
1416// ============================================================
1417
1418#[derive(Debug, Clone, PartialEq, Eq)]
1419pub enum ControlMessage {
1420    Setup(Setup),
1421    GoAway(GoAway),
1422    RequestOk(RequestOk),
1423    RequestError(RequestError),
1424    Subscribe(Subscribe),
1425    SubscribeOk(SubscribeOk),
1426    RequestUpdate(RequestUpdate),
1427    Publish(Publish),
1428    PublishStateNotify(PublishStateNotify),
1429    PublishDone(PublishDone),
1430    PublishNamespace(PublishNamespace),
1431    Namespace(Namespace),
1432    NamespaceDone(NamespaceDone),
1433    SubscribeNamespace(SubscribeNamespace),
1434    SubscribeTracks(SubscribeTracks),
1435    TrackStatus(TrackStatus),
1436    Fetch(Fetch),
1437    FetchOk(FetchOk),
1438    PublishSkipped(PublishSkipped),
1439}
1440
1441// Draft-20 has no range check on a control message, and the absence is the
1442// draft's rather than an omission here.
1443//
1444// Draft-19 carried one: its FETCH held a `Start Location` and an `End Location`
1445// inline, and draft-19 Section 10.12.3 said "End Location MUST specify the
1446// same or a larger Location than Start Location for Standalone and Absolute
1447// Joining
1448// Fetches". Draft-20 deleted both fields with the rest of the FETCH rewrite
1449// (Section 10.13), so there is no pair left in any message to compare.
1450//
1451// What replaced them cannot express the malformation either. A `LOCATION_FILTER`
1452// (Section 5.1.2) states its end as an unsigned `EndGroupDelta` added to
1453// `StartGroup`, so the end group can never precede the start group; and within
1454// one group draft-20 states no rule about an `EndObject` below `StartObject`.
1455// Section 5.1.2 says the opposite for subscriptions — "A Location Filter on a
1456// subscription is always valid, even if it specifies a range entirely before
1457// Largest Object" — so refusing one would close sessions over a sentence that
1458// is not there.
1459//
1460// The one backwards-range rule draft-20 does keep is in Section 10.14: "If End
1461// Location is smaller than the Start Location in the corresponding FETCH the
1462// receiver MUST close the session with a PROTOCOL_VIOLATION." It compares a
1463// FETCH_OK against the FETCH it answers, which is session state and not
1464// anything one frame holds, so it belongs to the caller.
1465
1466/// Refuse a message whose discriminator disagrees with the fields beside it.
1467///
1468/// One draft-20 message carries a field that says which of the following fields
1469/// are on the wire: REQUEST_ERROR's Error Code, whose REDIRECT value (0x34) is
1470/// what puts the Redirect structure on the wire. This codec holds the
1471/// alternative in an `Option`, so a value can say one thing in its
1472/// discriminator and another in its body, and the two sides of the codec
1473/// resolve that differently — the encoder writes whatever the body holds, and
1474/// the decoder reads whatever the discriminator announces.
1475///
1476/// A REQUEST_ERROR with code REDIRECT and no Redirect body encodes to a message
1477/// that ends where the decoder expects a Connect URI length, so the peer reads
1478/// the redirect out of whatever follows or runs off the end. The mirror case is
1479/// quieter and no better: a Redirect body under any other error code is written
1480/// out and then skipped by a decoder that was never told to look for it, so the
1481/// sender believes it redirected a peer that never saw a redirect.
1482///
1483/// Draft-19 had a second discriminator here, FETCH's `Fetch Type`, choosing
1484/// between a standalone body and a joining pair. Draft-20 deleted the field and
1485/// both bodies (Section 10.13), so FETCH has nothing left to disagree with
1486/// itself about.
1487///
1488/// Refusing at the encoder keeps the two readings from ever diverging on the
1489/// wire.
1490fn check_discriminators(message: &ControlMessage) -> Result<(), CodecError> {
1491    // One arm, where drafts 17 to 19 have two. Written as an `if let` rather
1492    // than a one-armed `match` because that is what it now is; a second
1493    // discriminator would restore the `match`.
1494    if let ControlMessage::RequestError(m) = message {
1495        let code_is_redirect = m.error_code.into_inner() == request_error_codes::REDIRECT;
1496        if code_is_redirect != m.redirect.is_some() {
1497            return Err(CodecError::InvalidField);
1498        }
1499    }
1500    Ok(())
1501}
1502
1503/// Whether draft-20 lets Message Parameter `key` appear in `message`.
1504///
1505/// Section 10.2.1: "Each Message Parameter definition indicates the message
1506/// types in which it can appear. If it appears in some other type of message,
1507/// the receiving endpoint MUST close the connection with a PROTOCOL_VIOLATION."
1508/// One arm per entry in the Message Parameters registry (Section 15.7),
1509/// carrying the message types that entry's own definition names.
1510///
1511/// Four things about this draft the arms below fold in:
1512///
1513/// * Six of the names are one wire type. Section 10.5: "This document uses the
1514///   shorthand PUBLISH_OK, REQUEST_UPDATE_OK, TRACK_STATUS_OK,
1515///   SUBSCRIBE_NAMESPACE_OK, SUBSCRIBE_TRACKS_OK and PUBLISH_NAMESPACE_OK to
1516///   refer to a REQUEST_OK sent in response to the corresponding request type".
1517///   Which one a given REQUEST_OK is depends on the request its Request ID
1518///   answers, which is session state and not in the frame, so each of those
1519///   names widens the same arm and a REQUEST_OK is held to their union.
1520/// * The five Range Filters state their scope in Section 5.1.4 — draft-19's
1521///   Section 5.1.3 — rather than in their own subsections: the Track Property
1522///   filter "MAY appear multiple times in a SUBSCRIBE_TRACKS message or
1523///   REQUEST_UPDATE for it", and "all other filter parameters MAY appear
1524///   multiple times in a FETCH, SUBSCRIBE, SUBSCRIBE_TRACKS, or REQUEST_UPDATE
1525///   (on a subscription, from the subscriber only) message". Draft-19 listed
1526///   PUBLISH_OK in that second sentence and draft-20 removed it.
1527/// * SUBSCRIBE_TRACKS inherits SUBSCRIBE's whole set. Section 10.20.1 — the
1528///   renumbering of draft-19's 10.19.1 — keeps the sentence verbatim: "Any
1529///   Parameter that can be specified on a Subscription (ie: in SUBSCRIBE) is
1530///   valid in SUBSCRIBE_TRACKS, unless otherwise specified."
1531/// * **`PUBLISH_OK` is gone from six definitions.** `OBJECT_DELIVERY_TIMEOUT`
1532///   (0x02), `SUBGROUP_DELIVERY_TIMEOUT` (0x06), `FORWARD` (0x10),
1533///   `SUBSCRIBER_PRIORITY` (0x20), `LOCATION_FILTER` (0x21) and
1534///   `NEW_GROUP_REQUEST` (0x32) each dropped it, and several gained `PUBLISH`
1535///   instead; the Range Filters dropped it via Section 5.1.4. `EXPIRES` (0x08)
1536///   is the only parameter that still names it. A subscriber that wants to
1537///   change something now sends a REQUEST_UPDATE after the PUBLISH_OK, and
1538///   sending any of the six on a PUBLISH_OK is a Section 10.2.1 violation.
1539///   Because PUBLISH_OK and REQUEST_OK are one wire type, this table cannot
1540///   see the difference: `M::RequestOk` is admitted wherever any of the six OK
1541///   names is, so the practical effect here is that the six lose their
1542///   `M::RequestOk` arm entirely.
1543///
1544/// FETCH_OK has no arm in the table below, and that is the draft's doing rather
1545/// than an omission here: Section 10.14 gives it a Parameters field and no
1546/// parameter definition names it, so every type this draft defines is "some
1547/// other type of message" there.
1548///
1549/// PUBLISH_STATE_NOTIFY is admitted by exactly three parameters, and treating
1550/// that list as closed is **a decision this codec makes**. Section 10.10 says
1551/// only "The semantics of each parameter, including whether it may appear in
1552/// PUBLISH_STATE_NOTIFY, are defined by the parameter", and `LARGEST_OBJECT`
1553/// (0x09), `FORWARD` (0x10) and `LOCATION_FILTER` (0x21) are the three whose
1554/// definitions name it. The draft implies the closure and never states it, so
1555/// anything else there is refused under Section 10.2.1 on that reading.
1556///
1557/// The table decides scope only. A type this draft does not define has no scope
1558/// to be outside of and is answered by [`CodecError::UnknownMessageParameter`],
1559/// which is why the final arm carries rather than refuses.
1560pub fn parameter_in_scope(key: u64, message: MessageType) -> bool {
1561    use MessageType as M;
1562    // Section 10.20.1 makes SUBSCRIBE_TRACKS a superset of SUBSCRIBE, so every
1563    // arm admitting one admits the other. The arms spell both out rather than
1564    // wrapping the call, so each still reads against its own sentence.
1565    match key {
1566        // Section 10.2.4 OBJECT_DELIVERY_TIMEOUT: "It MAY appear in a
1567        // SUBSCRIBE, PUBLISH, or REQUEST_UPDATE message." Draft-19 said
1568        // PUBLISH_OK where this says PUBLISH.
1569        0x02 => {
1570            matches!(message, M::Subscribe | M::Publish | M::RequestUpdate | M::SubscribeTracks)
1571        }
1572        // Section 10.2.2 AUTHORIZATION TOKEN: "It MAY appear in a PUBLISH,
1573        // SUBSCRIBE, REQUEST_UPDATE, SUBSCRIBE_NAMESPACE, SUBSCRIBE_TRACKS,
1574        // PUBLISH_NAMESPACE, TRACK_STATUS or FETCH message." Unchanged from
1575        // draft-19; what draft-20 added is the sentence after it, "This
1576        // Parameter MUST NOT be copied from a SUBSCRIBE_TRACKS to the resulting
1577        // PUBLISH message Parameters", which is a rule about two messages and
1578        // so belongs to the caller rather than to this table.
1579        0x03 => matches!(
1580            message,
1581            M::Publish
1582                | M::Subscribe
1583                | M::RequestUpdate
1584                | M::SubscribeNamespace
1585                | M::SubscribeTracks
1586                | M::PublishNamespace
1587                | M::TrackStatus
1588                | M::Fetch
1589        ),
1590        // Section 10.2.6 RENDEZVOUS TIMEOUT: it "MAY appear in a SUBSCRIBE
1591        // message".
1592        0x04 => matches!(message, M::Subscribe | M::SubscribeTracks),
1593        // Section 10.2.3 SUBGROUP_DELIVERY_TIMEOUT: "It MAY appear in a
1594        // SUBSCRIBE, PUBLISH, or REQUEST_UPDATE message." Draft-19 said
1595        // PUBLISH_OK where this says PUBLISH.
1596        0x06 => {
1597            matches!(message, M::Subscribe | M::Publish | M::RequestUpdate | M::SubscribeTracks)
1598        }
1599        // Section 10.2.16 EXPIRES: "It MAY appear in SUBSCRIBE_OK, PUBLISH,
1600        // PUBLISH_OK, SUBSCRIBE_NAMESPACE_OK, SUBSCRIBE_TRACKS_OK,
1601        // PUBLISH_NAMESPACE_OK, or REQUEST_UPDATE_OK." Five of those seven are
1602        // a REQUEST_OK. The one parameter that still names PUBLISH_OK.
1603        0x08 => matches!(message, M::SubscribeOk | M::Publish | M::RequestOk),
1604        // Section 10.2.17 LARGEST OBJECT: "It MAY appear in SUBSCRIBE_OK,
1605        // PUBLISH, REQUEST_UPDATE_OK, TRACK_STATUS_OK, or
1606        // PUBLISH_STATE_NOTIFY." The last is new in draft-20.
1607        0x09 => {
1608            matches!(message, M::SubscribeOk | M::Publish | M::RequestOk | M::PublishStateNotify)
1609        }
1610        // Section 10.2.5 FILL TIMEOUT: it "MAY appear in a FETCH message, or
1611        // inside a FILL_PARAMETERS parameter (see Section 10.2.15) in a
1612        // SUBSCRIBE or REQUEST_UPDATE (for a subscription), where it applies to
1613        // the fill fetch stream." The nested half is not a scope this table can
1614        // answer — a nested parameter is not in the enclosing message at all,
1615        // per Section 10.2.15 — so it is enforced by
1616        // [`decode_fill_parameters`] against Table 6 instead.
1617        0x0A => matches!(message, M::Fetch),
1618        // Section 10.2.18 FORWARD: "It MAY appear in SUBSCRIBE, REQUEST_UPDATE
1619        // (for a subscription or a SUBSCRIBE_TRACKS request), PUBLISH,
1620        // SUBSCRIBE_TRACKS and PUBLISH_STATE_NOTIFY." Draft-19 listed
1621        // PUBLISH_OK and had no PUBLISH_STATE_NOTIFY.
1622        0x10 => matches!(
1623            message,
1624            M::Subscribe
1625                | M::RequestUpdate
1626                | M::Publish
1627                | M::SubscribeTracks
1628                | M::PublishStateNotify
1629        ),
1630        // Section 10.2.7 SUBSCRIBER PRIORITY: "It MAY appear in a SUBSCRIBE,
1631        // PUBLISH, FETCH, or REQUEST_UPDATE (for a subscription or FETCH)."
1632        // Draft-19 said PUBLISH_OK where this says PUBLISH.
1633        0x20 => matches!(
1634            message,
1635            M::Subscribe | M::Publish | M::Fetch | M::RequestUpdate | M::SubscribeTracks
1636        ),
1637        // Section 10.2.9 LOCATION FILTER: "It MAY appear in a FETCH, SUBSCRIBE,
1638        // PUBLISH, REQUEST_UPDATE (for a subscription) or PUBLISH_STATE_NOTIFY
1639        // message." Draft-19 admitted SUBSCRIBE, PUBLISH_OK and REQUEST_UPDATE
1640        // and no FETCH, because a draft-19 FETCH carried its range in the
1641        // message instead.
1642        0x21 => matches!(
1643            message,
1644            M::Fetch
1645                | M::Subscribe
1646                | M::Publish
1647                | M::RequestUpdate
1648                | M::PublishStateNotify
1649                | M::SubscribeTracks
1650        ),
1651        // Section 10.2.8 GROUP ORDER: "It MAY appear in a SUBSCRIBE, PUBLISH,
1652        // SUBSCRIBE_TRACKS, or FETCH, or inside a FILL_PARAMETERS parameter".
1653        // The nested half is Table 6's, as for FILL_TIMEOUT above.
1654        0x22 => matches!(message, M::Subscribe | M::Publish | M::SubscribeTracks | M::Fetch),
1655        // Section 10.2.15 FILL_PARAMETERS, new in draft-20: it "MAY appear in a
1656        // SUBSCRIBE or REQUEST_UPDATE (for a subscription) message."
1657        //
1658        // SUBSCRIBE_TRACKS is admitted on top of those two, and the draft says
1659        // it twice over: Section 10.20.1's "Any Parameter that can be specified
1660        // on a Subscription (ie: in SUBSCRIBE) is valid in SUBSCRIBE_TRACKS,
1661        // unless otherwise specified", and the same section's closing sentence,
1662        // "To join Tracks initiated via the resulting PUBLISHes, the subscriber
1663        // can specify a Location Filter and optionally include
1664        // FILL_PARAMETERS". Section 10.2.15's own list is the "unless otherwise
1665        // specified" clause read strictly, and the two readings disagree. This
1666        // takes the wider one: a rule that ends sessions should be wrong in the
1667        // direction of carrying the parameter, and Section 10.20.1 names this
1668        // message outright.
1669        //
1670        // FETCH is refused, and that is the case the corpus pins: a fill fetch
1671        // stream is something a subscription opens, and a FETCH already is one.
1672        0x23 => matches!(message, M::Subscribe | M::RequestUpdate | M::SubscribeTracks),
1673        // Section 5.1.4: "All other filter parameters MAY appear multiple times
1674        // in a FETCH, SUBSCRIBE, SUBSCRIBE_TRACKS, or REQUEST_UPDATE (on a
1675        // subscription, from the subscriber only) message." SUBGROUP_FILTER
1676        // (Section 10.2.10), OBJECTID_FILTER (10.2.11), PRIORITY_FILTER
1677        // (10.2.12) and OBJECT_PROPERTY_FILTER (10.2.13) are those four.
1678        // Draft-19's sentence also listed PUBLISH_OK.
1679        0x25..=0x28 => {
1680            matches!(message, M::Fetch | M::Subscribe | M::SubscribeTracks | M::RequestUpdate)
1681        }
1682        // Section 5.1.4, of TRACK_PROPERTY_FILTER (Section 10.2.14) alone: it
1683        // "MAY appear multiple times in a SUBSCRIBE_TRACKS message or
1684        // REQUEST_UPDATE for it". It selects tracks rather than objects, which
1685        // is why it is the one filter a SUBSCRIBE may not carry and the one
1686        // Table 6 keeps out of FILL_PARAMETERS.
1687        0x29 => matches!(message, M::SubscribeTracks | M::RequestUpdate),
1688        // Section 10.2.19 NEW GROUP REQUEST: "It MAY appear in SUBSCRIBE or
1689        // REQUEST_UPDATE for a subscription." Draft-19 also listed PUBLISH_OK.
1690        0x32 => matches!(message, M::Subscribe | M::RequestUpdate | M::SubscribeTracks),
1691        // Section 10.2.20 TRACK_NAMESPACE_PREFIX: "It MAY appear in
1692        // REQUEST_UPDATE for a SUBSCRIBE_NAMESPACE or SUBSCRIBE_TRACKS
1693        // request." The two named there are the request being updated, not two
1694        // more places the parameter may be written.
1695        0x34 => matches!(message, M::RequestUpdate),
1696        // Section 10.2.21 INCLUDE_PROPERTIES, new in draft-20: "It MAY appear
1697        // in SUBSCRIBE, TRACK_STATUS, FETCH or SUBSCRIBE_TRACKS."
1698        0x35 => matches!(message, M::Subscribe | M::TrackStatus | M::Fetch | M::SubscribeTracks),
1699        _ => true,
1700    }
1701}
1702
1703/// Refuse a message carrying a Message Parameter its own definition does not
1704/// place there.
1705///
1706/// Section 10.2.1 answers this with a close, which the drafts below do not.
1707/// Draft-16 Section 9.2.2, and drafts 07 through 15 under the older name
1708/// Version Specific Parameters, end the same sentence "it MUST be ignored" —
1709/// so this check belongs to drafts 17, 18 and 19 and to no draft before them.
1710///
1711/// Applied on both sides. A parameter outside its scope is one the peer must
1712/// close the session over, so writing one is a way to end a session rather than
1713/// a way to ask for anything.
1714fn check_parameter_scope(message: &ControlMessage) -> Result<(), CodecError> {
1715    let parameters = match message {
1716        ControlMessage::RequestOk(m) => &m.parameters,
1717        ControlMessage::Subscribe(m) => &m.parameters,
1718        ControlMessage::SubscribeOk(m) => &m.parameters,
1719        ControlMessage::RequestUpdate(m) => &m.parameters,
1720        ControlMessage::Publish(m) => &m.parameters,
1721        ControlMessage::PublishStateNotify(m) => &m.parameters,
1722        ControlMessage::PublishNamespace(m) => &m.parameters,
1723        ControlMessage::SubscribeNamespace(m) => &m.parameters,
1724        ControlMessage::SubscribeTracks(m) => &m.parameters,
1725        ControlMessage::TrackStatus(m) => &m.parameters,
1726        ControlMessage::Fetch(m) => &m.parameters,
1727        ControlMessage::FetchOk(m) => &m.parameters,
1728        // No Message Parameters field. SETUP is named here rather than left to
1729        // a wildcard because the draft says why it can never have one: Section
1730        // 10.2.1 notes that "since Setup Options use a separate namespace, it
1731        // is impossible for Message Parameters to appear in Setup messages",
1732        // and this codec keeps the two namespaces in separate fields.
1733        ControlMessage::Setup(_)
1734        | ControlMessage::GoAway(_)
1735        | ControlMessage::RequestError(_)
1736        | ControlMessage::PublishDone(_)
1737        | ControlMessage::Namespace(_)
1738        | ControlMessage::NamespaceDone(_)
1739        | ControlMessage::PublishSkipped(_) => return Ok(()),
1740    };
1741
1742    let message_type = message.message_type();
1743    for parameter in parameters {
1744        let key = parameter.key.into_inner();
1745        if !parameter_in_scope(key, message_type) {
1746            return Err(CodecError::ParameterOutOfScope { key, message_type: message_type.id() });
1747        }
1748    }
1749    Ok(())
1750}
1751
1752impl ControlMessage {
1753    pub fn encode(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
1754        check_discriminators(self)?;
1755        check_parameter_scope(self)?;
1756        let mut body = Vec::with_capacity(256);
1757        self.encode_body(&mut body)?;
1758
1759        if body.len() > MAX_MESSAGE_LENGTH {
1760            return Err(CodecError::MessageTooLong(body.len()));
1761        }
1762
1763        let msg_type = self.message_type();
1764        VarInt::from_usize(msg_type.id() as usize).encode_moqt::<Wire>(buf);
1765        // Draft-20: 16-bit length (big-endian)
1766        buf.put_u16(body.len() as u16);
1767        buf.put_slice(&body);
1768        Ok(())
1769    }
1770
1771    pub fn decode(buf: &mut impl Buf) -> Result<Self, CodecError> {
1772        let type_id = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
1773        let msg_type =
1774            MessageType::from_id(type_id).ok_or(CodecError::UnknownMessageType(type_id))?;
1775        // Draft-20: 16-bit length (big-endian)
1776        if buf.remaining() < 2 {
1777            return Err(CodecError::UnexpectedEnd);
1778        }
1779        let body_len = buf.get_u16() as usize;
1780        if buf.remaining() < body_len {
1781            return Err(CodecError::UnexpectedEnd);
1782        }
1783        let body_bytes = buf.copy_to_bytes(body_len);
1784        let mut body = &body_bytes[..];
1785        let msg = match Self::decode_body(msg_type, &mut body) {
1786            Ok(msg) => msg,
1787            // The fields wanted more bytes than the Length allowed. This buffer
1788            // is already bounded by that Length, so running out inside it cannot
1789            // mean the message is still arriving - which is what the same error
1790            // means everywhere else, and why a reader loops on it rather than
1791            // closing. Here there is nothing left to arrive.
1792            Err(
1793                CodecError::UnexpectedEnd
1794                | CodecError::Kvp(crate::kvp::KvpError::UnexpectedEnd)
1795                | CodecError::Kvp(crate::kvp::KvpError::VarInt(
1796                    crate::varint::VarIntError::UnexpectedEnd,
1797                ))
1798                | CodecError::VarInt(crate::varint::VarIntError::UnexpectedEnd),
1799            ) => {
1800                return Err(CodecError::ControlMessageLengthMismatch {
1801                    declared: body_len,
1802                    detail: "its fields ran past the end",
1803                });
1804            }
1805            Err(e) => return Err(e),
1806        };
1807        check_parameter_scope(&msg)?;
1808        // Draft-20 Section 10: "If the length does not match the length of the
1809        // Message Body, the receiver MUST close the session with a
1810        // PROTOCOL_VIOLATION." A body parser that stops short leaves bytes
1811        // here; without this the surplus is discarded and a truncated or
1812        // mis-framed field looks like a well-formed message.
1813        if body.has_remaining() {
1814            return Err(CodecError::ControlMessageLengthMismatch {
1815                declared: body_len,
1816                detail: "its fields left bytes unread",
1817            });
1818        }
1819        Ok(msg)
1820    }
1821
1822    fn encode_body(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
1823        match self {
1824            ControlMessage::Setup(m) => {
1825                encode_setup_options(&m.options, buf)?;
1826            }
1827            ControlMessage::GoAway(m) => {
1828                if m.new_session_uri.len() > MAX_GOAWAY_URI_LENGTH {
1829                    return Err(CodecError::GoAwayUriTooLong);
1830                }
1831                VarInt::from_usize(m.new_session_uri.len()).encode_moqt::<Wire>(buf);
1832                buf.put_slice(&m.new_session_uri);
1833                m.timeout.encode_moqt::<Wire>(buf);
1834            }
1835            ControlMessage::RequestOk(m) => {
1836                encode_parameters(&m.parameters, buf)?;
1837                encode_track_properties(&m.track_properties, buf)?;
1838            }
1839            ControlMessage::RequestError(m) => {
1840                if m.reason_phrase.len() > MAX_REASON_PHRASE_LENGTH {
1841                    return Err(CodecError::ReasonPhraseTooLong);
1842                }
1843                m.error_code.encode_moqt::<Wire>(buf);
1844                m.retry_interval.encode_moqt::<Wire>(buf);
1845                VarInt::from_usize(m.reason_phrase.len()).encode_moqt::<Wire>(buf);
1846                buf.put_slice(&m.reason_phrase);
1847                if let Some(r) = &m.redirect {
1848                    r.track_namespace.validate_moqt()?;
1849                    check_full_track_name(&r.track_namespace, &r.track_name)?;
1850                    VarInt::from_usize(r.connect_uri.len()).encode_moqt::<Wire>(buf);
1851                    buf.put_slice(&r.connect_uri);
1852                    r.track_namespace.encode_moqt::<Wire>(buf);
1853                    VarInt::from_usize(r.track_name.len()).encode_moqt::<Wire>(buf);
1854                    buf.put_slice(&r.track_name);
1855                }
1856            }
1857            ControlMessage::Subscribe(m) => {
1858                m.track_namespace.validate_moqt()?;
1859                check_full_track_name(&m.track_namespace, &m.track_name)?;
1860                m.request_id.encode_moqt::<Wire>(buf);
1861                m.track_namespace.encode_moqt::<Wire>(buf);
1862                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1863                buf.put_slice(&m.track_name);
1864                encode_parameters(&m.parameters, buf)?;
1865            }
1866            ControlMessage::SubscribeOk(m) => {
1867                m.track_alias.encode_moqt::<Wire>(buf);
1868                encode_parameters(&m.parameters, buf)?;
1869                encode_track_properties(&m.track_properties, buf)?;
1870            }
1871            ControlMessage::RequestUpdate(m) => {
1872                m.request_id.encode_moqt::<Wire>(buf);
1873                encode_parameters(&m.parameters, buf)?;
1874            }
1875            ControlMessage::Publish(m) => {
1876                m.track_namespace.validate_moqt()?;
1877                check_full_track_name(&m.track_namespace, &m.track_name)?;
1878                m.request_id.encode_moqt::<Wire>(buf);
1879                m.track_namespace.encode_moqt::<Wire>(buf);
1880                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1881                buf.put_slice(&m.track_name);
1882                m.track_alias.encode_moqt::<Wire>(buf);
1883                encode_parameters(&m.parameters, buf)?;
1884                encode_track_properties(&m.track_properties, buf)?;
1885            }
1886            // Section 10.10, Figure 13: parameter count, then parameters,
1887            // and nothing else. No Request ID — the subscription's stream is
1888            // what identifies the message.
1889            ControlMessage::PublishStateNotify(m) => {
1890                encode_parameters(&m.parameters, buf)?;
1891            }
1892            ControlMessage::PublishDone(m) => {
1893                if m.reason_phrase.len() > MAX_REASON_PHRASE_LENGTH {
1894                    return Err(CodecError::ReasonPhraseTooLong);
1895                }
1896                m.status_code.encode_moqt::<Wire>(buf);
1897                m.stream_count.encode_moqt::<Wire>(buf);
1898                VarInt::from_usize(m.reason_phrase.len()).encode_moqt::<Wire>(buf);
1899                buf.put_slice(&m.reason_phrase);
1900            }
1901            ControlMessage::PublishNamespace(m) => {
1902                m.track_namespace.validate_moqt()?;
1903                m.request_id.encode_moqt::<Wire>(buf);
1904                m.track_namespace.encode_moqt::<Wire>(buf);
1905                encode_parameters(&m.parameters, buf)?;
1906            }
1907            ControlMessage::Namespace(m) => {
1908                m.namespace_suffix.validate_moqt()?;
1909                m.namespace_suffix.encode_moqt::<Wire>(buf);
1910            }
1911            ControlMessage::NamespaceDone(m) => {
1912                m.namespace_suffix.validate_moqt()?;
1913                m.namespace_suffix.encode_moqt::<Wire>(buf);
1914            }
1915            ControlMessage::SubscribeNamespace(m) => {
1916                m.namespace_prefix.validate_moqt()?;
1917                m.request_id.encode_moqt::<Wire>(buf);
1918                m.namespace_prefix.encode_moqt::<Wire>(buf);
1919                encode_parameters(&m.parameters, buf)?;
1920            }
1921            ControlMessage::SubscribeTracks(m) => {
1922                m.namespace_prefix.validate_moqt()?;
1923                m.request_id.encode_moqt::<Wire>(buf);
1924                m.namespace_prefix.encode_moqt::<Wire>(buf);
1925                encode_parameters(&m.parameters, buf)?;
1926            }
1927            ControlMessage::TrackStatus(m) => {
1928                m.track_namespace.validate_moqt()?;
1929                check_full_track_name(&m.track_namespace, &m.track_name)?;
1930                m.request_id.encode_moqt::<Wire>(buf);
1931                m.track_namespace.encode_moqt::<Wire>(buf);
1932                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1933                buf.put_slice(&m.track_name);
1934                encode_parameters(&m.parameters, buf)?;
1935            }
1936            // Section 10.13, Figure 16. Byte-identical to SUBSCRIBE above:
1937            // no Fetch Type, no inline range, and the namespace and name where
1938            // draft-19 put them inside its Standalone Fetch.
1939            ControlMessage::Fetch(m) => {
1940                m.track_namespace.validate_moqt()?;
1941                check_full_track_name(&m.track_namespace, &m.track_name)?;
1942                m.request_id.encode_moqt::<Wire>(buf);
1943                m.track_namespace.encode_moqt::<Wire>(buf);
1944                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1945                buf.put_slice(&m.track_name);
1946                encode_parameters(&m.parameters, buf)?;
1947            }
1948            ControlMessage::FetchOk(m) => {
1949                buf.put_u8(m.end_of_track);
1950                m.end_group.encode_moqt::<Wire>(buf);
1951                m.end_object.encode_moqt::<Wire>(buf);
1952                encode_parameters(&m.parameters, buf)?;
1953                encode_track_properties(&m.track_properties, buf)?;
1954            }
1955            ControlMessage::PublishSkipped(m) => {
1956                m.namespace_suffix.validate_moqt()?;
1957                check_full_track_name(&m.namespace_suffix, &m.track_name)?;
1958                m.namespace_suffix.encode_moqt::<Wire>(buf);
1959                VarInt::from_usize(m.track_name.len()).encode_moqt::<Wire>(buf);
1960                buf.put_slice(&m.track_name);
1961            }
1962        }
1963        Ok(())
1964    }
1965
1966    fn decode_body(msg_type: MessageType, buf: &mut impl Buf) -> Result<Self, CodecError> {
1967        match msg_type {
1968            MessageType::Setup => {
1969                let options = decode_setup_options(buf)?;
1970                Ok(ControlMessage::Setup(Setup { options }))
1971            }
1972            MessageType::GoAway => {
1973                let uri_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
1974                // Draft-20 Section 10.4: an endpoint that receives a New
1975                // Session URI Length above the maximum MUST close the session
1976                // with a PROTOCOL_VIOLATION. Checked here as well as on encode
1977                // so an oversized URI never reaches the application.
1978                if uri_len > MAX_GOAWAY_URI_LENGTH {
1979                    return Err(CodecError::GoAwayUriTooLong);
1980                }
1981                let uri = read_bytes(buf, uri_len)?;
1982                let timeout = VarInt::decode_moqt::<Wire>(buf)?;
1983                Ok(ControlMessage::GoAway(GoAway { new_session_uri: uri, timeout }))
1984            }
1985            MessageType::RequestOk => {
1986                let parameters = decode_parameters(buf)?;
1987                let track_properties = decode_track_properties(buf)?;
1988                Ok(ControlMessage::RequestOk(RequestOk { parameters, track_properties }))
1989            }
1990            MessageType::RequestError => {
1991                let error_code = VarInt::decode_moqt::<Wire>(buf)?;
1992                let retry_interval = VarInt::decode_moqt::<Wire>(buf)?;
1993                let reason_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
1994                // Draft-20 Section 1.4.4: a received reason phrase length above
1995                // the maximum MUST close the session with a PROTOCOL_VIOLATION.
1996                if reason_len > MAX_REASON_PHRASE_LENGTH {
1997                    return Err(CodecError::ReasonPhraseTooLong);
1998                }
1999                let reason_phrase = read_bytes(buf, reason_len)?;
2000                let redirect = if error_code.into_inner() == request_error_codes::REDIRECT {
2001                    let uri_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2002                    let connect_uri = read_bytes(buf, uri_len)?;
2003                    let track_namespace = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2004                    let name_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2005                    let track_name = read_bytes(buf, name_len)?;
2006                    check_full_track_name(&track_namespace, &track_name)?;
2007                    Some(Redirect { connect_uri, track_namespace, track_name })
2008                } else {
2009                    None
2010                };
2011                Ok(ControlMessage::RequestError(RequestError {
2012                    error_code,
2013                    retry_interval,
2014                    reason_phrase,
2015                    redirect,
2016                }))
2017            }
2018            MessageType::Subscribe => {
2019                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2020                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2021                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2022                let track_name = read_bytes(buf, tn_len)?;
2023                check_full_track_name(&track_namespace, &track_name)?;
2024                let parameters = decode_parameters(buf)?;
2025                Ok(ControlMessage::Subscribe(Subscribe {
2026                    request_id,
2027                    track_namespace,
2028                    track_name,
2029                    parameters,
2030                }))
2031            }
2032            MessageType::SubscribeOk => {
2033                let track_alias = VarInt::decode_moqt::<Wire>(buf)?;
2034                let parameters = decode_parameters(buf)?;
2035                let track_properties = decode_track_properties(buf)?;
2036                Ok(ControlMessage::SubscribeOk(SubscribeOk {
2037                    track_alias,
2038                    parameters,
2039                    track_properties,
2040                }))
2041            }
2042            MessageType::RequestUpdate => {
2043                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2044                let parameters = decode_parameters(buf)?;
2045                Ok(ControlMessage::RequestUpdate(RequestUpdate { request_id, parameters }))
2046            }
2047            MessageType::Publish => {
2048                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2049                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2050                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2051                let track_name = read_bytes(buf, tn_len)?;
2052                let track_alias = VarInt::decode_moqt::<Wire>(buf)?;
2053                check_full_track_name(&track_namespace, &track_name)?;
2054                let parameters = decode_parameters(buf)?;
2055                let track_properties = decode_track_properties(buf)?;
2056                Ok(ControlMessage::Publish(Publish {
2057                    request_id,
2058                    track_namespace,
2059                    track_name,
2060                    track_alias,
2061                    parameters,
2062                    track_properties,
2063                }))
2064            }
2065            MessageType::PublishStateNotify => {
2066                let parameters = decode_parameters(buf)?;
2067                Ok(ControlMessage::PublishStateNotify(PublishStateNotify { parameters }))
2068            }
2069            MessageType::PublishDone => {
2070                // The Status Code is carried up whatever it is. Section 14
2071                // forbids closing the session over an unknown one and requires
2072                // it to be read as INTERNAL_ERROR, so refusing the frame here
2073                // would take a choice away from the caller that the draft gives
2074                // it. See [`PublishDone::status_code`].
2075                let status_code = VarInt::decode_moqt::<Wire>(buf)?;
2076                let stream_count = VarInt::decode_moqt::<Wire>(buf)?;
2077                let reason_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2078                // Draft-20 Section 1.4.4, same bound as REQUEST_ERROR above.
2079                if reason_len > MAX_REASON_PHRASE_LENGTH {
2080                    return Err(CodecError::ReasonPhraseTooLong);
2081                }
2082                let reason_phrase = read_bytes(buf, reason_len)?;
2083                Ok(ControlMessage::PublishDone(PublishDone {
2084                    status_code,
2085                    stream_count,
2086                    reason_phrase,
2087                }))
2088            }
2089            MessageType::PublishNamespace => {
2090                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2091                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2092                let parameters = decode_parameters(buf)?;
2093                Ok(ControlMessage::PublishNamespace(PublishNamespace {
2094                    request_id,
2095                    track_namespace,
2096                    parameters,
2097                }))
2098            }
2099            MessageType::Namespace => {
2100                let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2101                Ok(ControlMessage::Namespace(Namespace { namespace_suffix }))
2102            }
2103            MessageType::NamespaceDone => {
2104                let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2105                Ok(ControlMessage::NamespaceDone(NamespaceDone { namespace_suffix }))
2106            }
2107            MessageType::SubscribeNamespace => {
2108                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2109                let namespace_prefix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2110                let parameters = decode_parameters(buf)?;
2111                Ok(ControlMessage::SubscribeNamespace(SubscribeNamespace {
2112                    request_id,
2113                    namespace_prefix,
2114                    parameters,
2115                }))
2116            }
2117            MessageType::SubscribeTracks => {
2118                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2119                let namespace_prefix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2120                let parameters = decode_parameters(buf)?;
2121                Ok(ControlMessage::SubscribeTracks(SubscribeTracks {
2122                    request_id,
2123                    namespace_prefix,
2124                    parameters,
2125                }))
2126            }
2127            MessageType::TrackStatus => {
2128                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2129                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2130                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2131                let track_name = read_bytes(buf, tn_len)?;
2132                check_full_track_name(&track_namespace, &track_name)?;
2133                let parameters = decode_parameters(buf)?;
2134                Ok(ControlMessage::TrackStatus(TrackStatus {
2135                    request_id,
2136                    track_namespace,
2137                    track_name,
2138                    parameters,
2139                }))
2140            }
2141            MessageType::Fetch => {
2142                let request_id = VarInt::decode_moqt::<Wire>(buf)?;
2143                let track_namespace = TrackNamespace::decode_moqt::<Wire>(buf)?;
2144                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2145                let track_name = read_bytes(buf, tn_len)?;
2146                check_full_track_name(&track_namespace, &track_name)?;
2147                let parameters = decode_parameters(buf)?;
2148                Ok(ControlMessage::Fetch(Fetch {
2149                    request_id,
2150                    track_namespace,
2151                    track_name,
2152                    parameters,
2153                }))
2154            }
2155            MessageType::FetchOk => {
2156                if buf.remaining() < 1 {
2157                    return Err(CodecError::UnexpectedEnd);
2158                }
2159                let end_of_track = buf.get_u8();
2160                let end_group = VarInt::decode_moqt::<Wire>(buf)?;
2161                let end_object = VarInt::decode_moqt::<Wire>(buf)?;
2162                let parameters = decode_parameters(buf)?;
2163                let track_properties = decode_track_properties(buf)?;
2164                Ok(ControlMessage::FetchOk(FetchOk {
2165                    end_of_track,
2166                    end_group,
2167                    end_object,
2168                    parameters,
2169                    track_properties,
2170                }))
2171            }
2172            MessageType::PublishSkipped => {
2173                let namespace_suffix = TrackNamespace::decode_allow_empty_moqt::<Wire>(buf)?;
2174                let tn_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
2175                let track_name = read_bytes(buf, tn_len)?;
2176                check_full_track_name(&namespace_suffix, &track_name)?;
2177                Ok(ControlMessage::PublishSkipped(PublishSkipped { namespace_suffix, track_name }))
2178            }
2179        }
2180    }
2181
2182    pub fn message_type(&self) -> MessageType {
2183        match self {
2184            ControlMessage::Setup(_) => MessageType::Setup,
2185            ControlMessage::GoAway(_) => MessageType::GoAway,
2186            ControlMessage::RequestOk(_) => MessageType::RequestOk,
2187            ControlMessage::RequestError(_) => MessageType::RequestError,
2188            ControlMessage::Subscribe(_) => MessageType::Subscribe,
2189            ControlMessage::SubscribeOk(_) => MessageType::SubscribeOk,
2190            ControlMessage::RequestUpdate(_) => MessageType::RequestUpdate,
2191            ControlMessage::Publish(_) => MessageType::Publish,
2192            ControlMessage::PublishStateNotify(_) => MessageType::PublishStateNotify,
2193            ControlMessage::PublishDone(_) => MessageType::PublishDone,
2194            ControlMessage::PublishNamespace(_) => MessageType::PublishNamespace,
2195            ControlMessage::Namespace(_) => MessageType::Namespace,
2196            ControlMessage::NamespaceDone(_) => MessageType::NamespaceDone,
2197            ControlMessage::SubscribeNamespace(_) => MessageType::SubscribeNamespace,
2198            ControlMessage::SubscribeTracks(_) => MessageType::SubscribeTracks,
2199            ControlMessage::TrackStatus(_) => MessageType::TrackStatus,
2200            ControlMessage::Fetch(_) => MessageType::Fetch,
2201            ControlMessage::FetchOk(_) => MessageType::FetchOk,
2202            ControlMessage::PublishSkipped(_) => MessageType::PublishSkipped,
2203        }
2204    }
2205}
2206
2207#[cfg(test)]
2208mod tests {
2209    use super::*;
2210
2211    /// Frame `body` as a draft-20 control message of `type_id`, declaring
2212    /// `declared_len` rather than the body's real length. Used to build the
2213    /// mismatched frame the length rule is about.
2214    fn frame_with_declared_len(type_id: u64, declared_len: u16, body: &[u8]) -> Vec<u8> {
2215        let mut out = Vec::new();
2216        VarInt::from_u64_moqt(type_id).encode_moqt::<Wire>(&mut out);
2217        out.put_u16(declared_len);
2218        out.put_slice(body);
2219        out
2220    }
2221
2222    fn frame(type_id: u64, body: &[u8]) -> Vec<u8> {
2223        frame_with_declared_len(type_id, body.len() as u16, body)
2224    }
2225
2226    /// A SUBSCRIBE body: request id 1, namespace ("a"), track name "b", and
2227    /// `params` already encoded.
2228    fn subscribe_body(params: &[u8]) -> Vec<u8> {
2229        let mut body = vec![0x01, 0x01, 0x01, b'a', 0x01, b'b'];
2230        body.extend_from_slice(params);
2231        body
2232    }
2233
2234    /// Draft-20 Section 10: "If the length does not match the length of the
2235    /// Message Body, the receiver MUST close the session with a
2236    /// PROTOCOL_VIOLATION."
2237    ///
2238    /// Without the trailing-byte check in `decode` this SUBSCRIBE parses and
2239    /// the two surplus bytes vanish:
2240    ///
2241    /// ```text
2242    /// assertion `left == right` failed
2243    ///   left: Ok(Subscribe(Subscribe { request_id: VarInt(1), track_namespace:
2244    ///         TrackNamespace([[97]]), track_name: [98], parameters: [] }))
2245    ///  right: Err(InvalidField)
2246    /// ```
2247    #[test]
2248    fn a_message_body_shorter_than_the_declared_length_is_refused() {
2249        let body = subscribe_body(&[0x00]);
2250        let mut junked = body.clone();
2251        junked.extend_from_slice(&[0xff, 0xff]);
2252        let bytes = frame_with_declared_len(0x03, (body.len() + 2) as u16, &junked);
2253
2254        let mut buf = &bytes[..];
2255        assert_eq!(
2256            ControlMessage::decode(&mut buf),
2257            Err(CodecError::ControlMessageLengthMismatch {
2258                declared: (body.len() + 2),
2259                detail: "its fields left bytes unread",
2260            })
2261        );
2262
2263        // The same body with an honest length still decodes, so the guard
2264        // rejects the mismatch and not the message.
2265        let honest = frame(0x03, &body);
2266        let mut buf = &honest[..];
2267        assert!(ControlMessage::decode(&mut buf).is_ok());
2268    }
2269
2270    /// Draft-20 Section 1.4.4: "The reason phrase length has a maximum value of
2271    /// 1024 bytes. If an endpoint receives a length exceeding the maximum, it
2272    /// MUST close the session with a PROTOCOL_VIOLATION".
2273    ///
2274    /// Without the decode-side bound the 2000-byte phrase is handed to the
2275    /// application:
2276    ///
2277    /// ```text
2278    /// assertion `left == right` failed
2279    ///   left: Ok(RequestError(RequestError { error_code: VarInt(1),
2280    ///         retry_interval: VarInt(0), reason_phrase: [120, 120, ...],
2281    ///         redirect: None }))
2282    ///  right: Err(ReasonPhraseTooLong)
2283    /// ```
2284    ///
2285    /// (The 2000 repeated bytes of the phrase are elided from that transcript.)
2286    #[test]
2287    fn an_over_long_reason_phrase_is_refused_on_decode() {
2288        for (type_id, prefix) in [(0x05u64, vec![0x01, 0x00]), (0x0B, vec![0x01, 0x00])] {
2289            let mut body = prefix;
2290            let over = MAX_REASON_PHRASE_LENGTH + 976;
2291            VarInt::from_usize(over).encode_moqt::<Wire>(&mut body);
2292            body.extend(std::iter::repeat_n(b'x', over));
2293            let bytes = frame(type_id, &body);
2294
2295            let mut buf = &bytes[..];
2296            assert_eq!(
2297                ControlMessage::decode(&mut buf),
2298                Err(CodecError::ReasonPhraseTooLong),
2299                "message type 0x{type_id:x}"
2300            );
2301        }
2302    }
2303
2304    /// Draft-20 Section 10.4: "The maximum length of the New Session URI is
2305    /// 8,192 bytes. If an endpoint receives a length exceeding the maximum, it
2306    /// MUST close the session with a PROTOCOL_VIOLATION."
2307    ///
2308    /// Without the decode-side bound the oversized URI reaches the application
2309    /// and a migrating endpoint follows it:
2310    ///
2311    /// ```text
2312    /// assertion `left == right` failed
2313    ///   left: Ok(GoAway(GoAway { new_session_uri: [117, 117, ...],
2314    ///         timeout: VarInt(0) }))
2315    ///  right: Err(GoAwayUriTooLong)
2316    /// ```
2317    ///
2318    /// (The 9000 repeated bytes of the URI are elided from that transcript.)
2319    #[test]
2320    fn an_over_long_goaway_uri_is_refused_on_decode() {
2321        let over = MAX_GOAWAY_URI_LENGTH + 808;
2322        let mut body = Vec::new();
2323        VarInt::from_usize(over).encode_moqt::<Wire>(&mut body);
2324        body.extend(std::iter::repeat_n(b'u', over));
2325        body.push(0x00); // timeout
2326        let bytes = frame(0x10, &body);
2327
2328        let mut buf = &bytes[..];
2329        assert_eq!(ControlMessage::decode(&mut buf), Err(CodecError::GoAwayUriTooLong));
2330    }
2331
2332    /// Draft-20 Section 10.2.8 (GROUP_ORDER): "The allowed values are Ascending
2333    /// (0x1) or Descending (0x2). If an endpoint receives a value outside this
2334    /// range, it MUST close the session with PROTOCOL_VIOLATION." Section
2335    /// 10.2.17 says the same of FORWARD with the values 0 and 1.
2336    ///
2337    /// Without `uint8_value_in_range` the out-of-range byte is handed up as an
2338    /// ordinary parameter:
2339    ///
2340    /// ```text
2341    /// assertion `left == right` failed
2342    ///   left: Ok(Subscribe(Subscribe { request_id: VarInt(1), track_namespace:
2343    ///         TrackNamespace([[97]]), track_name: [98], parameters:
2344    ///         [KeyValuePair { key: VarInt(34), value: Varint(VarInt(7)) }] }))
2345    ///  right: Err(InvalidField)
2346    /// ```
2347    #[test]
2348    fn a_uint8_parameter_outside_its_range_is_refused() {
2349        // key, rejected value, accepted value
2350        let cases = [(0x22u8, 7u8, 2u8), (0x10, 9, 1)];
2351        for (key, bad, good) in cases {
2352            let bytes = frame(0x03, &subscribe_body(&[0x01, key, bad]));
2353            let mut buf = &bytes[..];
2354            assert_eq!(
2355                ControlMessage::decode(&mut buf),
2356                Err(CodecError::ParameterValueOutOfRange { key: key as u64, value: bad as u64 }),
2357                "parameter 0x{key:x} value {bad}"
2358            );
2359
2360            let bytes = frame(0x03, &subscribe_body(&[0x01, key, good]));
2361            let mut buf = &bytes[..];
2362            assert!(
2363                ControlMessage::decode(&mut buf).is_ok(),
2364                "parameter 0x{key:x} value {good} should still decode"
2365            );
2366        }
2367    }
2368
2369    /// SUBSCRIBER_PRIORITY (0x20) is a uint8 with no restricted range, so it
2370    /// must keep accepting the whole 0-255 span. This is the negative half of
2371    /// the range check: a table that over-reached would fail here.
2372    #[test]
2373    fn subscriber_priority_still_accepts_the_whole_byte_range() {
2374        for value in [0u8, 1, 2, 128, 255] {
2375            let bytes = frame(0x03, &subscribe_body(&[0x01, 0x20, value]));
2376            let mut buf = &bytes[..];
2377            assert!(ControlMessage::decode(&mut buf).is_ok(), "priority {value}");
2378        }
2379    }
2380
2381    fn param(key: u64, value: &[u8]) -> KeyValuePair {
2382        KeyValuePair { key: VarInt::from_u64_moqt(key), value: KvpValue::Bytes(value.to_vec()) }
2383    }
2384
2385    /// Draft-20 Section 10.2.16: "The LARGEST_OBJECT parameter (Parameter Type
2386    /// 0x9) is a Location." Section 10.2 defines Location as "Two consecutive
2387    /// varints (Group, Object)" — the value carries no length of its own.
2388    ///
2389    /// The frame below is built from the draft rather than from this encoder:
2390    /// REQUEST_OK, four body bytes, one parameter, type delta `0x09`, then the
2391    /// two varints `0x0a` and `0x03` for Location (10, 3). A length-prefixed
2392    /// spelling would need a fifth byte.
2393    ///
2394    /// With `0x09` back in the Length-prefixed arm, the decoder reads the
2395    /// group varint `0x0a` as a value length of 10 and runs off the end of a
2396    /// four-byte body. Both this test and
2397    /// [`a_location_does_not_eat_the_block_that_follows_it`] fail with:
2398    ///
2399    /// ```text
2400    /// spec-correct frame must decode: UnexpectedEnd
2401    /// ```
2402    #[test]
2403    fn largest_object_is_two_bare_varints() {
2404        let body = [0x01, 0x09, 0x0a, 0x03];
2405        let bytes = frame(0x07, &body);
2406
2407        let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2408        let ControlMessage::RequestOk(ok) = &msg else {
2409            panic!("expected REQUEST_OK, got {msg:?}")
2410        };
2411        assert_eq!(ok.parameters, vec![param(0x09, &[0x0a, 0x03])]);
2412        assert!(ok.track_properties.is_empty(), "the four body bytes are all parameter");
2413
2414        let mut out = Vec::new();
2415        msg.encode(&mut out).expect("re-encode");
2416        assert_eq!(out, bytes, "the value must go back out as the two bare varints it came in as");
2417    }
2418
2419    /// A Location value the encoder was handed but the decoder could not read
2420    /// back is refused on the way out, not written.
2421    ///
2422    /// LARGEST_OBJECT carries no length of its own — that is the whole point
2423    /// of the encoding — so `encode_parameters` writes its bytes verbatim. A
2424    /// value built in memory rather than decoded is under no obligation to be
2425    /// two varints, and before this check the codec answered `Ok(())` and put
2426    /// a frame on the wire that `ControlMessage::decode` then refused. One
2427    /// varint short and one varint long are the two ways to get it wrong.
2428    ///
2429    /// # What it catches
2430    ///
2431    /// Dropping the `is_location_value` guard from this draft's encode arm,
2432    /// run:
2433    ///
2434    /// ```text
2435    /// panicked at crates\moqtap-codec\src\draft20\message.rs:1382:13:
2436    /// LARGEST_OBJECT of one varint must not encode: the decoder cannot read it back
2437    ///
2438    /// test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 108 filtered out
2439    /// ```
2440    ///
2441    /// The sibling draft kept its guard and kept passing, which is what shows
2442    /// the check is per-draft and not inherited from somewhere shared.
2443    #[test]
2444    fn a_location_value_that_is_not_two_varints_is_refused_on_encode() {
2445        for (label, value) in
2446            [("one varint", vec![0x0a]), ("three varints", vec![0x0a, 0x03, 0x05])]
2447        {
2448            let msg = ControlMessage::RequestOk(RequestOk {
2449                parameters: vec![param(0x09, &value)],
2450                track_properties: Vec::new(),
2451            });
2452            let mut out = Vec::new();
2453            assert!(
2454                msg.encode(&mut out).is_err(),
2455                "LARGEST_OBJECT of {label} must not encode: the decoder cannot read it back"
2456            );
2457        }
2458
2459        // The well-formed value still goes out, so the check refuses the
2460        // malformed case and not the encoding itself.
2461        let msg = ControlMessage::RequestOk(RequestOk {
2462            parameters: vec![param(0x09, &[0x0a, 0x03])],
2463            track_properties: Vec::new(),
2464        });
2465        let mut out = Vec::new();
2466        msg.encode(&mut out).expect("a Location of exactly two varints must still encode");
2467        ControlMessage::decode(&mut &out[..]).expect("and must decode back");
2468    }
2469
2470    /// The same Location read through a message that carries other fields
2471    /// after it, so a stray length byte cannot hide in a trailing block.
2472    ///
2473    /// SUBSCRIBE_OK is track alias `0x05`, then the parameters, then the track
2474    /// properties. With LARGEST_OBJECT (10, 3) and one property
2475    /// (OBJECT_DELIVERY_TIMEOUT, type `0x02`, 5000ms as the two-byte varint
2476    /// `0x93 0x88`), the body is `05 01 09 0a 03 02 93 88`.
2477    #[test]
2478    fn a_location_does_not_eat_the_block_that_follows_it() {
2479        let body = [0x05, 0x01, 0x09, 0x0a, 0x03, 0x02, 0x93, 0x88];
2480        let bytes = frame(0x04, &body);
2481
2482        let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2483        let ControlMessage::SubscribeOk(ok) = &msg else {
2484            panic!("expected SUBSCRIBE_OK, got {msg:?}")
2485        };
2486        assert_eq!(ok.parameters, vec![param(0x09, &[0x0a, 0x03])]);
2487        assert_eq!(
2488            ok.track_properties,
2489            vec![KeyValuePair {
2490                key: VarInt::from_u64_moqt(0x02),
2491                value: KvpValue::Varint(VarInt::from_u64_moqt(5000)),
2492            }]
2493        );
2494
2495        let mut out = Vec::new();
2496        msg.encode(&mut out).expect("re-encode");
2497        assert_eq!(out, bytes);
2498    }
2499
2500    /// Draft-20 Section 10.2.19: the TRACK_NAMESPACE_PREFIX parameter
2501    /// (Parameter Type 0x34) "uses the Track Namespace encoding described in
2502    /// Section 2.4.1" — a varint field count followed by that many
2503    /// length-prefixed fields, and nothing in front of it. That encoding is not
2504    /// one of the four Section 10.2 lists, so it cannot be assumed to be
2505    /// Length-prefixed by default.
2506    ///
2507    /// The frame below is built from Section 2.4.1: REQUEST_UPDATE for request
2508    /// `7`, one parameter, type delta `0x34`, then the namespace ("live",
2509    /// "sports") as `02 04 "live" 06 "sports"`. Sixteen body bytes; a
2510    /// length-prefixed spelling would need a seventeenth for the outer length.
2511    ///
2512    /// With `0x34` back in the Length-prefixed arm the field count `0x02` is
2513    /// read as an outer length of two bytes, leaving eleven bytes of namespace
2514    /// unread. Draft-20's Section 10 body-length check turns that into a
2515    /// refusal rather than a truncated value:
2516    ///
2517    /// ```text
2518    /// spec-correct frame must decode: InvalidField
2519    /// ```
2520    ///
2521    /// That check is not a safety net here. Where the surplus lands inside the
2522    /// declared body — as in
2523    /// [`an_empty_track_namespace_prefix_is_one_zero_byte`], whose namespace is
2524    /// one byte long — the misread is silent, and that test fails instead with:
2525    ///
2526    /// ```text
2527    /// assertion `left == right` failed
2528    ///   left: [KeyValuePair { key: VarInt(52), value: Bytes([]) }]
2529    ///  right: [KeyValuePair { key: VarInt(52), value: Bytes([0]) }]
2530    /// ```
2531    #[test]
2532    fn track_namespace_prefix_is_a_bare_track_namespace() {
2533        let namespace: Vec<u8> = [&[0x02, 0x04][..], b"live", &[0x06][..], b"sports"].concat();
2534        assert_eq!(namespace.len(), 13);
2535
2536        let body: Vec<u8> = [&[0x07, 0x01, 0x34][..], &namespace].concat();
2537        assert_eq!(body.len(), 16);
2538        let bytes = frame(0x02, &body);
2539
2540        let msg = ControlMessage::decode(&mut &bytes[..]).expect("spec-correct frame must decode");
2541        let ControlMessage::RequestUpdate(update) = &msg else {
2542            panic!("expected REQUEST_UPDATE, got {msg:?}")
2543        };
2544        assert_eq!(update.request_id.into_inner(), 7);
2545        assert_eq!(update.parameters, vec![param(0x34, &namespace)]);
2546
2547        let mut out = Vec::new();
2548        msg.encode(&mut out).expect("re-encode");
2549        assert_eq!(out, bytes, "no outer length may appear in front of the Track Namespace");
2550    }
2551
2552    /// An empty prefix is a legal Track Namespace: Section 2.4.1 puts one at
2553    /// "between 0 and 32 Track Namespace Fields". On the wire that is the
2554    /// single byte `0x00`, and it must not be confused with a length-prefixed
2555    /// value of zero bytes.
2556    #[test]
2557    fn an_empty_track_namespace_prefix_is_one_zero_byte() {
2558        let body = [0x07, 0x01, 0x34, 0x00];
2559        let bytes = frame(0x02, &body);
2560
2561        let msg = ControlMessage::decode(&mut &bytes[..]).expect("empty prefix must decode");
2562        let ControlMessage::RequestUpdate(update) = &msg else {
2563            panic!("expected REQUEST_UPDATE, got {msg:?}")
2564        };
2565        assert_eq!(update.parameters, vec![param(0x34, &[0x00])]);
2566
2567        let mut out = Vec::new();
2568        msg.encode(&mut out).expect("re-encode");
2569        assert_eq!(out, bytes);
2570    }
2571}