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