1use crate::internal::{CapturedOutput, FailureCause, TestResult};
2use crate::stats::Summary;
3use desert_rust::BinaryCodec;
4use interprocess::local_socket::{
5 GenericFilePath, GenericNamespaced, Name, NameType, ToFsName, ToNsName,
6};
7use std::io::{self, Read, Write};
8use std::time::Duration;
9
10pub const FRAME_LEN_BYTES: usize = 4;
14
15pub fn write_frame<W: Write>(writer: &mut W, payload: &[u8]) -> io::Result<()> {
18 let len = u32::try_from(payload.len()).map_err(|_| {
19 io::Error::new(
20 io::ErrorKind::InvalidData,
21 "IPC payload size exceeds u32::MAX",
22 )
23 })?;
24 writer.write_all(&len.to_le_bytes())?;
25 writer.write_all(payload)
26}
27
28pub fn read_frame<R: Read>(reader: &mut R) -> io::Result<Vec<u8>> {
30 let mut len_bytes = [0u8; FRAME_LEN_BYTES];
31 reader.read_exact(&mut len_bytes)?;
32 let len = u32::from_le_bytes(len_bytes) as usize;
33 let mut payload = vec![0; len];
34 reader.read_exact(&mut payload)?;
35 Ok(payload)
36}
37
38#[cfg(feature = "tokio")]
39pub async fn write_frame_async<W>(writer: &mut W, payload: &[u8]) -> io::Result<()>
40where
41 W: tokio::io::AsyncWriteExt + Unpin,
42{
43 let len = u32::try_from(payload.len()).map_err(|_| {
44 io::Error::new(
45 io::ErrorKind::InvalidData,
46 "IPC payload size exceeds u32::MAX",
47 )
48 })?;
49 writer.write_all(&len.to_le_bytes()).await?;
50 writer.write_all(payload).await
51}
52
53#[cfg(feature = "tokio")]
54pub async fn read_frame_async<R>(reader: &mut R) -> io::Result<Vec<u8>>
55where
56 R: tokio::io::AsyncReadExt + Unpin,
57{
58 let mut len_bytes = [0u8; FRAME_LEN_BYTES];
59 reader.read_exact(&mut len_bytes).await?;
60 let len = u32::from_le_bytes(len_bytes) as usize;
61 let mut payload = vec![0; len];
62 reader.read_exact(&mut payload).await?;
63 Ok(payload)
64}
65
66#[derive(Debug, BinaryCodec)]
68pub enum IpcCommand {
69 RunTest {
70 name: String,
71 crate_name: String,
72 module_path: String,
73 },
74 ProvideCloneable { dep_id: String, wire_bytes: Vec<u8> },
81 ProvideHostedDescriptor { dep_id: String, wire_bytes: Vec<u8> },
87 HostedRpcReply {
94 request_id: u64,
95 body: HostedRpcReplyBody,
96 },
97 Shutdown,
102}
103
104pub(crate) fn test_loop_should_exit(
114 is_ipc_worker: bool,
115 execution_done: bool,
116 owned_worker_exhausted: bool,
117) -> bool {
118 owned_worker_exhausted || (!is_ipc_worker && execution_done)
119}
120
121#[derive(Debug, BinaryCodec)]
125pub enum HostedRpcReplyBody {
126 Ok { result_bytes: Vec<u8> },
127 Err { message: String },
128}
129
130#[derive(Debug, BinaryCodec)]
131pub enum SerializableTestResult {
132 Passed {
133 exec_time: Duration,
134 },
135 Benchmarked {
136 exec_time: Duration,
137 ns_iter_summ: Summary,
138 mb_s: usize,
139 },
140 Failed {
141 exec_time: Duration,
142 rendered_failure_cause: String,
143 },
144 Ignored,
145 WithAttempts {
146 result: Box<SerializableTestResult>,
147 attempts: Vec<SerializableTestAttempt>,
148 },
149}
150
151#[derive(Debug, BinaryCodec)]
152pub struct SerializableTestAttempt {
153 result: SerializableTestResult,
154 finish_marker: Option<String>,
155}
156
157impl SerializableTestResult {
158 pub fn into_test_result(
159 self,
160 stdout: Vec<CapturedOutput>,
161 stderr: Vec<CapturedOutput>,
162 ) -> TestResult {
163 if let Self::WithAttempts { result, attempts } = self {
164 let mut stdout = stdout.into_iter();
165 let mut stderr = stderr.into_iter();
166 let mut history = Vec::new();
167 let mut all_output = Vec::new();
168 for attempt in attempts {
169 let (out, err) = if let Some(marker) = &attempt.finish_marker {
170 (
171 take_attempt_output(&mut stdout, marker),
172 take_attempt_output(&mut stderr, marker),
173 )
174 } else {
175 (Vec::new(), Vec::new())
176 };
177 let attempt_result = attempt.result.into_test_result(out, err);
178 all_output.extend(attempt_result.captured_output().iter().cloned());
179 history.push(crate::internal::TestAttempt {
180 result: Box::new(attempt_result),
181 finish_marker: None,
182 });
183 }
184 all_output.extend(stdout);
185 all_output.extend(stderr);
186 all_output.sort();
187 let mut result = result.into_test_result(Vec::new(), Vec::new());
188 result.set_captured_output(all_output);
189 result.set_attempts(history);
190 return result;
191 }
192 let mut captured = [stdout, stderr].concat();
193 captured.sort();
194
195 let mut result: TestResult = self.into();
196 result.set_captured_output(captured);
197 result
198 }
199}
200
201fn take_attempt_output(
202 source: &mut impl Iterator<Item = CapturedOutput>,
203 marker: &str,
204) -> Vec<CapturedOutput> {
205 let mut captured = Vec::new();
206 for mut output in source.by_ref() {
207 let line = match &mut output {
208 CapturedOutput::Stdout { line, .. }
209 | CapturedOutput::Stderr { line, .. }
210 | CapturedOutput::Host { line, .. } => line,
211 };
212 if let Some(prefix) = line.strip_suffix(marker) {
215 if !prefix.is_empty() {
216 *line = prefix.to_string();
217 captured.push(output);
218 }
219 break;
220 }
221 captured.push(output);
222 }
223 captured
224}
225
226impl From<&TestResult> for SerializableTestResult {
227 fn from(result: &TestResult) -> Self {
228 let final_result = Self::without_attempts(result);
229 if result.attempts().is_empty() {
230 final_result
231 } else {
232 Self::WithAttempts {
233 result: Box::new(final_result),
234 attempts: result
235 .attempts()
236 .iter()
237 .map(|attempt| SerializableTestAttempt {
238 result: Self::without_attempts(&attempt.result),
239 finish_marker: attempt.finish_marker.clone(),
240 })
241 .collect(),
242 }
243 }
244 }
245}
246
247impl SerializableTestResult {
248 fn without_attempts(result: &TestResult) -> Self {
249 match &result {
250 TestResult::Passed { exec_time, .. } => SerializableTestResult::Passed {
251 exec_time: *exec_time,
252 },
253 TestResult::Benchmarked {
254 exec_time,
255 ns_iter_summ,
256 mb_s,
257 ..
258 } => SerializableTestResult::Benchmarked {
259 exec_time: *exec_time,
260 ns_iter_summ: *ns_iter_summ,
261 mb_s: *mb_s,
262 },
263 TestResult::Failed {
264 exec_time, cause, ..
265 } => SerializableTestResult::Failed {
266 exec_time: *exec_time,
267 rendered_failure_cause: cause.render(),
268 },
269 TestResult::Ignored { .. } => SerializableTestResult::Ignored,
270 }
271 }
272}
273
274impl From<SerializableTestResult> for TestResult {
275 fn from(result: SerializableTestResult) -> Self {
276 match result {
277 SerializableTestResult::WithAttempts { .. } => {
278 result.into_test_result(Vec::new(), Vec::new())
279 }
280 SerializableTestResult::Passed { exec_time } => TestResult::passed(exec_time),
281 SerializableTestResult::Failed {
282 exec_time,
283 rendered_failure_cause,
284 } => TestResult::failed(
285 exec_time,
286 FailureCause::HarnessError(rendered_failure_cause),
287 ),
288 SerializableTestResult::Ignored => TestResult::ignored(),
289 SerializableTestResult::Benchmarked {
290 exec_time,
291 ns_iter_summ,
292 mb_s,
293 } => TestResult::benchmarked(exec_time, ns_iter_summ, mb_s),
294 }
295 }
296}
297
298#[derive(Debug, BinaryCodec)]
300pub struct TestRetry {
301 pub attempt: usize,
302 pub max_attempts: usize,
303 pub reason: String,
304}
305
306#[derive(Debug, BinaryCodec)]
309pub enum IpcResponse {
310 TestFinished {
311 result: SerializableTestResult,
312 finish_marker: String,
313 retries: Vec<TestRetry>,
315 worker_exhausted: bool,
320 },
321 CloneableAccepted { dep_id: String },
324 HostedDescriptorAccepted { dep_id: String },
327 HostedRpcCall {
335 request_id: u64,
336 dep_id: String,
337 method_idx: u32,
338 args_bytes: Vec<u8>,
339 },
340}
341
342pub fn ipc_name<'s>(name: String) -> Name<'s> {
343 if GenericNamespaced::is_supported() {
344 name.to_ns_name::<GenericNamespaced>()
345 .expect("Invalid local socket name")
346 } else {
347 name.to_fs_name::<GenericFilePath>()
348 .expect("Invalid local socket name")
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355 use std::io::Cursor;
356
357 #[test]
358 fn write_then_read_round_trip_empty() {
359 let mut buf: Vec<u8> = Vec::new();
360 write_frame(&mut buf, &[]).expect("write");
361 let mut cursor = Cursor::new(&buf);
362 let payload = read_frame(&mut cursor).expect("read");
363 assert!(payload.is_empty());
364 }
365
366 #[test]
367 fn write_then_read_round_trip_small() {
368 let mut buf: Vec<u8> = Vec::new();
369 let data = b"hello, world";
370 write_frame(&mut buf, data).expect("write");
371 let mut cursor = Cursor::new(&buf);
372 let payload = read_frame(&mut cursor).expect("read");
373 assert_eq!(payload, data);
374 }
375
376 #[test]
377 fn write_then_read_round_trip_large_payload_exceeds_u16() {
378 let mut data = vec![0u8; 200 * 1024];
380 for (i, b) in data.iter_mut().enumerate() {
381 *b = (i % 251) as u8;
382 }
383 let mut buf: Vec<u8> = Vec::new();
384 write_frame(&mut buf, &data).expect("write");
385 assert_eq!(buf.len(), FRAME_LEN_BYTES + data.len());
386 let mut cursor = Cursor::new(&buf);
387 let payload = read_frame(&mut cursor).expect("read");
388 assert_eq!(payload.len(), data.len());
389 assert_eq!(payload, data);
390 }
391
392 #[test]
393 fn read_frame_propagates_eof() {
394 let buf: Vec<u8> = Vec::new();
395 let mut cursor = Cursor::new(&buf);
396 let err = read_frame(&mut cursor).expect_err("must fail on empty");
397 assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
398 }
399
400 #[test]
401 fn worker_lifetime_and_parent_scheduler_capacity_are_distinct() {
402 assert!(test_loop_should_exit(false, true, false));
403 assert!(!test_loop_should_exit(true, true, false));
404 assert!(!test_loop_should_exit(true, false, false));
405 assert!(test_loop_should_exit(false, false, true));
406 }
407
408 #[cfg(feature = "tokio")]
409 #[test]
410 fn async_round_trip_large_payload_exceeds_u16() {
411 let runtime = tokio::runtime::Runtime::new().unwrap();
412 runtime.block_on(async {
413 let mut data = vec![0u8; 200 * 1024];
414 for (i, b) in data.iter_mut().enumerate() {
415 *b = (i % 251) as u8;
416 }
417 let mut buf: Vec<u8> = Vec::new();
418 write_frame_async(&mut buf, &data).await.expect("write");
419 assert_eq!(buf.len(), FRAME_LEN_BYTES + data.len());
420 let mut slice: &[u8] = &buf;
421 let payload = read_frame_async(&mut slice).await.expect("read");
422 assert_eq!(payload, data);
423 });
424 }
425}