use bytes::Bytes; use super::Version; use crate::{ Error, coding::{Decoder, Encoder}, model::object::{Properties, Property, Value}, }; /// Draft-22 assigns property 0x06 to SUBGROUP_DELIVERY_TIMEOUT. pub(crate) fn has_delivery_timeout(version: Version) -> bool { !matches!(version, Version::Draft18) } /// Object status: no object at or past this location in the group exists. pub(crate) const END_OF_GROUP: u64 = 0x3; /// Object status: no object at or past this location exists (every implemented draft). pub(crate) const END_OF_TRACK: u64 = 0x4; /// Object property: how many Group IDs just below this object's never exist. const PRIOR_GROUP_ID_GAP: u64 = 0x3c; /// Object property: how many Object IDs just below this object's never exist. const PRIOR_OBJECT_ID_GAP: u64 = 0x3e; /// Object property (draft-lcurley-moq-timestamp): subtracted from `Group ID + Object ID` /// when consecutive objects share a decode timestamp (`dts = Group ID + Object ID - tie`). pub(crate) const TIMESTAMP_TIE: u64 = 0x40B72; /// Compute the wire `(object_id, timestamp_tie)` for a frame at `dts` in group `group_id` /// following `prior` (the previous frame's Object ID, if any), per draft-lcurley-moq-timestamp. /// /// Always satisfies `group_id + object_id - tie == dts` (modulo u64 saturation) and strictly /// increasing Object IDs within the group. pub(crate) const fn timestamp_object_id(group_id: u64, prior: Option, dts: u64) -> (u64, u64) { let min_oid = match prior { None => 0, Some(prev) => prev.saturating_add(1), }; let desired = dts.saturating_sub(group_id); let oid = if desired > min_oid { desired } else { min_oid }; let tie = group_id.saturating_add(oid).saturating_sub(dts); (oid, tie) } /// Whether the Object Status `status` is defined, 0 being Normal. pub(crate) fn status_defined(status: u64) -> bool { matches!(status, 0 | END_OF_GROUP | END_OF_TRACK) } /// Refuse properties on a status object, such as END_OF_GROUP, which may not carry any. #[cfg(feature = "async")] pub(super) fn check_status(properties: &Properties) -> Result<(), Error> { match properties.is_empty() { true => Ok(()), false => Err(Error::Session(crate::SessionError::ProtocolViolation)), } } pub(crate) struct Decoded { pub properties: Properties, /// The Prior Object ID Gap. pub gap: Option, /// The Prior Group ID Gap, which also stays in the block. pub group_gap: Option, pub inflated: Option, /// The Timestamp Tie (`0x40B72`), which also stays in the block. pub tie: Option, } /// The largest properties block an object may carry, which a relay forwards unchanged. pub(crate) const MAX_BLOCK: usize = super::group::MAX_OBJECT_EXTENSIONS; struct List { /// In arrival order. Values borrow the input. values: Vec, gap: Option, group_gap: Option, inflated: Option, sealed_inflated: Option, tie: Option, immutable: bool, } /// Parse a property list, `immutable` when it is the one Immutable Properties holds. fn list(data: &Bytes, version: Version, immutable: bool) -> Result { let mut decoder = Decoder::new(data, version.into()); let mut result = List { values: Vec::new(), gap: None, group_gap: None, inflated: None, sealed_inflated: None, tie: None, immutable: false, }; let mut previous = 0u64; while !decoder.is_empty() { let key = decoder.varint()?; let id = previous.checked_add(key).ok_or(Error::MalformedTrack)?; previous = id; let value = if id % 2 == 0 { let value = decoder.varint()?; let repeated = match id { PRIOR_OBJECT_ID_GAP => result.gap.replace(value).is_some(), PRIOR_GROUP_ID_GAP => result.group_gap.replace(value).is_some(), super::flate::INFLATED => result.inflated.replace(value).is_some(), TIMESTAMP_TIE => result.tie.replace(value).is_some(), _ => false, }; if repeated { return Err(Error::MalformedTrack); } Value::Int(value) } else { let bytes = decoder.bytes()?; if bytes.len() > u16::MAX as usize { return Err(Error::MalformedTrack); } let bytes = data.slice_ref(bytes); if id == 0x0b { if immutable || std::mem::replace(&mut result.immutable, true) { return Err(Error::MalformedTrack); } let nested = list(&bytes, version, true).map_err(|_| Error::MalformedTrack)?; result.sealed_inflated = nested.inflated; // Each appears once, inside the Immutable Properties or outside them. for (outer, inner) in [ (&mut result.inflated, nested.inflated), (&mut result.gap, nested.gap), (&mut result.group_gap, nested.group_gap), (&mut result.tie, nested.tie), ] { if let Some(value) = inner && outer.replace(value).is_some() { return Err(Error::MalformedTrack); } } } Value::Bytes(bytes) }; result.values.push(Property { id, value }); } Ok(result) } /// Serialize `values` as `version` does, in ascending ID order. Equal IDs keep their order. fn serialize<'a>(values: impl IntoIterator, version: Version) -> Result, Error> { let mut sorted: Vec<_> = values.into_iter().collect(); sorted.sort_by_key(|property| property.id); let mut out = Vec::new(); let mut encoder = Encoder::new(&mut out, version.into()); let mut previous = 0; for property in sorted { encoder.varint(property.id - previous)?; previous = property.id; match &property.value { Value::Int(value) => encoder.varint(*value)?, Value::Bytes(value) => encoder.bytes(value)?, } } Ok(out) } /// The properties our own object carries: an optional Prior Group ID Gap and/or Timestamp Tie. pub(crate) fn own_properties(group_gap: Option, tie: Option, version: Version) -> Result, Error> { let mut values = Vec::with_capacity(2); if let Some(gap) = group_gap { values.push(Property { id: PRIOR_GROUP_ID_GAP, value: Value::Int(gap), }); } if let Some(tie) = tie { values.push(Property { id: TIMESTAMP_TIE, value: Value::Int(tie), }); } if values.is_empty() { return Ok(Vec::new()); } serialize(&values, version) } /// Encode `values` as the block of an object whose properties arrived on `version`, or /// `None` without any. /// /// Sorting a delta-encoded list, which arrives ascending, never grows it, so the block /// fits wherever the publisher's list did. pub(crate) fn block(values: &[Property], version: Version) -> Result, Error> { if values.is_empty() { return Ok(None); } Ok(Some(crate::model::object::Block { bytes: serialize(values, version)?.into(), immutable: values.iter().any(|property| property.id == 0x0b), })) } /// What a received [`Block`](crate::model::object::Block) holds beside its bytes. pub(crate) struct Checked { pub immutable: bool, pub gap: Option, } /// Validate a block a `version` publisher published, as moq-transport ingress validates a /// list. /// /// An empty block is malformed, since it is sent as none. Absolute IDs must ascend, as /// delta ones do, since egress may forward the block unchanged; Immutable Properties stay /// as the publisher sent them. pub(crate) fn check(bytes: &Bytes, version: Version) -> Result { if bytes.is_empty() || bytes.len() > MAX_BLOCK { return Err(Error::MalformedTrack); } let parsed = list(bytes, version, false)?; if !parsed.values.is_sorted_by_key(|property| property.id) { return Err(Error::MalformedTrack); } Ok(Checked { immutable: parsed.immutable, gap: parsed.gap, }) } /// Restate an object's known size declaration, preserving sealed declarations verbatim. pub(super) fn compression(data: Vec, version: Version, inflated: Option) -> Result, Error> { if data.is_empty() && inflated.is_none() { return Ok(data); } let mut parsed = list(&Bytes::from(data), version, false)?; if let Some(sealed) = parsed.sealed_inflated { return match inflated == Some(sealed) { true => serialize(&parsed.values, version), false => Err(Error::Unsupported), }; } parsed.values.retain(|p| p.id != super::flate::INFLATED); if let Some(size) = inflated { parsed.values.push(Property { id: super::flate::INFLATED, value: Value::Int(size), }); } let out = serialize(&parsed.values, version)?; if out.len() > MAX_BLOCK { return Err(Error::Unsupported); } Ok(out) } /// A compressed frame must declare its inflated size; a plain frame must not. pub(super) fn inflated(size: Option, compressed: bool) -> Result, Error> { if size.is_some() != compressed { return Err(Error::MalformedTrack); } Ok(size) } /// Every property a block from a `version` publisher holds, decoded, for tests to inspect. #[cfg(test)] pub(crate) fn listed(properties: &Properties, version: Version) -> Vec { properties .block .as_ref() .map_or_else(Vec::new, |block| values(block, version).unwrap()) } /// Decode the properties of a block from a `version` publisher, whose values borrow its bytes. fn values(block: &crate::model::object::Block, version: Version) -> Result, Error> { Ok(list(&block.bytes, version, false)?.values) } /// Read an object's property list. Every property but the inflated size, which the frame /// holds, stays in the block, a Timestamp included: nothing reads time from an object. pub(crate) fn read(data: &Bytes, version: Version) -> Result { decode(data, version, true) } /// Read the property list of an object without a frame, such as an END_OF_GROUP status. pub(crate) fn unframed(data: &Bytes, version: Version) -> Result { let decoded = decode(data, version, false)?; if decoded.inflated.is_some() { return Err(Error::MalformedTrack); } Ok(decoded.properties) } fn decode(data: &Bytes, version: Version, framed: bool) -> Result { let mut parsed = list(data, version, false)?; if framed { parsed.values.retain(|p| p.id != super::flate::INFLATED); } let properties = Properties { block: block(&parsed.values, version)?, }; if properties.heap() > MAX_BLOCK as u64 { return Err(Error::Unsupported); } Ok(Decoded { properties, gap: parsed.gap, group_gap: parsed.group_gap, inflated: parsed.inflated, tie: parsed.tie, }) } /// Serialize relayed properties for `version`. /// /// `source` is the draft the track's publisher spoke, which serialized the block. A track /// without one carries no properties. pub(crate) fn write(properties: &Properties, source: Option, version: Version) -> Result, Error> { let Some(block) = &properties.block else { return Ok(Vec::new()); }; let source = source.ok_or(Error::MalformedTrack)?; // Between draft-18 and draft-22, forwarding 0x06 would give it a different meaning. // A mutable one is dropped; a sealed one is refused. if has_delivery_timeout(source) == has_delivery_timeout(version) { // The common case: the block is already what this draft would send. return Ok(block.bytes.to_vec()); } let values = values(block, source)?; if sealed_key(&values, source, 0x06)? { return Err(Error::Unsupported); } let out = serialize(values.iter().filter(|property| property.id != 0x06), version)?; // Another draft's varints can be wider, so a block re-encoded for it may not fit: // refused, as the receiver would refuse it. if out.len() > MAX_BLOCK { return Err(Error::Unsupported); } Ok(out) } /// Whether the immutable block among `values` holds a property with `id`. fn sealed_key(values: &[Property], version: Version, id: u64) -> Result { let Some(sealed) = values.iter().find(|property| property.id == 0x0b) else { return Ok(false); }; let Value::Bytes(bytes) = &sealed.value else { return Err(Error::MalformedTrack); }; let nested = list(bytes, version, true)?; Ok(nested.values.iter().any(|property| property.id == id)) } #[cfg(test)] mod tests { use super::*; const DRAFTS: [Version; 4] = [Version::Draft18, Version::Draft20, Version::Draft22, Version::Draft23]; #[test] fn key_six_is_opaque_on_every_draft() { for version in DRAFTS { for bytes in [ Bytes::from_static(&[0x06, 42]), Bytes::from_static(&[0x0b, 2, 0x06, 42]), ] { let decoded = read(&bytes, version).unwrap(); assert_eq!( write(&decoded.properties, Some(version), version).unwrap(), bytes, "{version}" ); } } } #[test] fn cached_bytes_do_not_retain_the_receive_buffer() { use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, }; struct Buffer { bytes: Vec, dropped: Arc, } impl AsRef<[u8]> for Buffer { fn as_ref(&self) -> &[u8] { &self.bytes } } impl Drop for Buffer { fn drop(&mut self) { self.dropped.store(true, Ordering::Relaxed); } } let dropped = Arc::new(AtomicBool::new(false)); let mut bytes = vec![0; 65536]; bytes[..3].copy_from_slice(&[5, 1, 42]); let received = Bytes::from_owner(Buffer { bytes, dropped: dropped.clone(), }) .slice(..3); let decoded = read(&received, Version::Draft22).unwrap(); drop(received); assert!(dropped.load(Ordering::Relaxed)); assert_eq!( listed(&decoded.properties, Version::Draft22)[0].value, Value::Bytes(Bytes::from_static(&[42])) ); } /// Nothing reads time from an object: a Timestamp, mutable or sealed, is a property /// like any other, which passes between moq-transport peers byte for byte. #[test] fn a_timestamp_passes_through_untouched() { for version in DRAFTS { for bytes in [ Bytes::from_static(&[0x10, 42, 0x20, 7]), Bytes::from_static(&[0x0b, 2, 0x10, 42, 0x10 - 0x0b, 50]), ] { let decoded = read(&bytes, version).unwrap(); assert_eq!( write(&decoded.properties, Some(version), version).unwrap(), bytes, "{version}" ); let status = unframed(&bytes, version).unwrap(); assert_eq!(write(&status, Some(version), version).unwrap(), bytes, "{version}"); assert!(check(&bytes, version).is_ok()); } } } /// The Prior Group ID Gap is read wherever it is, and stays in the block, which a relay /// forwards unchanged. One object may name it once. #[test] fn the_prior_group_id_gap_is_read_and_kept() { for version in DRAFTS { let outer = Bytes::from(own_properties(Some(2), None, version).unwrap()); let decoded = read(&outer, version).unwrap(); assert_eq!(decoded.group_gap, Some(2), "{version}"); assert_eq!(decoded.gap, None, "{version}"); assert_eq!(write(&decoded.properties, Some(version), version).unwrap(), outer); let sealed = Bytes::from_static(&[0x0b, 2, 0x3c, 5]); assert_eq!(read(&sealed, version).unwrap().group_gap, Some(5), "{version}"); for repeated in [&[0x3c, 1, 0, 1][..], &[0x0b, 2, 0x3c, 5, 0x3c - 0x0b, 5][..]] { assert!(matches!( read(&Bytes::copy_from_slice(repeated), version), Err(Error::MalformedTrack) )); } } } /// Draft-22 assigns 0x06 to SUBGROUP_DELIVERY_TIMEOUT, so it cannot cross that boundary. #[test] fn key_six_follows_its_draft() { let bytes = Bytes::from_static(&[0x06, 42, 0x1a, 7]); let decoded = read(&bytes, Version::Draft22).unwrap(); assert_eq!( write(&decoded.properties, Some(Version::Draft22), Version::Draft22).unwrap(), bytes ); // Between draft-18 and draft-22 neither reading survives: a mutable one is dropped. let modern = Bytes::from_static(&[0x20, 7]); assert_eq!( write(&decoded.properties, Some(Version::Draft22), Version::Draft18).unwrap(), modern ); let legacy = read(&bytes, Version::Draft18).unwrap(); assert_eq!( write(&legacy.properties, Some(Version::Draft18), Version::Draft22).unwrap(), modern ); // A sealed one is refused. let sealed = Bytes::from_static(&[0x0b, 2, 0x06, 42]); let decoded = read(&sealed, Version::Draft22).unwrap(); assert_eq!( write(&decoded.properties, Some(Version::Draft22), Version::Draft22).unwrap(), sealed ); assert!(matches!( write(&decoded.properties, Some(Version::Draft22), Version::Draft18), Err(Error::Unsupported) )); let legacy = read(&sealed, Version::Draft18).unwrap(); assert!(matches!( write(&legacy.properties, Some(Version::Draft18), Version::Draft22), Err(Error::Unsupported) )); } #[test] fn immutable_lists_validate_nested_blocks_and_integer_forms() { for bytes in [&[0x0b, 2, 0x0b, 0][..], &[0x0b, 0, 0, 0][..], &[0x0b, 1, 2][..]] { assert!(read(&Bytes::copy_from_slice(bytes), Version::Draft22).is_err()); } // Draft-18 permits this nonminimal seven-byte value. let bytes = Bytes::from_static(&[0x0b, 8, 2, 0xfc, 0, 0, 0, 0, 0, 1]); let decoded = read(&bytes, Version::Draft18).unwrap(); assert_eq!( write(&decoded.properties, Some(Version::Draft18), Version::Draft22).unwrap(), bytes ); } } #[cfg(test)] mod compression_tests { use super::*; #[test] fn inflated_size_is_admitted_before_any_inflate() { let broadcast = crate::broadcast::Info::default().produce(); let track = broadcast .create_track( "data", crate::track::Info::default().with_compression(crate::track::Compression::Deflate), ) .unwrap(); let group = track.append_next().unwrap(); let header = crate::frame::Header { info: crate::frame::Info { size: 1, timestamp: crate::Timestamp::unscaled(group.start), }, fields: None, inflated: inflated(Some(crate::group::MAX_CACHE_BYTES + 1), true).unwrap(), }; assert!(matches!(group.create_object(header), Err(Error::FrameTooLarge))); } fn property(id: u64, value: u64) -> Property { Property { id, value: Value::Int(value), } } #[test] fn sizes_are_known_and_unknown_properties_survive() { for version in [Version::Draft18, Version::Draft20, Version::Draft22, Version::Draft23] { let unknown = property(0x8800, 7); let wire = compression(serialize([&unknown], version).unwrap(), version, Some(123)).unwrap(); let decoded = read(&wire.into(), version).unwrap(); assert_eq!(decoded.inflated, Some(123)); assert_eq!(listed(&decoded.properties, version), [unknown]); assert_eq!(inflated(Some(0), true).unwrap(), Some(0)); assert!(inflated(None, true).is_err()); assert!(inflated(Some(0), false).is_err()); } } #[test] fn a_status_cannot_declare_an_inflated_size() { for version in [Version::Draft18, Version::Draft20, Version::Draft22, Version::Draft23] { let size = property(super::super::flate::INFLATED, 0); for value in [ size.clone(), Property { id: 0x0b, value: Value::Bytes(serialize([&size], version).unwrap().into()), }, ] { let wire = serialize([&value], version).unwrap(); assert!(matches!(unframed(&wire.into(), version), Err(Error::MalformedTrack))); } } } #[test] fn sealed_sizes_are_forwarded_or_refused_without_rewriting() { for version in [Version::Draft18, Version::Draft20, Version::Draft22, Version::Draft23] { let sealed = Property { id: 0x0b, value: Value::Bytes( serialize([&property(super::super::flate::INFLATED, 23)], version) .unwrap() .into(), ), }; let wire = serialize([&sealed], version).unwrap(); let decoded = read(&wire.clone().into(), version).unwrap(); assert_eq!(decoded.inflated, Some(23)); assert!(super::super::flate::egress_object(&decoded.properties, Some(version), true).is_ok()); assert!(matches!( super::super::flate::egress_object(&decoded.properties, Some(version), false), Err(Error::Unsupported) )); assert_eq!(compression(wire.clone(), version, Some(23)).unwrap(), wire); assert!(matches!( compression(wire.clone(), version, None), Err(Error::Unsupported) )); assert!(matches!( compression(wire.clone(), version, Some(24)), Err(Error::Unsupported) )); let repeated = serialize([&sealed, &property(super::super::flate::INFLATED, 23)], version).unwrap(); assert!(read(&repeated.into(), version).is_err()); } } /// `timestamp_object_id` encodes monotonic, tied, and backwards DTS values into strictly /// increasing Object IDs with an optional `TIMESTAMP_TIE (0x40B72)` property. #[test] fn timestamp_object_id_and_tie_roundtrip() { let group = 1000u64; // Monotonic: oid = dts - group, tie = 0. let mut prior = None; let mono: Vec<_> = [1000u64, 1033, 1066] .into_iter() .map(|dts| { let pair = timestamp_object_id(group, prior, dts); prior = Some(pair.0); pair }) .collect(); assert_eq!(mono, [(0, 0), (33, 0), (66, 0)]); // Consecutive ties: oid increments by 1, tie tracks offset. let mut prior = None; let tied: Vec<_> = [1000u64, 1000, 1000] .into_iter() .map(|dts| { let pair = timestamp_object_id(group, prior, dts); prior = Some(pair.0); pair }) .collect(); assert_eq!(tied, [(0, 0), (1, 1), (2, 2)]); // Backwards DTS bridging: oid increments by 1, tie absorbs the delta. let mut prior = None; let backwards: Vec<_> = [1000u64, 1100, 1033] .into_iter() .map(|dts| { let pair = timestamp_object_id(group, prior, dts); prior = Some(pair.0); pair }) .collect(); assert_eq!(backwards, [(0, 0), (100, 0), (101, 68)]); // Roundtrip TIMESTAMP_TIE alone, with PRIOR_GROUP_ID_GAP, inside Immutable Properties, // and reject duplicates. for version in [Version::Draft18, Version::Draft20, Version::Draft22, Version::Draft23] { let tie_only = Bytes::from(own_properties(None, Some(7), version).unwrap()); let decoded = read(&tie_only, version).unwrap(); assert_eq!(decoded.group_gap, None, "{version}"); assert_eq!(decoded.tie, Some(7), "{version}"); let both = Bytes::from(own_properties(Some(3), Some(12), version).unwrap()); let decoded = read(&both, version).unwrap(); assert_eq!(decoded.group_gap, Some(3), "{version}"); assert_eq!(decoded.tie, Some(12), "{version}"); let sealed = Property { id: 0x0b, value: Value::Bytes(serialize([&property(TIMESTAMP_TIE, 9)], version).unwrap().into()), }; let wire = serialize([&sealed], version).unwrap(); assert_eq!(read(&wire.into(), version).unwrap().tie, Some(9), "{version}"); let repeated = serialize([&sealed, &property(TIMESTAMP_TIE, 2)], version).unwrap(); assert!(matches!(read(&repeated.into(), version), Err(Error::MalformedTrack))); } } }