Skip to main content

base/interface/exec/
process.rs

1//! `Process` — running a program somewhere.
2
3use futures::future::BoxFuture;
4use futures::stream::BoxStream;
5use std::path::PathBuf;
6use tokio_util::sync::CancellationToken;
7
8use super::ExecError;
9
10/// What to run. A shell command is one of these by the time it gets here:
11/// `bash -c <command>`. There is deliberately no separate shell contract —
12/// two execution contracts would mean two places a sandbox has to be attached,
13/// and therefore two places it can be missed.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ProcessSpec {
16    pub program: String,
17    pub args: Vec<String>,
18    pub cwd: PathBuf,
19    /// Added to whatever the provider's own environment is. Not a replacement:
20    /// a remote provider's environment is not this machine's to dictate.
21    pub env: Vec<(String, String)>,
22    /// How much of the provider's own environment the process starts from.
23    pub env_scope: super::env::EnvScope,
24    pub stdin: Option<Vec<u8>>,
25}
26
27impl ProcessSpec {
28    pub fn new(program: impl Into<String>, cwd: impl Into<PathBuf>) -> Self {
29        Self {
30            program: program.into(),
31            args: Vec::new(),
32            cwd: cwd.into(),
33            env: Vec::new(),
34            env_scope: super::env::EnvScope::Session,
35            stdin: None,
36        }
37    }
38
39    pub fn arg(mut self, a: impl Into<String>) -> Self {
40        self.args.push(a.into());
41        self
42    }
43
44    pub fn args<I: IntoIterator<Item = S>, S: Into<String>>(mut self, it: I) -> Self {
45        self.args.extend(it.into_iter().map(Into::into));
46        self
47    }
48}
49
50/// How long output may keep arriving once the process itself has exited.
51///
52/// A background process the command started inherits its pipes, and they stay
53/// open as long as it runs. Reading on to EOF would wait for that process, not
54/// for the command; past this a reader stops and treats what it has as the
55/// output.
56pub const OUTPUT_GRACE_AFTER_EXIT: std::time::Duration = std::time::Duration::from_secs(1);
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum OutputStream {
60    Stdout,
61    Stderr,
62}
63
64/// A piece of output, tagged with where it came from.
65///
66/// One stream rather than two, because a remote provider has one channel and
67/// splitting it would make ordering a provider's problem to reinvent. A
68/// consumer that wants the two separated accumulates two buffers; a consumer
69/// that wants them interleaved already has them in order.
70///
71/// Bytes rather than lines: line splitting is a consumer's concern, and a
72/// provider that split for them would be deciding what a line is on output
73/// that may not have any.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct OutputChunk {
76    pub stream: OutputStream,
77    pub bytes: Vec<u8>,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub struct ExitStatus {
82    /// `None` when the process was killed by a signal.
83    pub code: Option<i32>,
84    pub success: bool,
85}
86
87/// A process that has started.
88pub trait ProcessHandle: Send {
89    /// The output, incrementally. `None` after the first call — the stream
90    /// owns the pipes.
91    ///
92    /// **Streaming is a requirement, not an optimization.** A long-running
93    /// command's output reaches the user while it runs; a provider that
94    /// returned everything at the end would remove that silently.
95    fn output(&mut self) -> Option<BoxStream<'static, Result<OutputChunk, ExecError>>>;
96
97    /// Stop it and whatever it started that is still running. Best effort,
98    /// and idempotent; also valid after `wait`, for the descendants that
99    /// outlived it.
100    fn kill(&mut self) -> BoxFuture<'_, ()>;
101
102    /// Wait for it to finish.
103    fn wait(&mut self) -> BoxFuture<'_, Result<ExitStatus, ExecError>>;
104}
105
106/// Where a program runs.
107#[async_trait::async_trait]
108pub trait Process: Send + Sync {
109    async fn spawn(
110        &self,
111        spec: ProcessSpec,
112        cancel: CancellationToken,
113    ) -> Result<Box<dyn ProcessHandle>, ExecError>;
114}