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