Skip to main content

odradek_protocol/
consumer_protocol.rs

1//! The classic consumer protocol's embedded payloads.
2//!
3//! Brokers treat the subscription and assignment bytes inside
4//! JoinGroup/SyncGroup as opaque; between *clients* they are a wire
5//! format of their own — an `i16` version prefix, then the
6//! [`ConsumerProtocolSubscription`]/[`ConsumerProtocolAssignment`]
7//! schema body, with two forward-compatibility rules: decode at the
8//! highest version we know when the prefix is newer, and ignore
9//! trailing bytes newer members append. Every classic-group member
10//! implementation needs exactly this envelope, so it lives here.
11
12use bytes::{Buf, BufMut, Bytes, BytesMut};
13
14use crate::error::DecodeError;
15use crate::messages::consumer_protocol_assignment::{ConsumerProtocolAssignment, TopicPartition};
16use crate::messages::consumer_protocol_subscription::ConsumerProtocolSubscription;
17
18/// Encode a subscription to `topics` at envelope version 0.
19pub fn encode_subscription(topics: &[String]) -> Bytes {
20    let body = ConsumerProtocolSubscription {
21        topics: topics.to_vec(),
22        ..ConsumerProtocolSubscription::default()
23    };
24    let mut out = BytesMut::new();
25    out.put_i16(0);
26    body.encode(&mut out, 0).expect("v0 subscription encodes");
27    out.freeze()
28}
29
30/// Decode a subscription's topic list, tolerating newer envelopes.
31pub fn decode_subscription(data: &[u8]) -> Result<Vec<String>, DecodeError> {
32    let mut buf = Bytes::copy_from_slice(data);
33    if buf.len() < 2 {
34        return Err(DecodeError::Truncated {
35            needed: 2 - buf.len(),
36        });
37    }
38    let version = buf.get_i16().min(ConsumerProtocolSubscription::MAX_VERSION);
39    // Newer members may append fields; the prefix decodes, the rest is
40    // deliberately ignored.
41    let sub = ConsumerProtocolSubscription::decode(&mut buf, version.max(0))?;
42    Ok(sub.topics)
43}
44
45/// Encode an assignment at envelope version 0.
46pub fn encode_assignment(partitions: &[(String, Vec<i32>)]) -> Bytes {
47    let body = ConsumerProtocolAssignment {
48        assigned_partitions: partitions
49            .iter()
50            .map(|(topic, parts)| TopicPartition {
51                topic: topic.clone(),
52                partitions: parts.clone(),
53                ..TopicPartition::default()
54            })
55            .collect(),
56        ..ConsumerProtocolAssignment::default()
57    };
58    let mut out = BytesMut::new();
59    out.put_i16(0);
60    body.encode(&mut out, 0).expect("v0 assignment encodes");
61    out.freeze()
62}
63
64/// Decode an assignment, tolerating newer envelopes; empty bytes are an
65/// empty assignment (what a member awaiting partitions receives).
66pub fn decode_assignment(data: &[u8]) -> Result<Vec<(String, Vec<i32>)>, DecodeError> {
67    if data.is_empty() {
68        return Ok(Vec::new());
69    }
70    let mut buf = Bytes::copy_from_slice(data);
71    if buf.len() < 2 {
72        return Err(DecodeError::Truncated {
73            needed: 2 - buf.len(),
74        });
75    }
76    let version = buf.get_i16().min(ConsumerProtocolAssignment::MAX_VERSION);
77    let assignment = ConsumerProtocolAssignment::decode(&mut buf, version.max(0))?;
78    Ok(assignment
79        .assigned_partitions
80        .into_iter()
81        .map(|tp| (tp.topic, tp.partitions))
82        .collect())
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88
89    #[test]
90    fn payloads_roundtrip() {
91        let topics = vec!["alpha".to_owned(), "beta".to_owned()];
92        assert_eq!(
93            decode_subscription(&encode_subscription(&topics)).unwrap(),
94            topics
95        );
96
97        let parts = vec![("alpha".to_owned(), vec![0, 2])];
98        assert_eq!(
99            decode_assignment(&encode_assignment(&parts)).unwrap(),
100            parts
101        );
102        assert!(decode_assignment(b"").unwrap().is_empty());
103    }
104
105    #[test]
106    fn newer_envelopes_decode_and_short_ones_error() {
107        // A newer member's payload: a version prefix past our snapshot,
108        // a body carrying every field we know (newer versions are
109        // supersets), then fields we do not — which must be ignored.
110        let body = ConsumerProtocolSubscription {
111            topics: vec!["t".to_owned()],
112            ..ConsumerProtocolSubscription::default()
113        };
114        let mut encoded = BytesMut::new();
115        encoded.put_i16(ConsumerProtocolSubscription::MAX_VERSION + 9);
116        body.encode(&mut encoded, ConsumerProtocolSubscription::MAX_VERSION)
117            .unwrap();
118        encoded.put_slice(b"future-fields");
119        assert_eq!(decode_subscription(&encoded).unwrap(), vec!["t".to_owned()]);
120
121        assert!(decode_subscription(b"\x00").is_err());
122        assert!(decode_assignment(b"\x00").is_err());
123    }
124}