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;
20
21pub(crate) const OUTPUT_CLOSE_GRACE: Duration = Duration::from_secs(5);
27
28#[derive(Debug)]
30pub(super) enum PipeEnd {
31 Closed,
33 Open,
35 Failed(io::Error),
36}
37
38#[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
48pub(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
91async 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 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
116enum 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 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 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#[derive(Debug)]
182pub enum StreamFailure {
183 Open,
185 Read(io::Error),
187 Evidence(io::Error),
189}
190
191#[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 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 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
244pub(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#[cfg(test)]
277pub(crate) mod slow_disk {
278 use std::{cell::RefCell, sync::Arc};
279
280 use tokio::sync::watch;
281
282 type Hold = (watch::Receiver<bool>, Arc<()>);
284
285 thread_local! {
286 static HOLD: RefCell<Option<Hold>> = const { RefCell::new(None) };
287 }
288
289 pub(crate) struct SlowDisk {
291 release: watch::Sender<bool>,
292 waiting: Arc<()>,
293 }
294
295 impl SlowDisk {
296 pub(crate) fn waiting(&self) -> usize {
298 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}