artifactize_core/process/
capture.rs1use 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
18const CAPTURE_BUFFER_BYTES: usize = 8192;
20pub(crate) const TAIL_BYTES: usize = 4096;
23
24pub(crate) const OUTPUT_CLOSE_GRACE: Duration = Duration::from_secs(5);
30
31#[derive(Debug)]
33pub(super) enum PipeEnd {
34 Closed,
36 Open,
38 Failed(io::Error),
39}
40
41#[derive(Debug)]
44pub(super) struct Captured {
45 pub output: Vec<u8>,
46 pub truncated: bool,
47 pub tail: Vec<u8>,
49 pub pipe: PipeEnd,
50 pub evidence: io::Result<()>,
51}
52
53pub(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
105async 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 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
130enum 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 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 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#[derive(Debug)]
196pub enum StreamFailure {
197 Open,
199 Read(io::Error),
201 Evidence(io::Error),
203}
204
205#[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 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 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
263pub(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#[cfg(test)]
298#[path = "capture/tests/slow_disk.rs"]
299pub(crate) mod slow_disk;