Skip to main content

labstream_proto/
meta.rs

1//! In-band live metadata records for the `meta/1` feature (`docs/extensions.md`,
2//! section `meta`, `docs/roadmap.md`, step 16).
3//!
4//! A metadata record stands between two samples on the TCP feed channel. It
5//! carries the outlet sample sequence number at the point of emission, a full
6//! outlet-clock timestamp, a UTF-8 key, and a UTF-8 value.
7//!
8//! Wire layout (little-endian):
9//! ```text
10//! u8   tag        0xFC
11//! u64  seq        outlet sequence number at the point of emission
12//! f64  timestamp  outlet clock timestamp in seconds
13//! u32  key_len    byte length of key (UTF-8)
14//! u32  val_len    byte length of value (UTF-8)
15//! [u8; key_len]   key bytes
16//! [u8; val_len]   value bytes
17//! ```
18
19/// First byte of a live metadata record on the TCP feed channel.
20///
21/// Sample tags are `0x01`, `0x02`, `0xF9`, and `0xFA`. Control tags are
22/// `0xFD` (`dgram` path) and `0xFE` (`seq`). `0xFC` is distinct from all of
23/// them.
24pub const TAG: u8 = 0xFC;
25
26/// Fixed header length in bytes before the variable-length key and value.
27pub const HEADER_LEN: usize = 1 + 8 + 8 + 4 + 4;
28
29/// Maximum allowed byte length of either key or value in one metadata record.
30pub const MAX_FIELD_LEN: usize = 64 * 1024;
31
32/// One live metadata change emitted by an outlet.
33#[derive(Debug, Clone, PartialEq)]
34pub struct MetadataUpdate {
35    /// Outlet sample sequence number at the moment the change was emitted.
36    ///
37    /// Samples with sequence numbers below `seq` came before this change.
38    /// Samples with sequence numbers at or above `seq` came after it.
39    pub seq: u64,
40    /// Timestamp of the change on the stream clock, in seconds.
41    pub timestamp: f64,
42    /// Hierarchical or flat key name (for example `impedance/Fp1`).
43    pub key: String,
44    /// Value string (for example `4.2 kOhm` or `bad`).
45    pub value: String,
46}
47
48/// Append one `meta/1` record to `out`.
49pub fn write_record(out: &mut Vec<u8>, update: &MetadataUpdate) {
50    let key = update.key.as_bytes();
51    let val = update.value.as_bytes();
52    let key_len = key.len().min(MAX_FIELD_LEN);
53    let val_len = val.len().min(MAX_FIELD_LEN);
54    out.reserve(HEADER_LEN + key_len + val_len);
55    out.push(TAG);
56    out.extend_from_slice(&update.seq.to_le_bytes());
57    out.extend_from_slice(&update.timestamp.to_le_bytes());
58    out.extend_from_slice(&(key_len as u32).to_le_bytes());
59    out.extend_from_slice(&(val_len as u32).to_le_bytes());
60    out.extend_from_slice(&key[..key_len]);
61    out.extend_from_slice(&val[..val_len]);
62}
63
64/// Result of inspecting the start of a TCP feed buffer for a `meta/1` record.
65#[derive(Debug, Clone, PartialEq)]
66pub enum Next {
67    /// A complete record and the total number of bytes consumed.
68    Record(MetadataUpdate, usize),
69    /// A `meta/1` record that is cut before its end. The caller reads more bytes.
70    Incomplete,
71    /// Not a `meta/1` record (starts with another tag or empty slice).
72    Other,
73    /// Malformed `meta/1` record (oversized field or invalid UTF-8).
74    Invalid,
75}
76
77/// Inspect the start of `buf` for a `meta/1` record.
78pub fn peek(buf: &[u8]) -> Next {
79    match buf.first() {
80        Some(&TAG) => {}
81        _ => return Next::Other,
82    }
83    if buf.len() < HEADER_LEN {
84        return Next::Incomplete;
85    }
86    let mut seq_b = [0u8; 8];
87    seq_b.copy_from_slice(&buf[1..9]);
88    let seq = u64::from_le_bytes(seq_b);
89
90    let mut ts_b = [0u8; 8];
91    ts_b.copy_from_slice(&buf[9..17]);
92    let timestamp = f64::from_le_bytes(ts_b);
93
94    let mut kl_b = [0u8; 4];
95    kl_b.copy_from_slice(&buf[17..21]);
96    let key_len = u32::from_le_bytes(kl_b) as usize;
97
98    let mut vl_b = [0u8; 4];
99    vl_b.copy_from_slice(&buf[21..25]);
100    let val_len = u32::from_le_bytes(vl_b) as usize;
101
102    if key_len > MAX_FIELD_LEN || val_len > MAX_FIELD_LEN {
103        return Next::Invalid;
104    }
105    let total = match HEADER_LEN
106        .checked_add(key_len)
107        .and_then(|n| n.checked_add(val_len))
108    {
109        Some(n) => n,
110        None => return Next::Invalid,
111    };
112    if buf.len() < total {
113        return Next::Incomplete;
114    }
115    let key = match core::str::from_utf8(&buf[HEADER_LEN..HEADER_LEN + key_len]) {
116        Ok(s) => s.to_string(),
117        Err(_) => return Next::Invalid,
118    };
119    let value = match core::str::from_utf8(&buf[HEADER_LEN + key_len..total]) {
120        Ok(s) => s.to_string(),
121        Err(_) => return Next::Invalid,
122    };
123    Next::Record(
124        MetadataUpdate {
125            seq,
126            timestamp,
127            key,
128            value,
129        },
130        total,
131    )
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn round_trip_preserves_fields_and_exact_timestamp_bits() {
140        let orig = MetadataUpdate {
141            seq: 42_000,
142            timestamp: 12345.6789012345,
143            key: "impedance/Fp1".to_string(),
144            value: "4.2 kOhm".to_string(),
145        };
146        let mut buf = Vec::new();
147        write_record(&mut buf, &orig);
148        assert_eq!(buf[0], TAG);
149        match peek(&buf) {
150            Next::Record(got, used) => {
151                assert_eq!(used, buf.len());
152                assert_eq!(got.seq, orig.seq);
153                assert_eq!(got.timestamp.to_bits(), orig.timestamp.to_bits());
154                assert_eq!(got.key, orig.key);
155                assert_eq!(got.value, orig.value);
156            }
157            other => panic!("expected Record, got {other:?}"),
158        }
159    }
160
161    #[test]
162    fn every_truncation_returns_incomplete() {
163        let orig = MetadataUpdate {
164            seq: 7,
165            timestamp: 1.5,
166            key: "ch/0/bad".to_string(),
167            value: "1".to_string(),
168        };
169        let mut buf = Vec::new();
170        write_record(&mut buf, &orig);
171        for cut in 1..buf.len() {
172            assert_eq!(peek(&buf[..cut]), Next::Incomplete, "cut at {cut}");
173        }
174    }
175
176    #[test]
177    fn other_tags_and_empty_return_other() {
178        assert_eq!(peek(&[]), Next::Other);
179        assert_eq!(peek(&[0x01, 0x00]), Next::Other);
180        assert_eq!(peek(&[0x02, 0x00]), Next::Other);
181        assert_eq!(peek(&[0xFE, 0x00]), Next::Other);
182    }
183
184    #[test]
185    fn oversized_and_bad_utf8_return_invalid() {
186        let mut bad_len = vec![TAG];
187        bad_len.extend_from_slice(&0u64.to_le_bytes());
188        bad_len.extend_from_slice(&0.0f64.to_le_bytes());
189        bad_len.extend_from_slice(&((MAX_FIELD_LEN as u32) + 1).to_le_bytes());
190        bad_len.extend_from_slice(&0u32.to_le_bytes());
191        assert_eq!(peek(&bad_len), Next::Invalid);
192
193        let mut bad_utf8 = vec![TAG];
194        bad_utf8.extend_from_slice(&0u64.to_le_bytes());
195        bad_utf8.extend_from_slice(&0.0f64.to_le_bytes());
196        bad_utf8.extend_from_slice(&2u32.to_le_bytes());
197        bad_utf8.extend_from_slice(&0u32.to_le_bytes());
198        bad_utf8.extend_from_slice(&[0xFF, 0xFE]);
199        assert_eq!(peek(&bad_utf8), Next::Invalid);
200    }
201}