1use std::io;
2
3use tokio_util::{
4 bytes::{Bytes, BytesMut},
5 codec::{Decoder, Encoder, LengthDelimitedCodec},
6};
7
8use crate::model::Message;
9
10pub struct PostcardCodec(LengthDelimitedCodec);
11
12impl PostcardCodec {
13 pub fn new() -> Self {
14 Self(LengthDelimitedCodec::builder().new_codec())
15 }
16}
17
18impl Default for PostcardCodec {
19 fn default() -> Self {
20 Self::new()
21 }
22}
23
24impl Decoder for PostcardCodec {
25 type Item = Message;
26 type Error = io::Error;
27
28 fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Message>, Self::Error> {
29 match self.0.decode(src)? {
30 Some(frame) => match postcard::from_bytes(&frame) {
31 Ok(msg) => Ok(Some(msg)),
32 Err(err) => Err(io::Error::new(io::ErrorKind::InvalidData, err)),
33 },
34 None => Ok(None),
35 }
36 }
37}
38
39impl Encoder<Message> for PostcardCodec {
40 type Error = io::Error;
41
42 fn encode(&mut self, item: Message, dst: &mut BytesMut) -> Result<(), Self::Error> {
43 match postcard::to_allocvec(&item) {
44 Ok(val) => self.0.encode(Bytes::from(val), dst),
45 Err(err) => Err(io::Error::new(io::ErrorKind::InvalidData, err)),
46 }
47 }
48}
49
50#[cfg(test)]
51mod tests {
52 use crate::model::Start;
53
54 use super::*;
55
56 fn frame(message: Message) -> BytesMut {
57 let mut bytes = BytesMut::new();
58 PostcardCodec::new().encode(message, &mut bytes).unwrap();
59 bytes
60 }
61
62 #[test]
63 fn start_preserves_token_arguments_environment_and_working_directory() {
64 for token in [None, Some("secret"), Some("")] {
65 let mut bytes = frame(Message::Start(Start {
66 token: token.map(str::to_owned),
67 command: "команда".into(),
68 args: vec!["".into(), "argument with spaces".into()],
69 env: vec![("NAME".into(), "value\nwith\0bytes".into())],
70 cwd: "/work dir".into(),
71 }));
72 let Some(Message::Start(start)) = PostcardCodec::new().decode(&mut bytes).unwrap()
73 else {
74 panic!("expected start message");
75 };
76 assert_eq!(start.token.as_deref(), token);
77 assert_eq!(start.command, "команда");
78 assert_eq!(start.args, ["", "argument with spaces"]);
79 assert_eq!(
80 start.env,
81 [("NAME".to_owned(), "value\nwith\0bytes".to_owned())]
82 );
83 assert_eq!(start.cwd, "/work dir");
84 assert!(bytes.is_empty());
85 }
86 }
87
88 #[test]
89 fn stream_messages_preserve_empty_and_non_utf8_payloads() {
90 for payload in [vec![], vec![0, 255, 128, b'\n']] {
91 for message in [
92 Message::Stdin(payload.clone()),
93 Message::Stdout(payload.clone()),
94 Message::Stderr(payload.clone()),
95 ] {
96 let kind = std::mem::discriminant(&message);
97 let decoded = PostcardCodec::new()
98 .decode(&mut frame(message))
99 .unwrap()
100 .unwrap();
101 assert_eq!(std::mem::discriminant(&decoded), kind);
102 match decoded {
103 Message::Stdin(data) | Message::Stdout(data) | Message::Stderr(data) => {
104 assert_eq!(data, payload);
105 }
106 other => panic!("unexpected message: {other:?}"),
107 }
108 }
109 }
110 }
111
112 #[test]
113 fn statuses_and_failures_round_trip() {
114 for value in [i32::MIN, -1, 0, 255, i32::MAX] {
115 assert!(matches!(
116 PostcardCodec::new().decode(&mut frame(Message::Code(value))).unwrap(),
117 Some(Message::Code(actual)) if actual == value
118 ));
119 assert!(matches!(
120 PostcardCodec::new().decode(&mut frame(Message::Signaled(value))).unwrap(),
121 Some(Message::Signaled(actual)) if actual == value
122 ));
123 }
124 assert!(matches!(
125 PostcardCodec::new().decode(&mut frame(Message::Failed("ошибка\n".into()))).unwrap(),
126 Some(Message::Failed(message)) if message == "ошибка\n"
127 ));
128 }
129
130 #[test]
131 fn frames_use_a_big_endian_length_and_keep_message_order() {
132 let mut bytes = frame(Message::Code(0));
133 assert_eq!(bytes.as_ref(), &[0, 0, 0, 2, 4, 0]);
134 PostcardCodec::new()
135 .encode(Message::Code(7), &mut bytes)
136 .unwrap();
137 let mut codec = PostcardCodec::new();
138 assert!(matches!(
139 codec.decode(&mut bytes).unwrap(),
140 Some(Message::Code(0))
141 ));
142 assert!(matches!(
143 codec.decode(&mut bytes).unwrap(),
144 Some(Message::Code(7))
145 ));
146 assert!(codec.decode(&mut bytes).unwrap().is_none());
147 }
148
149 #[test]
150 fn incomplete_frames_wait_for_the_remaining_bytes_at_every_split() {
151 let encoded = frame(Message::Stdout(b"chunked payload".to_vec()));
152 for split in 0..encoded.len() {
153 let mut codec = PostcardCodec::new();
154 let mut bytes = BytesMut::from(&encoded[..split]);
155 assert!(codec.decode(&mut bytes).unwrap().is_none(), "split {split}");
156 bytes.extend_from_slice(&encoded[split..]);
157 assert!(matches!(
158 codec.decode(&mut bytes).unwrap(),
159 Some(Message::Stdout(data)) if data == b"chunked payload"
160 ));
161 assert!(bytes.is_empty());
162 }
163 }
164
165 #[test]
166 fn malformed_payloads_and_oversized_frames_are_rejected() {
167 for bytes in [
168 &[0, 0, 0, 0][..],
169 &[0, 0, 0, 1, 255][..],
170 &[0, 0, 0, 1, 4][..],
171 &[255, 255, 255, 255][..],
172 ] {
173 let error = PostcardCodec::new()
174 .decode(&mut BytesMut::from(bytes))
175 .unwrap_err();
176 assert_eq!(error.kind(), io::ErrorKind::InvalidData);
177 }
178 }
179
180 #[test]
181 fn eof_distinguishes_a_clean_stream_from_a_truncated_frame() {
182 let mut codec = PostcardCodec::new();
183 assert!(codec.decode_eof(&mut BytesMut::new()).unwrap().is_none());
184 for bytes in [&[0, 0][..], &[0, 0, 0, 2, 4][..]] {
185 assert!(
186 PostcardCodec::new()
187 .decode_eof(&mut BytesMut::from(bytes))
188 .is_err()
189 );
190 }
191 }
192
193 #[test]
194 fn encoding_rejects_payloads_above_the_frame_limit() {
195 let mut bytes = BytesMut::new();
196 let result =
197 PostcardCodec::new().encode(Message::Stdout(vec![0; 8 * 1024 * 1024]), &mut bytes);
198 assert!(result.is_err());
199 assert!(bytes.is_empty());
200 }
201}