Skip to main content

verctl_core/runtime/
process.rs

1use std::error::Error;
2use std::fmt;
3use std::io::{self, Read, Write};
4use std::path::Path;
5use std::process::ExitStatus;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::thread::{self, JoinHandle};
9use std::time::Duration;
10
11use anyhow::{Context, Result, bail, ensure};
12
13use crate::{env, registry_token};
14
15/// How long a driver command may run.
16pub const DEFAULT_TIMEOUT: Duration = Duration::from_mins(1);
17/// How many bytes a driver command may print before it is killed.
18pub const DEFAULT_OUTPUT_LIMIT: usize = 8 * 1024 * 1024;
19
20/// Run an argv with stdin piped and stdout captured.
21///
22/// `duct` owns the pipe lifetime so a streaming child cannot deadlock
23/// the parent the way a sequential `write_all` + `wait_with_output` can.
24/// stdout/stderr are read incrementally and killed at `output_limit`.
25///
26/// # Errors
27///
28/// Returns an error in the same cases as [`filter_limited`], called with the
29/// default timeout and output limit.
30pub fn filter(argv: &[String], stdin: &str, env: &[(&str, &str)]) -> Result<String> {
31    filter_limited(argv, stdin, env, DEFAULT_TIMEOUT, DEFAULT_OUTPUT_LIMIT)
32}
33
34/// Run an argv with no stdin. Used by `release`.
35///
36/// # Errors
37///
38/// Returns an error in the same cases as [`filter_limited`], called with the
39/// given `timeout` and the default output limit.
40pub fn run_limited(argv: &[String], env: &[(&str, &str)], timeout: Duration) -> Result<String> {
41    filter_limited(argv, "", env, timeout, DEFAULT_OUTPUT_LIMIT)
42}
43
44/// The most stderr [`run_inherit`] keeps for its error message.
45const STDERR_TAIL: usize = 64 * 1024;
46
47/// Stream the command's stdout and stderr to this process's stderr.
48/// Actions then show cargo/bun as they run, and stdout contains only verctl's
49/// own report, so `--format json` stays parseable.
50/// The error keeps the last 64 KiB of the streamed output.
51/// A caller such as `release` reads it to recognise an already-published
52/// version.
53///
54/// # Errors
55///
56/// Returns an error when:
57///
58/// - `argv` is empty.
59/// - The stderr pipe cannot be created.
60/// - The command cannot be spawned or waited on.
61/// - The command runs longer than `timeout`.
62/// - The command exits unsuccessfully.
63///
64/// A non-zero exit puts the joined argv and the stderr tail in the error.
65pub fn run_inherit(argv: &[String], timeout: Duration) -> Result<()> {
66    run_inherit_in(argv, None, timeout)
67}
68
69/// [`run_inherit`] in `dir`, or in this process's working directory when
70/// `dir` is `None`.
71///
72/// # Errors
73///
74/// Returns an error under the conditions of [`run_inherit`].
75pub fn run_inherit_in(argv: &[String], dir: Option<&Path>, timeout: Duration) -> Result<()> {
76    inherit(argv, dir, &[], timeout)
77}
78
79/// [`run_inherit`], plus `env` set on the command.
80/// Only a command that needs a secret takes this path, such as a publisher
81/// that reads its registry token.
82///
83/// # Errors
84///
85/// Returns an error under the conditions of [`run_inherit`].
86pub fn run_inherit_env(argv: &[String], env: &[(&str, &str)], timeout: Duration) -> Result<()> {
87    inherit(argv, None, env, timeout)
88}
89
90/// The variables that carry GitHub credentials.
91/// A publisher, a dependency build script, and an asset build all run as
92/// children of a job that has a token able to write contents.
93/// None of them inherits one.
94const GITHUB_CREDENTIALS: [&str; 2] = ["GITHUB_TOKEN", "GH_TOKEN"];
95
96/// `argv[0]` with its arguments and `env`, without the variables a registry
97/// token arrives in ([`registry_token::SOURCES`]), the owner's token
98/// ([`registry_token::OWNER`]), a GitHub credential
99/// ([`GITHUB_CREDENTIALS`]), or the packslip key ([`env::PACKSLIP_KEY`]), so no
100/// command verctl starts inherits one.
101///
102/// A command that needs one gets it back through `env` under the variable it
103/// reads. `env` is set inside the removals, so a variable named in both stays
104/// set. duct applies the outermost call first, which makes the innermost win.
105fn command(argv: &[String], env: &[(&str, &str)]) -> duct::Expression {
106    let expression = env.iter().fold(
107        duct::cmd(&argv[0], &argv[1..]),
108        |expression, (key, value)| expression.env(key, value),
109    );
110    registry_token::SOURCES
111        .iter()
112        .chain(&[registry_token::OWNER, env::PACKSLIP_KEY])
113        .chain(&GITHUB_CREDENTIALS)
114        .fold(expression, |expression, variable| {
115            expression.env_remove(variable)
116        })
117}
118
119fn inherit(
120    argv: &[String],
121    dir: Option<&Path>,
122    env: &[(&str, &str)],
123    timeout: Duration,
124) -> Result<()> {
125    ensure!(!argv.is_empty(), "driver argv is empty");
126    let (stderr_r, stderr_w) = os_pipe::pipe().context("command stderr pipe")?;
127    let mut expression = command(argv, env);
128    if let Some(dir) = dir {
129        expression = expression.dir(dir);
130    }
131    // duct applies the outer redirect first, so stdout joins the pipe.
132    let handle = expression
133        .stdout_to_stderr()
134        .stderr_file(stderr_w)
135        .unchecked()
136        .start()
137        .context("spawn command")?;
138    let tail = thread::spawn(move || stream_tail(stderr_r));
139    let waited = match handle.wait_timeout(timeout) {
140        Ok(output) => output.is_some(),
141        Err(error) => {
142            let _ = handle.kill();
143            let _ = handle.wait();
144            let _ = tail.join();
145            return Err(error).context("command");
146        }
147    };
148    if !waited {
149        let _ = handle.kill();
150        let _ = handle.wait();
151        let _ = tail.join();
152        bail!("command timed out after {timeout:?}");
153    }
154    #[expect(
155        clippy::map_err_ignore,
156        reason = "a thread join error is a panic payload (`Box<dyn Any>`), not an `Error`, so it cannot be a source"
157    )]
158    let stderr = tail
159        .join()
160        .map_err(|_| anyhow::anyhow!("stderr reader panicked"))?;
161    let status = handle
162        .try_wait()
163        .context("command")?
164        .context("command exited without a status")?
165        .status;
166    if !status.success() {
167        bail!(
168            "command failed: {}: {}",
169            argv.join(" "),
170            String::from_utf8_lossy(&stderr).trim()
171        );
172    }
173    Ok(())
174}
175
176/// Copies `reader` to this process's stderr and returns its last
177/// [`STDERR_TAIL`] bytes.
178fn stream_tail(mut reader: impl Read) -> Vec<u8> {
179    let mut tail = Vec::new();
180    let mut chunk = [0_u8; 8192];
181    let mut stderr = io::stderr();
182    loop {
183        match reader.read(&mut chunk) {
184            Ok(0) | Err(_) => return tail,
185            Ok(read) => {
186                let _ = stderr.write_all(&chunk[..read]);
187                tail.extend_from_slice(&chunk[..read]);
188                if tail.len() > STDERR_TAIL {
189                    tail.drain(..tail.len() - STDERR_TAIL);
190                }
191            }
192        }
193    }
194}
195
196/// `["cargo", "publish"]` without a `.into()` on every word.
197#[must_use]
198pub fn argv(parts: &[&str]) -> Vec<String> {
199    parts.iter().map(|part| (*part).to_owned()).collect()
200}
201
202/// [`filter`] with an explicit timeout and output limit.
203///
204/// # Errors
205///
206/// Returns an error when:
207///
208/// - `argv` is empty.
209/// - The pipes cannot be created.
210/// - The command cannot be spawned or waited on.
211/// - The command runs longer than `timeout`.
212/// - The command prints more than `output_limit` bytes on either stream.
213/// - The command exits unsuccessfully.
214/// - Its stdout is not UTF-8.
215///
216/// An unsuccessful exit puts the argv, status, and trimmed stderr in the
217/// error.
218pub fn filter_limited(
219    argv: &[String],
220    stdin: &str,
221    env: &[(&str, &str)],
222    timeout: Duration,
223    output_limit: usize,
224) -> Result<String> {
225    capture(argv, stdin, env, None, timeout, output_limit)
226}
227
228/// Run an argv in `dir` with `env` set, no stdin, and stdout captured.
229/// A registry `query` runs this way in the package directory, where the
230/// registry config of the publisher is in effect.
231///
232/// # Errors
233///
234/// Returns an error when:
235///
236/// - `argv` is empty.
237/// - The command cannot be spawned.
238/// - The command runs longer than `timeout`, which returns a [`TimedOut`].
239/// - Its output passes [`DEFAULT_OUTPUT_LIMIT`].
240/// - Its stdout is not UTF-8.
241/// - The command exits unsuccessfully, which returns an [`ExitFailure`].
242///
243/// A caller can downcast an [`ExitFailure`] to tell an answer apart from a
244/// failure to run.
245pub fn run_in(
246    argv: &[String],
247    dir: &Path,
248    env: &[(&str, &str)],
249    timeout: Duration,
250) -> Result<String> {
251    capture(argv, "", env, Some(dir), timeout, DEFAULT_OUTPUT_LIMIT)
252}
253
254/// A command that ran to completion and exited unsuccessfully.
255#[derive(Debug)]
256pub struct ExitFailure {
257    /// The argv, joined with spaces.
258    pub command: String,
259    /// How it exited.
260    pub status: ExitStatus,
261    /// Its stderr, trimmed.
262    pub stderr: String,
263}
264
265impl fmt::Display for ExitFailure {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        let Self {
268            command,
269            status,
270            stderr,
271        } = self;
272        if stderr.is_empty() {
273            write!(f, "driver command failed: {command}: {status}")
274        } else {
275            write!(f, "driver command failed: {command}: {status}: {stderr}")
276        }
277    }
278}
279
280impl Error for ExitFailure {}
281
282/// A command that ran longer than its timeout and was killed.
283#[derive(Debug)]
284pub struct TimedOut {
285    /// How long it was allowed to run.
286    pub timeout: Duration,
287}
288
289impl fmt::Display for TimedOut {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        write!(f, "driver command timed out after {:?}", self.timeout)
292    }
293}
294
295impl Error for TimedOut {}
296
297fn capture(
298    argv: &[String],
299    stdin: &str,
300    env: &[(&str, &str)],
301    dir: Option<&Path>,
302    timeout: Duration,
303    output_limit: usize,
304) -> Result<String> {
305    ensure!(!argv.is_empty(), "driver argv is empty");
306    let mut expr = command(argv, env);
307    if let Some(dir) = dir {
308        expr = expr.dir(dir);
309    }
310    let (stdout_r, stdout_w) = os_pipe::pipe().context("driver stdout pipe")?;
311    let (stderr_r, stderr_w) = os_pipe::pipe().context("driver stderr pipe")?;
312    let handle = Arc::new(
313        expr.stdin_bytes(stdin.as_bytes().to_vec())
314            .stdout_file(stdout_w)
315            .stderr_file(stderr_w)
316            .unchecked()
317            .start()
318            .context("spawn driver command")?,
319    );
320    let mut guard = ChildGuard {
321        handle: Arc::clone(&handle),
322        reaped: false,
323    };
324    let exceeded = Arc::new(AtomicBool::new(false));
325    let stdout_h = spawn_capped(
326        stdout_r,
327        output_limit,
328        Arc::clone(&handle),
329        Arc::clone(&exceeded),
330    );
331    let stderr_h = spawn_capped(
332        stderr_r,
333        output_limit,
334        Arc::clone(&handle),
335        Arc::clone(&exceeded),
336    );
337
338    let waited = match handle.wait_timeout(timeout) {
339        Ok(output) => output.is_some(),
340        Err(error) => {
341            let _ = handle.kill();
342            let _ = handle.wait();
343            let _ = take_capped(stdout_h);
344            let _ = take_capped(stderr_h);
345            guard.reaped = true;
346            return Err(error).context("driver command");
347        }
348    };
349    if !waited {
350        let _ = handle.kill();
351        let _ = handle.wait();
352        let _ = take_capped(stdout_h);
353        let _ = take_capped(stderr_h);
354        guard.reaped = true;
355        return Err(TimedOut { timeout }.into());
356    }
357
358    let stdout = take_capped(stdout_h)?;
359    let stderr = take_capped(stderr_h)?;
360    guard.reaped = true;
361
362    if exceeded.load(Ordering::SeqCst) {
363        bail!("driver command output exceeded {output_limit} bytes");
364    }
365    let status = handle
366        .try_wait()
367        .context("driver command")?
368        .context("driver exited without a status")?
369        .status;
370    if !status.success() {
371        return Err(ExitFailure {
372            command: argv.join(" "),
373            status,
374            stderr: String::from_utf8_lossy(&stderr).trim().to_owned(),
375        }
376        .into());
377    }
378    String::from_utf8(stdout).context("driver stdout is not UTF-8")
379}
380
381struct ChildGuard {
382    handle: Arc<duct::Handle>,
383    reaped: bool,
384}
385
386impl Drop for ChildGuard {
387    fn drop(&mut self) {
388        if !self.reaped {
389            let _ = self.handle.kill();
390            let _ = self.handle.try_wait();
391        }
392    }
393}
394
395enum CapRead {
396    Bytes(Vec<u8>),
397    Exceeded,
398}
399
400fn spawn_capped(
401    reader: os_pipe::PipeReader,
402    limit: usize,
403    handle: Arc<duct::Handle>,
404    exceeded: Arc<AtomicBool>,
405) -> JoinHandle<io::Result<CapRead>> {
406    thread::spawn(move || {
407        let result = read_capped(reader, limit);
408        if matches!(result, Ok(CapRead::Exceeded)) {
409            exceeded.store(true, Ordering::SeqCst);
410            let _ = handle.kill();
411        }
412        result
413    })
414}
415
416fn read_capped(mut reader: os_pipe::PipeReader, limit: usize) -> io::Result<CapRead> {
417    let mut buf = Vec::new();
418    let mut chunk = [0_u8; 8192];
419    loop {
420        let n = reader.read(&mut chunk)?;
421        if n == 0 {
422            return Ok(CapRead::Bytes(buf));
423        }
424        if buf.len().saturating_add(n) > limit {
425            return Ok(CapRead::Exceeded);
426        }
427        buf.extend_from_slice(&chunk[..n]);
428    }
429}
430
431fn take_capped(handle: JoinHandle<io::Result<CapRead>>) -> Result<Vec<u8>> {
432    match handle.join() {
433        Ok(Ok(CapRead::Bytes(bytes))) => Ok(bytes),
434        Ok(Ok(CapRead::Exceeded)) => bail!("driver command output exceeded the cap"),
435        Ok(Err(error)) => Err(error).context("read driver output"),
436        Err(_) => bail!("driver output reader panicked"),
437    }
438}
439
440#[cfg(test)]
441mod tests;