1use std::ffi::{OsStr, OsString};
2use std::io::{Read, Write};
3use std::path::{Path, PathBuf};
4use std::process::{ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus, Stdio};
5use std::sync::{Arc, Mutex};
6use std::thread;
7use std::time::{Duration, Instant};
8
9#[cfg(unix)]
10use std::os::unix::process::CommandExt;
11#[cfg(unix)]
12use std::process::Child;
13
14#[cfg(windows)]
15use process_wrap::std::{ChildWrapper, CommandWrap, JobObject};
16
17use serde::Serialize;
18use thiserror::Error;
19
20use crate::CommandTemplate;
21
22#[cfg(unix)]
23type ManagedChild = Child;
24#[cfg(windows)]
25type ManagedChild = Box<dyn ChildWrapper>;
26
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
29pub enum StdinMode {
30 #[default]
32 Empty,
33 Piped(Vec<u8>),
38 Terminal(Vec<u8>),
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct EnvironmentChange {
45 name: OsString,
46 value: Option<OsString>,
47}
48
49impl EnvironmentChange {
50 pub fn name(&self) -> &OsStr {
52 &self.name
53 }
54
55 pub fn value(&self) -> Option<&OsStr> {
57 self.value.as_deref()
58 }
59}
60
61#[derive(Debug, Clone, Default, PartialEq, Eq)]
63pub struct Invocation {
64 args: Vec<OsString>,
65 current_dir: Option<PathBuf>,
66 environment: Vec<EnvironmentChange>,
67 stdin: StdinMode,
68 timeout: Option<Duration>,
69 capture_limit: Option<usize>,
70}
71
72impl Invocation {
73 pub fn new() -> Self {
75 Self::default()
76 }
77
78 #[must_use]
80 pub fn arg(mut self, argument: impl Into<OsString>) -> Self {
81 self.args.push(argument.into());
82 self
83 }
84
85 #[must_use]
87 pub fn args<I, S>(mut self, arguments: I) -> Self
88 where
89 I: IntoIterator<Item = S>,
90 S: Into<OsString>,
91 {
92 self.args.extend(arguments.into_iter().map(Into::into));
93 self
94 }
95
96 #[must_use]
98 pub fn current_dir(mut self, path: impl Into<PathBuf>) -> Self {
99 self.current_dir = Some(path.into());
100 self
101 }
102
103 #[must_use]
105 pub fn env(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
106 self.environment.push(EnvironmentChange {
107 name: name.into(),
108 value: Some(value.into()),
109 });
110 self
111 }
112
113 #[must_use]
115 pub fn env_remove(mut self, name: impl Into<OsString>) -> Self {
116 self.environment.push(EnvironmentChange {
117 name: name.into(),
118 value: None,
119 });
120 self
121 }
122
123 #[must_use]
125 pub fn stdin(mut self, stdin: StdinMode) -> Self {
126 self.stdin = stdin;
127 self
128 }
129
130 #[must_use]
132 pub fn timeout(mut self, timeout: Duration) -> Self {
133 self.timeout = Some(timeout);
134 self
135 }
136
137 #[must_use]
143 pub fn capture_limit(mut self, bytes_per_stream: usize) -> Self {
144 self.capture_limit = Some(bytes_per_stream);
145 self
146 }
147
148 pub fn arguments(&self) -> &[OsString] {
150 &self.args
151 }
152
153 pub fn working_directory(&self) -> Option<&Path> {
155 self.current_dir.as_deref()
156 }
157
158 pub fn environment(&self) -> &[EnvironmentChange] {
160 &self.environment
161 }
162
163 pub fn stdin_mode(&self) -> &StdinMode {
165 &self.stdin
166 }
167
168 pub fn timeout_value(&self) -> Option<Duration> {
170 self.timeout
171 }
172
173 pub fn capture_limit_value(&self) -> Option<usize> {
175 self.capture_limit
176 }
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
181#[serde(rename_all = "snake_case", tag = "kind")]
182pub enum Termination {
183 Exited {
185 code: i32,
187 },
188 Signaled,
190 TimedOut,
192}
193
194impl Termination {
195 pub fn success(self) -> bool {
197 matches!(self, Self::Exited { code: 0 })
198 }
199
200 pub fn code(self) -> Option<i32> {
202 match self {
203 Self::Exited { code } => Some(code),
204 Self::Signaled | Self::TimedOut => None,
205 }
206 }
207}
208
209#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct InvocationResult {
212 termination: Termination,
213 stdout: Vec<u8>,
214 stderr: Vec<u8>,
215 duration: Duration,
216}
217
218impl InvocationResult {
219 pub fn new(
221 termination: Termination,
222 stdout: Vec<u8>,
223 stderr: Vec<u8>,
224 duration: Duration,
225 ) -> Self {
226 Self {
227 termination,
228 stdout,
229 stderr,
230 duration,
231 }
232 }
233
234 pub fn termination(&self) -> Termination {
236 self.termination
237 }
238
239 pub fn stdout(&self) -> &[u8] {
241 &self.stdout
242 }
243
244 pub fn stderr(&self) -> &[u8] {
246 &self.stderr
247 }
248
249 pub fn duration(&self) -> Duration {
251 self.duration
252 }
253}
254
255#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
257pub struct RunnerCapabilities {
258 pub terminal_input: bool,
260 pub completion_script_execution: bool,
263}
264
265pub trait Runner: Send + Sync {
267 fn command(&self) -> &CommandTemplate;
269
270 fn capabilities(&self) -> RunnerCapabilities {
272 RunnerCapabilities::default()
273 }
274
275 fn run(&self, invocation: &Invocation) -> Result<InvocationResult, RunnerError>;
285}
286
287#[derive(Debug, Clone)]
289pub struct LocalProcessRunner {
290 command: CommandTemplate,
291}
292
293impl LocalProcessRunner {
294 pub fn new(command: CommandTemplate) -> Self {
296 Self { command }
297 }
298}
299
300impl Runner for LocalProcessRunner {
301 fn command(&self) -> &CommandTemplate {
302 &self.command
303 }
304
305 fn capabilities(&self) -> RunnerCapabilities {
306 RunnerCapabilities {
307 terminal_input: false,
308 completion_script_execution: true,
309 }
310 }
311
312 fn run(&self, invocation: &Invocation) -> Result<InvocationResult, RunnerError> {
313 if matches!(invocation.stdin, StdinMode::Terminal(_)) {
314 return Err(RunnerError::UnsupportedCapability {
315 capability: "terminal input",
316 });
317 }
318
319 let mut command = Command::new(self.command.program());
320 command
321 .args(self.command.prefix_args())
322 .args(&invocation.args)
323 .stdin(if matches!(invocation.stdin, StdinMode::Piped(_)) {
324 Stdio::piped()
325 } else {
326 Stdio::null()
327 })
328 .stdout(Stdio::piped())
329 .stderr(Stdio::piped());
330 #[cfg(unix)]
331 command.process_group(0);
332 if let Some(current_dir) = &invocation.current_dir {
333 command.current_dir(current_dir);
334 }
335 for change in &invocation.environment {
336 match &change.value {
337 Some(value) => {
338 command.env(&change.name, value);
339 }
340 None => {
341 command.env_remove(&change.name);
342 }
343 }
344 }
345
346 let started = Instant::now();
347 let mut child = spawn_child(command).map_err(|source| RunnerError::Launch {
348 program: self.command.program().to_string_lossy().into_owned(),
349 source,
350 })?;
351 let stdout =
352 take_stdout(&mut child).ok_or(RunnerError::MissingPipe { stream: "stdout" })?;
353 let stderr =
354 take_stderr(&mut child).ok_or(RunnerError::MissingPipe { stream: "stderr" })?;
355 let stdout_reader = read_pipe(stdout, invocation.capture_limit);
356 let stderr_reader = read_pipe(stderr, invocation.capture_limit);
357
358 let stdin_writer = if let StdinMode::Piped(input) = &invocation.stdin {
359 let mut stdin =
360 take_stdin(&mut child).ok_or(RunnerError::MissingPipe { stream: "stdin" })?;
361 let input = input.clone();
362 Some(thread::spawn(move || stdin.write_all(&input)))
363 } else {
364 None
365 };
366
367 let lifecycle = wait_for_invocation(
368 &mut child,
369 &stdout_reader,
370 &stderr_reader,
371 stdin_writer.as_ref(),
372 invocation
373 .timeout
374 .and_then(|timeout| started.checked_add(timeout)),
375 )?;
376 let (termination, stdout, stderr) = match lifecycle {
377 InvocationLifecycle::Completed(status) => {
378 let stdout = stdout_reader.finish("stdout");
379 let stderr = stderr_reader.finish("stderr");
380 if let Some(stdin_writer) = stdin_writer {
381 join_stdin(stdin_writer)?;
382 }
383 (termination_from_status(status), stdout?, stderr?)
384 }
385 InvocationLifecycle::TimedOut => {
386 let stdout = stdout_reader.finish_after_timeout("stdout");
387 let stderr = stderr_reader.finish_after_timeout("stderr");
388 (Termination::TimedOut, stdout?, stderr?)
389 }
390 };
391
392 Ok(InvocationResult::new(
393 termination,
394 stdout,
395 stderr,
396 started.elapsed(),
397 ))
398 }
399}
400
401#[cfg(unix)]
402fn spawn_child(mut command: Command) -> std::io::Result<ManagedChild> {
403 command.spawn()
404}
405
406#[cfg(windows)]
407fn spawn_child(command: Command) -> std::io::Result<ManagedChild> {
408 let mut command = CommandWrap::from(command);
409 command.wrap(JobObject);
410 command.spawn()
411}
412
413#[cfg(unix)]
414fn take_stdin(child: &mut ManagedChild) -> Option<ChildStdin> {
415 child.stdin.take()
416}
417
418#[cfg(windows)]
419fn take_stdin(child: &mut ManagedChild) -> Option<ChildStdin> {
420 child.stdin().take()
421}
422
423#[cfg(unix)]
424fn take_stdout(child: &mut ManagedChild) -> Option<ChildStdout> {
425 child.stdout.take()
426}
427
428#[cfg(windows)]
429fn take_stdout(child: &mut ManagedChild) -> Option<ChildStdout> {
430 child.stdout().take()
431}
432
433#[cfg(unix)]
434fn take_stderr(child: &mut ManagedChild) -> Option<ChildStderr> {
435 child.stderr.take()
436}
437
438#[cfg(windows)]
439fn take_stderr(child: &mut ManagedChild) -> Option<ChildStderr> {
440 child.stderr().take()
441}
442
443fn join_stdin(handle: thread::JoinHandle<std::io::Result<()>>) -> Result<(), RunnerError> {
444 let result = handle.join().map_err(|_| RunnerError::WriterPanicked)?;
445 match result {
446 Ok(()) => Ok(()),
447 Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => Ok(()),
448 Err(source) => Err(RunnerError::WriteStdin { source }),
449 }
450}
451
452struct PipeCapture {
453 output: Arc<Mutex<CapturedOutput>>,
454 handle: thread::JoinHandle<std::io::Result<()>>,
455 capture_limit: Option<usize>,
456}
457
458#[derive(Clone, Default)]
459struct CapturedOutput {
460 bytes: Vec<u8>,
461 limit_exceeded: bool,
462}
463
464impl PipeCapture {
465 fn is_finished(&self) -> bool {
466 self.handle.is_finished()
467 }
468
469 fn finish(self, stream: &'static str) -> Result<Vec<u8>, RunnerError> {
470 let Self {
471 output,
472 handle,
473 capture_limit,
474 } = self;
475 handle
476 .join()
477 .map_err(|_| RunnerError::ReaderPanicked { stream })?
478 .map_err(|source| RunnerError::ReadPipe { stream, source })?;
479 captured_result(snapshot_output(&output), stream, capture_limit)
480 }
481
482 fn finish_after_timeout(self, stream: &'static str) -> Result<Vec<u8>, RunnerError> {
483 let drain_deadline = Instant::now() + Duration::from_millis(100);
484 while !self.handle.is_finished() && Instant::now() < drain_deadline {
485 thread::sleep(Duration::from_millis(1));
486 }
487 if self.handle.is_finished() {
488 let Self {
489 output,
490 handle,
491 capture_limit,
492 } = self;
493 handle
494 .join()
495 .map_err(|_| RunnerError::ReaderPanicked { stream })?
496 .map_err(|source| RunnerError::ReadPipe { stream, source })?;
497 return captured_result(snapshot_output(&output), stream, capture_limit);
498 }
499 let output = self.snapshot();
500 captured_result(output, stream, self.capture_limit)
501 }
502
503 fn snapshot(&self) -> CapturedOutput {
504 self.output
505 .lock()
506 .unwrap_or_else(std::sync::PoisonError::into_inner)
507 .clone()
508 }
509}
510
511fn captured_result(
512 output: CapturedOutput,
513 stream: &'static str,
514 capture_limit: Option<usize>,
515) -> Result<Vec<u8>, RunnerError> {
516 if output.limit_exceeded {
517 return Err(RunnerError::OutputLimitExceeded {
518 stream,
519 limit: capture_limit.unwrap_or(output.bytes.len()),
520 });
521 }
522 Ok(output.bytes)
523}
524
525fn snapshot_output(output: &Mutex<CapturedOutput>) -> CapturedOutput {
526 output
527 .lock()
528 .unwrap_or_else(std::sync::PoisonError::into_inner)
529 .to_owned()
530}
531
532fn read_pipe(mut pipe: impl Read + Send + 'static, capture_limit: Option<usize>) -> PipeCapture {
533 let output = Arc::new(Mutex::new(CapturedOutput::default()));
534 let writer = Arc::clone(&output);
535 let handle = thread::spawn(move || {
536 let mut buffer = [0_u8; 8192];
537 loop {
538 let count = pipe.read(&mut buffer)?;
539 if count == 0 {
540 return Ok(());
541 }
542 let mut output = writer
543 .lock()
544 .unwrap_or_else(std::sync::PoisonError::into_inner);
545 let retained = capture_limit.map_or(count, |limit| {
546 let remaining = limit.saturating_sub(output.bytes.len());
547 if count > remaining {
548 output.limit_exceeded = true;
549 }
550 count.min(remaining)
551 });
552 output.bytes.extend_from_slice(&buffer[..retained]);
553 }
554 });
555 PipeCapture {
556 output,
557 handle,
558 capture_limit,
559 }
560}
561
562enum InvocationLifecycle {
563 Completed(ExitStatus),
564 TimedOut,
565}
566
567fn wait_for_invocation(
568 child: &mut ManagedChild,
569 stdout: &PipeCapture,
570 stderr: &PipeCapture,
571 stdin: Option<&thread::JoinHandle<std::io::Result<()>>>,
572 deadline: Option<Instant>,
573) -> Result<InvocationLifecycle, RunnerError> {
574 let mut status = None;
575 loop {
576 if status.is_none() {
577 status = child
578 .try_wait()
579 .map_err(|source| RunnerError::Wait { source })?;
580 }
581 let stdin_finished = stdin.is_none_or(thread::JoinHandle::is_finished);
582 if let Some(status) = status
583 && stdout.is_finished()
584 && stderr.is_finished()
585 && stdin_finished
586 {
587 return Ok(InvocationLifecycle::Completed(status));
588 }
589 if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
590 terminate_child_tree(child, status.is_some())?;
591 if status.is_none() {
592 child
593 .wait()
594 .map_err(|source| RunnerError::Wait { source })?;
595 }
596 return Ok(InvocationLifecycle::TimedOut);
597 }
598 thread::sleep(Duration::from_millis(5));
599 }
600}
601
602#[cfg(unix)]
603fn terminate_child_tree(child: &mut ManagedChild, leader_exited: bool) -> Result<(), RunnerError> {
604 use nix::errno::Errno;
605 use nix::sys::signal::{Signal, killpg};
606 use nix::unistd::Pid;
607
608 match killpg(Pid::from_raw(child.id() as i32), Signal::SIGKILL) {
609 Ok(()) => Ok(()),
610 Err(Errno::ESRCH) if leader_exited => Ok(()),
611 Err(error) => child.kill().map_err(|source| RunnerError::Kill {
612 source: if source.kind() == std::io::ErrorKind::InvalidInput {
613 std::io::Error::from_raw_os_error(error as i32)
614 } else {
615 source
616 },
617 }),
618 }
619}
620
621#[cfg(windows)]
622fn terminate_child_tree(child: &mut ManagedChild, _leader_exited: bool) -> Result<(), RunnerError> {
623 child
624 .start_kill()
625 .map_err(|source| RunnerError::Kill { source })
626}
627
628fn termination_from_status(status: ExitStatus) -> Termination {
629 status
630 .code()
631 .map_or(Termination::Signaled, |code| Termination::Exited { code })
632}
633
634#[derive(Debug, Error)]
636#[non_exhaustive]
637pub enum RunnerError {
638 #[error("failed to launch candidate program {program}: {source}")]
640 Launch {
641 program: String,
643 #[source]
645 source: std::io::Error,
646 },
647 #[error("runner does not support {capability}")]
649 UnsupportedCapability {
650 capability: &'static str,
652 },
653 #[error("candidate {stream} pipe was unavailable")]
655 MissingPipe {
656 stream: &'static str,
658 },
659 #[error("failed to write candidate stdin: {source}")]
661 WriteStdin {
662 #[source]
664 source: std::io::Error,
665 },
666 #[error("failed while waiting for candidate: {source}")]
668 Wait {
669 #[source]
671 source: std::io::Error,
672 },
673 #[error("failed to terminate timed-out candidate: {source}")]
675 Kill {
676 #[source]
678 source: std::io::Error,
679 },
680 #[error("failed to read candidate {stream}: {source}")]
682 ReadPipe {
683 stream: &'static str,
685 #[source]
687 source: std::io::Error,
688 },
689 #[error("candidate {stream} exceeded the {limit}-byte output capture limit")]
691 OutputLimitExceeded {
692 stream: &'static str,
694 limit: usize,
696 },
697 #[error("candidate {stream} reader panicked")]
699 ReaderPanicked {
700 stream: &'static str,
702 },
703 #[error("candidate stdin writer panicked")]
705 WriterPanicked,
706}
707
708#[cfg(test)]
709mod tests {
710 use std::io::{self, Read};
711
712 use super::{RunnerError, read_pipe};
713
714 struct FailingReader;
715
716 impl Read for FailingReader {
717 fn read(&mut self, _buffer: &mut [u8]) -> io::Result<usize> {
718 Err(io::Error::other("injected pipe read failure"))
719 }
720 }
721
722 #[test]
723 fn timed_out_capture_should_preserve_completed_pipe_read_failure() {
724 let error = read_pipe(FailingReader, None)
725 .finish_after_timeout("stdout")
726 .expect_err("a completed pipe read failure should not become a timeout result");
727
728 assert!(matches!(
729 error,
730 RunnerError::ReadPipe {
731 stream: "stdout",
732 source,
733 } if source.kind() == io::ErrorKind::Other
734 ));
735 }
736}