Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 152 additions & 2 deletions asap-precompute-rs/src/envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ impl SketchType {
/// from 0. Record 0 is a full state (the samples folded into the window when
/// it was sent); record `n ≥ 1` is a delta on record `n − 1` (the state of the
/// samples folded since). The OTAP codec writes the epoch as the metric's
/// `asap.producer_epoch` metadata and the rest as the point's
/// `asap.sequence`, `asap.state_kind` and `asap.base_sequence` attributes.
/// `asap.producer_epoch` metadata and the sequence in the lineage frame
/// around the state's ASAPv1 bytes in `sketch.envelope` ([`Lineage::frame`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Lineage {
/// The collector instance: a random number drawn at start.
Expand All @@ -100,11 +100,116 @@ pub struct Lineage {
pub sequence: u64,
}

/// The first byte of a version 1 lineage frame. The high nibble `0xA` marks
/// a lineage frame and the low one is its version; an ASAPv1 envelope starts
/// with `b'A'` (`0x41`), so a bare one is never taken for a frame.
pub const LINEAGE_FRAME_V1: u8 = 0xA1;
/// The flags byte's bit of a delta; the other bits are 0.
const LINEAGE_FRAME_DELTA: u8 = 0x01;

impl Lineage {
/// A delta's base sequence; `None` for a full.
pub fn base_sequence(&self) -> Option<u64> {
self.sequence.checked_sub(1)
}

/// `asapv1` behind this record's lineage frame, the bytes of its
/// `sketch.envelope`:
///
/// ```text
/// [ 0xA1 | flags:u8 (bit 0: delta) | sequence:uleb128
/// | base_sequence:uleb128 (deltas only) | ASAPv1 bytes ]
/// ```
///
/// A full is 3 bytes longer than its ASAPv1 bytes (`A1 00 00`); a delta
/// below sequence 128 is 4 longer. The epoch is not in the frame: it is
/// the metric's, shared by all of its points.
pub fn frame(&self, asapv1: &[u8]) -> Vec<u8> {
let mut framed = Vec::with_capacity(asapv1.len() + 2 + 2 * 10);
framed.push(LINEAGE_FRAME_V1);
match self.base_sequence() {
None => {
framed.push(0);
push_uleb128(&mut framed, self.sequence);
}
Some(base) => {
framed.push(LINEAGE_FRAME_DELTA);
push_uleb128(&mut framed, self.sequence);
push_uleb128(&mut framed, base);
}
}
framed.extend_from_slice(asapv1);
framed
}

/// The sequence of a framed state ([`Self::frame`]) and its ASAPv1
/// bytes. Errs, saying why, for bytes that are no version 1 frame (a
/// bare ASAPv1 envelope from a collector without lineage frames, or
/// another frame version), with unknown flags, or whose kind disagrees
/// with its sequence and base (a full is sequence 0, a delta `n ≥ 1` has
/// base `n − 1`).
pub fn unframe(bytes: &[u8]) -> Result<(u64, &[u8]), String> {
match bytes.first() {
Some(&LINEAGE_FRAME_V1) => {}
Some(_) if bytes.starts_with(b"ASAPv1") => {
return Err("a bare ASAPv1 state without a lineage frame".into())
}
Some(&first) if first >> 4 == 0xA => {
return Err(format!(
"lineage frame version {}; this reader reads version 1",
first & 0x0F
))
}
_ => return Err("not a lineage frame".into()),
}
let flags = *bytes.get(1).ok_or("a truncated lineage frame")?;
if flags & !LINEAGE_FRAME_DELTA != 0 {
return Err(format!("unknown lineage frame flags {flags:#04x}"));
}
let mut rest = &bytes[2..];
let sequence = read_uleb128(&mut rest)?;
if flags & LINEAGE_FRAME_DELTA == 0 {
if sequence != 0 {
return Err(format!("a full has sequence {sequence}, not 0"));
}
} else {
let base = read_uleb128(&mut rest)?;
if sequence == 0 || base != sequence - 1 {
return Err(format!(
"a delta of sequence {sequence} has base {base}, not its sequence − 1"
));
}
}
Ok((sequence, rest))
}
}

fn push_uleb128(out: &mut Vec<u8>, mut value: u64) {
loop {
let byte = (value & 0x7F) as u8;
value >>= 7;
if value == 0 {
out.push(byte);
return;
}
out.push(byte | 0x80);
}
}

fn read_uleb128(bytes: &mut &[u8]) -> Result<u64, String> {
let mut value = 0u64;
for (i, &byte) in bytes.iter().enumerate().take(10) {
let bits = u64::from(byte & 0x7F);
if i == 9 && bits > 1 {
return Err("a lineage frame varint overflows u64".into());
}
value |= bits << (7 * i);
if byte & 0x80 == 0 {
*bytes = &bytes[i + 1..];
return Ok(value);
}
}
Err("a truncated lineage frame varint".into())
}

/// One emitted sketch (or scalar estimate) plus its runtime metadata.
Expand Down Expand Up @@ -217,4 +322,49 @@ mod tests {
let decoded: SketchEnvelope = serde_json::from_str(&json).expect("deserialize");
assert_eq!(env, decoded);
}

/// The lineage frame's bytes, pinned: ASAPQuery-backend's decoder holds
/// the same vectors.
#[test]
fn lineage_frames_are_these_bytes_and_round_trip() {
let asapv1 = b"ASAPv1\x01rest";
let lineage = |sequence| Lineage {
producer_epoch: 7,
sequence,
};
let cases: [(u64, &[u8]); 3] = [
(0, &[0xA1, 0x00, 0x00]),
(1, &[0xA1, 0x01, 0x01, 0x00]),
(300, &[0xA1, 0x01, 0xAC, 0x02, 0xAB, 0x02]),
];
for (sequence, head) in cases {
let framed = lineage(sequence).frame(asapv1);
assert_eq!(&framed[..head.len()], head, "sequence {sequence}");
assert_eq!(&framed[head.len()..], asapv1);
assert_eq!(Lineage::unframe(&framed), Ok((sequence, &asapv1[..])));
}
let max = lineage(u64::MAX).frame(asapv1);
assert_eq!(Lineage::unframe(&max), Ok((u64::MAX, &asapv1[..])));
}

/// Bytes that are no version 1 lineage frame, or whose kind disagrees
/// with its sequence and base, are refused, saying why.
#[test]
fn bad_lineage_frames_are_refused() {
let refused = |bytes: &[u8]| Lineage::unframe(bytes).unwrap_err();
assert!(refused(b"ASAPv1\x01rest").contains("without a lineage frame"));
assert!(refused(&[0xA2, 0x00, 0x00]).contains("version 2"));
assert!(refused(&[0x00]).contains("not a lineage frame"));
assert!(refused(&[]).contains("not a lineage frame"));
assert!(refused(&[0xA1]).contains("truncated"));
assert!(refused(&[0xA1, 0x02, 0x00]).contains("flags"));
assert!(refused(&[0xA1, 0x00, 0x80]).contains("truncated"));
assert!(refused(&[0xA1, 0x00, 0x01]).contains("a full has sequence 1"));
assert!(refused(&[0xA1, 0x01, 0x00, 0x00]).contains("base"));
assert!(refused(&[0xA1, 0x01, 0x03, 0x01]).contains("base 1"));
let overflow = [
0xA1, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02,
];
assert!(refused(&overflow).contains("overflows"));
}
}
Loading
Loading