Skip to main content

artifactize_core/process/
capture.rs

1//! Draining a child's output pipes into its bounded capture, its evidence files and the lines a
2//! Tool log shows. How each pipe ended and whether its evidence was saved are kept apart, so a
3//! slow disk is never taken for a process that still holds a pipe.
4
5use std::{io, path::PathBuf, time::Duration};
6
7use tokio::{
8    io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
9    time::{Instant, timeout},
10};
11use tokio_util::sync::CancellationToken;
12
13use crate::{
14    platform,
15    tools::human::log::{Lines, Stream},
16};
17
18/// Drain process pipes in small bounded chunks without one read per byte.
19const CAPTURE_BUFFER_BYTES: usize = 8192;
20/// The end of a stream kept beside its prefix: enough lines for a failed command's issue to
21/// say why, whatever it printed before.
22pub(crate) const TAIL_BYTES: usize = 4096;
23
24/// How long a pipe may stay open once the process group is gone. Only a process outside the
25/// group can hold it then, such as a descendant that left the group. The time counts only
26/// while the pipe is waited for, never while its evidence is written, and it is generous
27/// because waiting costs nothing unless such a process exists, while a late wakeup on a busy
28/// runtime must not pass for one.
29pub(crate) const OUTPUT_CLOSE_GRACE: Duration = Duration::from_secs(5);
30
31/// How reading one pipe ended.
32#[derive(Debug)]
33pub(super) enum PipeEnd {
34    /// Every writer closed it.
35    Closed,
36    /// Still open [`OUTPUT_CLOSE_GRACE`] after the process group was gone.
37    Open,
38    Failed(io::Error),
39}
40
41/// One stream's capture: what was read of it, how its pipe ended and whether its evidence was
42/// saved.
43#[derive(Debug)]
44pub(super) struct Captured {
45    pub output: Vec<u8>,
46    pub truncated: bool,
47    /// Its last [`TAIL_BYTES`] bytes.
48    pub tail: Vec<u8>,
49    pub pipe: PipeEnd,
50    pub evidence: io::Result<()>,
51}
52
53/// Read `pipe` to its end, keeping its first `limit` bytes and writing all of it to `path` and
54/// `lines`. Once `gone` is cancelled, waiting for the pipe is limited to
55/// [`OUTPUT_CLOSE_GRACE`] in all.
56pub(super) async fn capture(
57    mut pipe: impl AsyncRead + Unpin,
58    limit: usize,
59    path: Option<PathBuf>,
60    mut lines: Option<Lines>,
61    gone: &CancellationToken,
62) -> Captured {
63    let mut evidence = Evidence::open(path);
64    let mut output = Vec::new();
65    let mut tail = Vec::new();
66    let mut buffer = [0; CAPTURE_BUFFER_BYTES];
67    let mut truncated = false;
68    let mut grace = OUTPUT_CLOSE_GRACE;
69    let pipe_end = loop {
70        let count = match read(&mut pipe, &mut buffer, gone, &mut grace).await {
71            Some(Ok(0)) => break PipeEnd::Closed,
72            Some(Ok(count)) => count,
73            Some(Err(error)) => break PipeEnd::Failed(error),
74            None => break PipeEnd::Open,
75        };
76        let chunk = &buffer[..count];
77        evidence.write(chunk).await;
78        if let Some(lines) = &mut lines {
79            lines.push(chunk);
80        }
81        let retained = count.min(limit - output.len());
82        output.extend_from_slice(&chunk[..retained]);
83        truncated |= retained < count;
84        tail.extend_from_slice(chunk);
85        if tail.len() > 2 * TAIL_BYTES {
86            tail.drain(..tail.len() - TAIL_BYTES);
87        }
88    };
89    if tail.len() > TAIL_BYTES {
90        tail.drain(..tail.len() - TAIL_BYTES);
91    }
92    if let Some(lines) = &mut lines {
93        lines.finish();
94    }
95    let evidence = evidence.finish(matches!(pipe_end, PipeEnd::Closed)).await;
96    Captured {
97        output,
98        truncated,
99        tail,
100        pipe: pipe_end,
101        evidence,
102    }
103}
104
105/// One read of `pipe`: unbounded while the process group runs, then within what is left of
106/// `grace`, which the time spent waiting here uses up. `None` when it ran out.
107async fn read(
108    pipe: &mut (impl AsyncRead + Unpin),
109    buffer: &mut [u8],
110    gone: &CancellationToken,
111    grace: &mut Duration,
112) -> Option<io::Result<usize>> {
113    if !gone.is_cancelled() {
114        // A pipe read is cancel safe: a read dropped here has taken no bytes.
115        tokio::select! {
116            biased;
117            read = pipe.read(buffer) => return Some(read),
118            () = gone.cancelled() => {}
119        }
120    }
121    let started = Instant::now();
122    let read = timeout(*grace, pipe.read(buffer));
123    #[cfg(test)]
124    platform::pipe_grace_armed();
125    let read = read.await;
126    *grace = grace.saturating_sub(started.elapsed());
127    read.ok()
128}
129
130/// A stream's evidence file. A failed write ends the evidence, not the draining, so the pipe is
131/// still read to its end and the failure is reported once it is.
132enum Evidence {
133    Disabled,
134    Open {
135        path: PathBuf,
136        file: tokio::fs::File,
137    },
138    Failed(io::Error),
139}
140
141impl Evidence {
142    fn open(path: Option<PathBuf>) -> Self {
143        let Some(path) = path else {
144            return Self::Disabled;
145        };
146        let mut options = platform::private_options();
147        options.write(true).create_new(true);
148        match options.open(&path) {
149            Ok(file) => Self::Open {
150                path,
151                file: tokio::fs::File::from_std(file),
152            },
153            Err(error) => Self::Failed(error),
154        }
155    }
156
157    async fn write(&mut self, chunk: &[u8]) {
158        let Self::Open { file, .. } = self else {
159            return;
160        };
161        #[cfg(test)]
162        slow_disk::wait().await;
163        // Flushed at once, so captured evidence is available while the process still runs.
164        let written = async {
165            file.write_all(chunk).await?;
166            file.flush().await
167        };
168        if let Err(error) = written.await {
169            *self = Self::Failed(error);
170        }
171    }
172
173    /// Flush the file and, when the pipe was `closed`, mark the stream complete beside it.
174    async fn finish(self, closed: bool) -> io::Result<()> {
175        let (path, mut file) = match self {
176            Self::Disabled => return Ok(()),
177            Self::Failed(failure) => return Err(failure),
178            Self::Open { path, file } => (path, file),
179        };
180        #[cfg(test)]
181        slow_disk::wait().await;
182        file.flush().await?;
183        if closed {
184            let mut options = platform::private_options();
185            options.write(true).create_new(true);
186            let extension = path.extension().expect("stream extension");
187            options
188                .open(path.with_extension(format!("{}.complete", extension.to_string_lossy())))?;
189        }
190        Ok(())
191    }
192}
193
194/// What failed in capturing one stream.
195#[derive(Debug)]
196pub enum StreamFailure {
197    /// Its pipe was still open [`OUTPUT_CLOSE_GRACE`] after the process group was gone.
198    Open,
199    /// Its pipe could not be read.
200    Read(io::Error),
201    /// Its evidence file could not be written.
202    Evidence(io::Error),
203}
204
205/// A capture failure with all the run had come to: how the process ended and the output read.
206#[derive(Debug, thiserror::Error)]
207#[error("process output could not be captured: {}; {}", failure_text(&self.failures), end_text(&self.output.status))]
208pub struct CaptureError {
209    pub output: super::Output,
210    /// Each failure with its stream, never empty.
211    pub failures: Vec<(Stream, StreamFailure)>,
212}
213
214fn failure_text(failures: &[(Stream, StreamFailure)]) -> String {
215    failures
216        .iter()
217        .map(|(stream, failure)| {
218            let stream = match stream {
219                Stream::Stdout => "stdout",
220                Stream::Stderr => "stderr",
221            };
222            match failure {
223                StreamFailure::Open => format!(
224                    "{stream} was still open {}s after the process group was gone, so a process \
225                     outside the group holds it",
226                    OUTPUT_CLOSE_GRACE.as_secs()
227                ),
228                StreamFailure::Read(error) => format!("{stream} could not be read: {error}"),
229                StreamFailure::Evidence(error) => {
230                    format!("{stream} could not be saved: {error}")
231                }
232            }
233        })
234        .collect::<Vec<_>>()
235        .join("; ")
236}
237
238fn end_text(status: &platform::ProcessOutcome) -> String {
239    format!("the process had ended ({status})")
240}
241
242impl Captured {
243    /// The output read, and what failed.
244    fn split(
245        self,
246    ) -> (
247        (Vec<u8>, bool, Vec<u8>),
248        impl Iterator<Item = StreamFailure>,
249    ) {
250        let pipe = match self.pipe {
251            PipeEnd::Closed => None,
252            PipeEnd::Open => Some(StreamFailure::Open),
253            PipeEnd::Failed(error) => Some(StreamFailure::Read(error)),
254        };
255        let evidence = self.evidence.err().map(StreamFailure::Evidence);
256        (
257            (self.output, self.truncated, self.tail),
258            pipe.into_iter().chain(evidence),
259        )
260    }
261}
262
263/// Combine how the process ended with its two streams' captures.
264pub(super) fn finish(
265    status: platform::ProcessOutcome,
266    stdout: Captured,
267    stderr: Captured,
268    duration: Duration,
269) -> Result<super::Output, super::Error> {
270    let ((stdout, stdout_truncated, stdout_tail), stdout_failures) = stdout.split();
271    let ((stderr, stderr_truncated, stderr_tail), stderr_failures) = stderr.split();
272    let failures: Vec<_> = stdout_failures
273        .map(|failure| (Stream::Stdout, failure))
274        .chain(stderr_failures.map(|failure| (Stream::Stderr, failure)))
275        .collect();
276    let output = super::Output {
277        status,
278        stdout,
279        stderr,
280        truncated: stdout_truncated || stderr_truncated,
281        stdout_tail,
282        stderr_tail,
283        duration,
284    };
285    if failures.is_empty() {
286        Ok(output)
287    } else {
288        Err(super::Error::Capture(Box::new(CaptureError {
289            output,
290            failures,
291        })))
292    }
293}
294
295/// Tests stand in for a slow disk by holding every evidence write on their thread until
296/// released.
297#[cfg(test)]
298#[path = "capture/tests/slow_disk.rs"]
299pub(crate) mod slow_disk;