gent_protocol/
transport_batch.rs1use std::fmt;
4
5pub const MAX_PACKETS: usize = 16;
6pub const MAX_PACKET_BYTES: usize = 1024 * 1024;
7pub const MAX_BYTES: usize = 2 * 1024 * 1024;
8pub const HEADER_BYTES: usize = 7;
9const MAGIC: &[u8; 5] = b"GNTB\x01";
10
11#[derive(Debug)]
12pub struct InvalidBatch;
13impl fmt::Display for InvalidBatch {
14 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15 f.write_str("invalid or oversized transport batch")
16 }
17}
18impl std::error::Error for InvalidBatch {}
19
20#[derive(Debug)]
21pub struct Batch {
22 packets: Vec<Vec<u8>>,
23 size: usize,
24}
25impl Default for Batch {
26 fn default() -> Self {
27 Self {
28 packets: Vec::new(),
29 size: HEADER_BYTES,
30 }
31 }
32}
33impl Batch {
34 pub fn push(&mut self, bytes: Vec<u8>) -> Result<bool, InvalidBatch> {
37 if bytes.is_empty() || bytes.len() > MAX_PACKET_BYTES {
38 return Err(InvalidBatch);
39 }
40 if self.packets.len() == MAX_PACKETS || self.size + 4 + bytes.len() > MAX_BYTES {
41 return Ok(false);
42 }
43 self.size += 4 + bytes.len();
44 self.packets.push(bytes);
45 Ok(true)
46 }
47 pub fn packets(&self) -> &[Vec<u8>] {
48 &self.packets
49 }
50 pub fn encode(&self) -> Vec<u8> {
51 let mut bytes = Vec::with_capacity(self.size);
52 bytes.extend_from_slice(MAGIC);
53 bytes.extend_from_slice(&(self.packets.len() as u16).to_be_bytes());
54 for packet in &self.packets {
55 bytes.extend_from_slice(&(packet.len() as u32).to_be_bytes());
56 bytes.extend_from_slice(packet);
57 }
58 bytes
59 }
60 pub fn decode(bytes: &[u8]) -> Result<Self, InvalidBatch> {
61 if bytes.len() < HEADER_BYTES || bytes.len() > MAX_BYTES || &bytes[..5] != MAGIC {
62 return Err(InvalidBatch);
63 }
64 let count = u16::from_be_bytes([bytes[5], bytes[6]]) as usize;
65 if count > MAX_PACKETS {
66 return Err(InvalidBatch);
67 }
68 let mut batch = Self::default();
69 let mut rest = &bytes[HEADER_BYTES..];
70 for _ in 0..count {
71 let length: [u8; 4] = rest
72 .get(..4)
73 .ok_or(InvalidBatch)?
74 .try_into()
75 .map_err(|_| InvalidBatch)?;
76 let size = u32::from_be_bytes(length) as usize;
77 rest = &rest[4..];
78 if !batch.push(rest.get(..size).ok_or(InvalidBatch)?.to_vec())? {
79 return Err(InvalidBatch);
80 }
81 rest = &rest[size..];
82 }
83 if !rest.is_empty() {
84 return Err(InvalidBatch);
85 }
86 Ok(batch)
87 }
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93 #[test]
94 fn bounded_round_trip_and_full_batch() {
95 assert!(
96 Batch::decode(&Batch::default().encode())
97 .unwrap()
98 .packets()
99 .is_empty()
100 );
101 let mut batch = Batch::default();
102 for i in 0..MAX_PACKETS {
103 assert!(batch.push(vec![i as u8; 123]).unwrap());
104 }
105 assert!(!batch.push(vec![99]).unwrap());
106 assert_eq!(
107 Batch::decode(&batch.encode()).unwrap().packets(),
108 batch.packets()
109 );
110 let mut large = Batch::default();
111 assert!(large.push(vec![1; MAX_PACKET_BYTES]).unwrap());
112 assert!(!large.push(vec![2; MAX_PACKET_BYTES]).unwrap());
113 assert!(
114 large
115 .push(vec![3; MAX_BYTES - MAX_PACKET_BYTES - HEADER_BYTES - 8])
116 .unwrap()
117 );
118 assert_eq!(large.encode().len(), MAX_BYTES);
119 assert!(Batch::decode(&large.encode()).is_ok());
120 }
121 #[test]
122 fn malformed_envelopes_are_refused_without_partial_results() {
123 let mut batch = Batch::default();
124 batch.push(vec![42; 8]).unwrap();
125 let encoded = batch.encode();
126 for end in 0..encoded.len() {
127 assert!(Batch::decode(&encoded[..end]).is_err());
128 }
129 for index in [0, 4, 5, 6, 7, 8, 9, 10] {
130 let mut bad = encoded.clone();
131 bad[index] = 255;
132 assert!(Batch::decode(&bad).is_err());
133 }
134 let mut trailing = encoded.clone();
135 trailing.push(0);
136 assert!(Batch::decode(&trailing).is_err());
137 assert!(Batch::decode(&vec![0; MAX_BYTES + 1]).is_err());
138 assert!(Batch::default().push(vec![]).is_err());
139 assert!(
140 Batch::default()
141 .push(vec![0; MAX_PACKET_BYTES + 1])
142 .is_err()
143 );
144 }
145}