Skip to main content

test_r_core/
ipc.rs

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
10/// Length-prefix width used to frame all IPC messages. A `u32` allows payloads
11/// up to 4 GiB which comfortably covers Cloneable payloads such as
12/// precompiled wasm components.
13pub const FRAME_LEN_BYTES: usize = 4;
14
15/// Writes a length-prefixed frame to the writer. The length is encoded as a
16/// little-endian `u32`.
17pub 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
28/// Reads a length-prefixed frame produced by [`write_frame`].
29pub 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/// Commands sent from the primary test runner to the spawned worker processes.
67#[derive(Debug, BinaryCodec)]
68pub enum IpcCommand {
69    RunTest {
70        name: String,
71        crate_name: String,
72        module_path: String,
73    },
74    /// Provide the wire bytes for a `Cloneable` dependency to the worker.
75    /// Sent before any test that requires the dep. The `dep_id` is the
76    /// dep's fully-qualified id (`{crate}::{module}::{name}`) so that
77    /// same-named deps registered in different modules don't collide.
78    /// Workers cache the bytes and pass them to the worker reconstructor
79    /// when materializing.
80    ProvideCloneable { dep_id: String, wire_bytes: Vec<u8> },
81    /// Provide the descriptor bytes for a `Hosted` dependency to a worker.
82    /// Same shape as [`Self::ProvideCloneable`]; on the worker side the
83    /// bytes are fed to `HostedDep::from_descriptor` (via the registered
84    /// worker reconstructor) instead of being treated as the dep value
85    /// directly. The `dep_id` is the dep's fully-qualified id.
86    ProvideHostedDescriptor { dep_id: String, wire_bytes: Vec<u8> },
87    /// Phase 1C: parent's response to a worker-initiated
88    /// [`IpcResponse::HostedRpcCall`]. Carries the same `request_id`
89    /// echoed back so the worker's stub can match the reply to the
90    /// outstanding in-flight call. `body` is `Ok(result_bytes)` if the
91    /// owner-side dispatcher succeeded, or `Err(message)` if it failed
92    /// (owner panic, unknown method, codec error, …).
93    HostedRpcReply {
94        request_id: u64,
95        body: HostedRpcReplyBody,
96    },
97    /// Tells an IPC worker that its owning parent scheduler thread will not
98    /// send any more commands. Worker lifetime is parent-controlled rather
99    /// than inferred from the worker's private execution plan, whose
100    /// `remaining_count` can reach zero before the parent is done dispatching.
101    Shutdown,
102}
103
104/// Returns whether a test loop should stop based on its execution plan.
105///
106/// An in-process runner owns its scheduler and stops when that scheduler is
107/// done. An IPC worker must ignore its private scheduler's completion state:
108/// only an explicit [`IpcCommand::Shutdown`] from its owning parent proves
109/// that no future [`IpcCommand::RunTest`] will arrive. Conversely, a parent
110/// scheduler thread must retire when its owned worker reports that its private
111/// plan is exhausted, even if the shared parent plan still has tests for other
112/// workers.
113pub(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/// Body of a [`IpcCommand::HostedRpcReply`]. Either the serialized return
122/// value of the owner's method, or a human-readable error describing why
123/// dispatch failed.
124#[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        // A test may leave a partial line before the flushed marker. Strip
213        // only the unique marker suffix, retaining the test's actual bytes.
214        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/// A performed repetition, replayed by the parent reporter before completion.
299#[derive(Debug, BinaryCodec)]
300pub struct TestRetry {
301    pub attempt: usize,
302    pub max_attempts: usize,
303    pub reason: String,
304}
305
306/// Responses sent from the spawned worker processes to the primary test
307/// runner.
308#[derive(Debug, BinaryCodec)]
309pub enum IpcResponse {
310    TestFinished {
311        result: SerializableTestResult,
312        finish_marker: String,
313        /// Repetitions of this test only; workers drain these after each test.
314        retries: Vec<TestRetry>,
315        /// Whether the worker's private execution plan was exhausted while
316        /// locating this test. The owning parent scheduler thread must retire
317        /// after this response because the worker cannot accept another
318        /// `RunTest`, but the worker process remains alive until `Shutdown`.
319        worker_exhausted: bool,
320    },
321    /// Acknowledges a [`IpcCommand::ProvideCloneable`]. Echoes back the
322    /// fully-qualified `dep_id` the command carried.
323    CloneableAccepted { dep_id: String },
324    /// Acknowledges a [`IpcCommand::ProvideHostedDescriptor`]. Echoes back
325    /// the fully-qualified `dep_id`.
326    HostedDescriptorAccepted { dep_id: String },
327    /// Phase 1C: worker-initiated remote procedure call against a
328    /// `HostedRpc` dep owned by the parent. The worker's stub assigns a
329    /// monotonically-increasing `request_id`, serializes its method
330    /// arguments into `args_bytes`, and writes this frame on the shared
331    /// IPC stream. The parent's `Worker::run_test` loop dispatches the
332    /// call to the right owner via `dep_id`, and responds with a matching
333    /// [`IpcCommand::HostedRpcReply`].
334    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        // 200 KiB — larger than the old u16 length prefix could express.
379        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}