1use std::fmt;
5use std::io;
6use std::process::{Command, Stdio};
7use std::sync::Arc;
8use std::thread::{Builder, Scope as Threads, ScopedJoinHandle};
9use std::time::{Duration, Instant};
10
11use crate::notice::Notice;
12use crate::{Cancel, Escalation, Group, Outcome, Scope, Signal, Status, StopReason, sys};
13
14mod output;
15mod pipes;
16
17#[cfg(test)]
18mod tests;
19
20use self::output::Keeper;
21pub use self::output::{Capture, Captured, OverLimit};
22use self::pipes::{Ends, Kept};
23
24pub const DRAIN_GRACE: Duration = Duration::from_secs(1);
28
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum Input {
33 #[default]
35 Null,
36 Bytes(Vec<u8>),
39 Inherit,
43}
44
45#[derive(Clone, Debug, Default)]
55pub struct RunOptions {
56 stdin: Input,
57 stdout: Capture,
58 stderr: Capture,
59 deadline: Option<Instant>,
60 cancel: Option<Cancel>,
61 escalation: Escalation,
62 scope: Scope,
63}
64
65impl RunOptions {
66 #[must_use]
68 pub fn new() -> Self {
69 Self::default()
70 }
71
72 #[must_use]
74 pub fn stdin(mut self, input: Input) -> Self {
75 self.stdin = input;
76 self
77 }
78
79 #[must_use]
81 pub fn stdout(mut self, capture: Capture) -> Self {
82 self.stdout = capture;
83 self
84 }
85
86 #[must_use]
88 pub fn stderr(mut self, capture: Capture) -> Self {
89 self.stderr = capture;
90 self
91 }
92
93 #[must_use]
96 pub const fn deadline(mut self, deadline: Instant) -> Self {
97 self.deadline = Some(deadline);
98 self
99 }
100
101 #[must_use]
103 pub fn cancel(mut self, cancel: &Cancel) -> Self {
104 self.cancel = Some(cancel.clone());
105 self
106 }
107
108 #[must_use]
110 pub fn escalation(mut self, escalation: Escalation) -> Self {
111 self.escalation = escalation;
112 self
113 }
114
115 #[must_use]
117 pub const fn scope(mut self, scope: Scope) -> Self {
118 self.scope = scope;
119 self
120 }
121
122 fn stopping(&self) {
125 self.stdout.stopping();
126 self.stderr.stopping();
127 }
128
129 fn drain_until(&self, deadline: Instant) {
132 self.stdout.drain_until(deadline);
133 self.stderr.drain_until(deadline);
134 }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct ChildFinished {
140 outcome: Outcome,
141 status: Option<Status>,
142 stdout: Captured,
143 stderr: Captured,
144 first_stdout: Option<Duration>,
145}
146
147impl ChildFinished {
148 #[must_use]
150 pub const fn outcome(&self) -> Outcome {
151 self.outcome
152 }
153
154 #[must_use]
163 pub const fn status(&self) -> Option<Status> {
164 self.status
165 }
166
167 #[must_use]
169 pub const fn stdout(&self) -> &Captured {
170 &self.stdout
171 }
172
173 #[must_use]
175 pub const fn stderr(&self) -> &Captured {
176 &self.stderr
177 }
178
179 #[must_use]
181 pub fn into_output(self) -> (Captured, Captured) {
182 (self.stdout, self.stderr)
183 }
184
185 #[must_use]
189 pub const fn first_stdout(&self) -> Option<Duration> {
190 self.first_stdout
191 }
192}
193
194#[derive(Debug)]
196#[non_exhaustive]
197pub enum RunError {
198 Start(io::Error),
200 Run(io::Error),
203}
204
205impl fmt::Display for RunError {
206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207 f.write_str(match self {
208 Self::Start(_) => "cannot start the program",
209 Self::Run(_) => "cannot follow the program to its end",
210 })
211 }
212}
213
214impl std::error::Error for RunError {
215 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
216 match self {
217 Self::Start(error) | Self::Run(error) => Some(error),
218 }
219 }
220}
221
222pub fn run(mut command: Command, options: &RunOptions) -> Result<ChildFinished, RunError> {
257 let _end = EndLines(options);
258 if options.cancel.as_ref().is_some_and(Cancel::is_cancelled) {
259 return Ok(ChildFinished {
260 outcome: Outcome::Stopped(StopReason::Cancelled),
261 status: None,
262 stdout: Captured::default(),
263 stderr: Captured::default(),
264 first_stdout: None,
265 });
266 }
267 let input = match &options.stdin {
268 Input::Null => Stdio::null(),
269 Input::Inherit => Stdio::inherit(),
270 Input::Bytes(_) => Stdio::piped(),
271 };
272 command
273 .stdin(input)
274 .stdout(options.stdout.stdio())
275 .stderr(options.stderr.stdio());
276 let started = Instant::now();
277 let mut group = Group::start(command, options.scope).map_err(RunError::Start)?;
278 let notice = Arc::new(Notice::default());
279 if let Some(cancel) = &options.cancel {
280 cancel.watch(¬ice);
281 }
282 let ends = Ends::default();
283 let followed = std::thread::scope(|threads| {
284 let unwind = Unwind {
285 group: &mut group,
286 ends: &ends,
287 options,
288 };
289 follow(threads, &mut *unwind.group, ¬ice, &ends, options)
290 });
291 let (outcome, status, stdout, stderr) = followed.map_err(RunError::Run)?;
292 Ok(ChildFinished {
293 outcome,
294 status: Some(status),
295 first_stdout: stdout.first.map(|first| first - started),
296 stdout: stdout.captured,
297 stderr: stderr.captured,
298 })
299}
300
301struct EndLines<'run>(&'run RunOptions);
303
304impl Drop for EndLines<'_> {
305 fn drop(&mut self) {
306 self.0.stdout.end();
307 self.0.stderr.end();
308 }
309}
310
311struct Unwind<'a> {
318 group: &'a mut Group,
319 ends: &'a Ends,
320 options: &'a RunOptions,
321}
322
323impl Drop for Unwind<'_> {
324 fn drop(&mut self) {
325 let _ = self.group.signal(Signal::Kill);
328 self.ends.set(Instant::now());
329 self.options.stopping();
330 }
331}
332
333struct Started<'scope> {
335 waiter: ScopedJoinHandle<'scope, io::Result<()>>,
336 stdout: Option<ScopedJoinHandle<'scope, io::Result<Kept>>>,
337 stderr: Option<ScopedJoinHandle<'scope, io::Result<Kept>>>,
338 stdin: Option<ScopedJoinHandle<'scope, ()>>,
339}
340
341fn follow<'scope>(
344 threads: &'scope Threads<'scope, '_>,
345 group: &mut Group,
346 notice: &'scope Notice,
347 ends: &'scope Ends,
348 options: &'scope RunOptions,
349) -> io::Result<(Outcome, Status, Kept, Kept)> {
350 let pipes = (group.take_stdin(), group.take_stdout(), group.take_stderr());
351 let exit = group.waiter();
352 let waiter = match Builder::new().spawn_scoped(threads, move || {
353 let waited = exit.wait();
354 notice.set(|flags| flags.exited = true);
355 waited
356 }) {
357 Ok(waiter) => waiter,
358 Err(error) => {
359 let _ = group.signal(Signal::Kill);
360 let _ = group.reap();
361 return Err(error);
362 }
363 };
364 let mut started = Started {
365 waiter,
366 stdout: None,
367 stderr: None,
368 stdin: None,
369 };
370 let mut failure = start_pipes(threads, &mut started, pipes, notice, ends, options).err();
371 let stopped = if failure.is_some() {
372 stop(group, notice, &Escalation::default(), options);
373 None
374 } else {
375 control(group, notice, options)
376 };
377 let status = group.reap();
378 let reaped = Instant::now();
382 let after = |grace: Duration| reaped.checked_add(grace).unwrap_or(reaped);
383 ends.set(after(DRAIN_GRACE));
384 options.drain_until(after(DRAIN_GRACE / 2));
385 let exited = joined(started.waiter.join());
386 let stdout = started.stdout.map(|reader| joined(reader.join()));
387 let stderr = started.stderr.map(|reader| joined(reader.join()));
388 if let Some(writer) = started.stdin {
389 let _ = writer.join();
390 }
391 if let Some(failure) = failure.take() {
392 return Err(failure);
393 }
394 exited?;
395 let status = sys::status_of(status?);
396 let exit = stopped.unwrap_or(Outcome::Ended(status));
397 let unread = || Kept {
398 captured: Captured::default(),
399 first: None,
400 };
401 Ok((
402 exit,
403 status,
404 stdout.transpose()?.unwrap_or_else(unread),
405 stderr.transpose()?.unwrap_or_else(unread),
406 ))
407}
408
409fn start_pipes<'scope>(
412 threads: &'scope Threads<'scope, '_>,
413 started: &mut Started<'scope>,
414 (stdin, stdout, stderr): (
415 Option<std::process::ChildStdin>,
416 Option<std::process::ChildStdout>,
417 Option<std::process::ChildStderr>,
418 ),
419 notice: &'scope Notice,
420 ends: &'scope Ends,
421 options: &'scope RunOptions,
422) -> io::Result<()> {
423 let over = || notice.set(|flags| flags.over_limit = true);
424 if let Some(stdout) = stdout {
425 let keeper = Keeper::new(&options.stdout);
426 started.stdout = Some(
427 Builder::new()
428 .spawn_scoped(threads, move || pipes::read(stdout, ends, keeper, over))?,
429 );
430 }
431 if let Some(stderr) = stderr {
432 let keeper = Keeper::new(&options.stderr);
433 started.stderr = Some(
434 Builder::new()
435 .spawn_scoped(threads, move || pipes::read(stderr, ends, keeper, over))?,
436 );
437 }
438 if let (Some(stdin), Input::Bytes(bytes)) = (stdin, &options.stdin) {
439 started.stdin =
440 Some(Builder::new().spawn_scoped(threads, move || pipes::write(stdin, bytes, ends))?);
441 }
442 Ok(())
443}
444
445fn control(group: &Group, notice: &Notice, options: &RunOptions) -> Option<Outcome> {
449 let flags = notice.wait(options.deadline, |flags| {
450 flags.exited || flags.cancelled || flags.over_limit
451 });
452 let exit = if flags.exited {
453 return None;
454 } else if flags.cancelled {
455 Outcome::Stopped(StopReason::Cancelled)
456 } else if flags.over_limit {
457 Outcome::Stopped(StopReason::OverLimit)
458 } else if group.has_exited().unwrap_or(false) {
459 notice.wait(None, |flags| flags.exited);
462 return None;
463 } else {
464 Outcome::TimedOut
465 };
466 stop(group, notice, &options.escalation, options);
467 Some(exit)
468}
469
470fn stop(group: &Group, notice: &Notice, escalation: &Escalation, options: &RunOptions) {
484 options.stopping();
485 if sys::GRACEFUL {
486 for (signal, grace) in escalation.steps() {
487 let _ = group.signal(signal);
488 if notice
489 .wait(Instant::now().checked_add(grace), |flags| flags.exited)
490 .exited
491 {
492 return;
493 }
494 }
495 }
496 let _ = group.signal(Signal::Kill);
497 notice.wait(None, |flags| flags.exited);
498}
499
500fn joined<T>(result: std::thread::Result<io::Result<T>>) -> io::Result<T> {
503 result.unwrap_or_else(|_| Err(io::Error::other("a thread of the run stopped")))
504}