1mod environment;
5
6use std::{
7 ffi::OsString,
8 future::Future,
9 io,
10 path::{Path, PathBuf},
11 time::Duration,
12};
13
14use thiserror::Error;
15use tokio_util::sync::CancellationToken;
16
17use crate::process::{self, ChildIdentity, Output};
18
19pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
22pub const MAX_TIMEOUT: Duration = Duration::from_millis(crate::config::validation::MAX_TIMEOUT_MS);
24
25#[derive(Debug)]
29pub struct Command {
30 pub cwd: PathBuf,
32 command: process::Command,
33 directory: PathBuf,
34}
35
36impl Command {
37 pub fn prepare(
41 program: OsString,
42 args: Vec<OsString>,
43 workspace: &Path,
44 run_dir: &Path,
45 timeout: Option<Duration>,
46 ) -> Result<Self, Error> {
47 Self::prepare_with_env(program, args, workspace, run_dir, timeout, None)
48 }
49
50 pub(crate) fn prepare_with_env(
51 program: OsString,
52 args: Vec<OsString>,
53 workspace: &Path,
54 run_dir: &Path,
55 timeout: Option<Duration>,
56 caller_env: Option<&std::collections::BTreeMap<OsString, OsString>>,
57 ) -> Result<Self, Error> {
58 let timeout = timeout.unwrap_or(DEFAULT_TIMEOUT);
59 if timeout.is_zero() || timeout > MAX_TIMEOUT {
60 return Err(Error::InvalidTimeout);
61 }
62 let (cwd, directory, env) = environment::prepare(workspace, run_dir, caller_env)?;
63 Ok(Self {
64 command: process::Command {
65 program,
66 args,
67 cwd: cwd.clone(),
68 env,
69 timeout,
70 },
71 cwd,
72 directory,
73 })
74 }
75
76 pub(crate) fn session_environment(&mut self, directory: &Path) {
77 crate::platform::environment::set(
78 &mut self.command.env,
79 "ARTIFACTIZE_SESSION_DIR",
80 directory,
81 );
82 }
83
84 pub(crate) fn inherit_session(
86 &mut self,
87 environment: &std::collections::BTreeMap<OsString, OsString>,
88 ) {
89 if let Some(value) =
90 crate::platform::environment::lookup(environment, "ARTIFACTIZE_SESSION_DIR")
91 {
92 crate::platform::environment::set(
93 &mut self.command.env,
94 "ARTIFACTIZE_SESSION_DIR",
95 value,
96 );
97 }
98 }
99
100 pub(crate) fn into_process(mut self) -> process::Command {
101 self.command.cwd = self.cwd;
102 self.command
103 }
104
105 pub fn directory(&self) -> &Path {
106 &self.directory
107 }
108
109 pub fn timeout(&self) -> Duration {
110 self.command.timeout
111 }
112
113 pub(crate) async fn tool_output(
115 mut self,
116 input: Vec<u8>,
117 output_limit: usize,
118 cancellation: CancellationToken,
119 ) -> Result<Output, process::Error> {
120 self.command.cwd = self.cwd;
121 process::run_unregistered(self.command, Some(input), output_limit, cancellation).await
122 }
123}
124
125#[derive(
126 Debug,
127 Clone,
128 Copy,
129 PartialEq,
130 Eq,
131 PartialOrd,
132 Ord,
133 serde::Serialize,
134 serde::Deserialize,
135 clap::ValueEnum,
136)]
137#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
138#[value(rename_all = "SCREAMING_SNAKE_CASE")]
139pub enum Verdict {
140 Green,
141 Red,
142}
143
144impl Verdict {
145 pub fn as_str(self) -> &'static str {
146 match self {
147 Self::Green => "GREEN",
148 Self::Red => "RED",
149 }
150 }
151}
152
153impl std::fmt::Display for Verdict {
154 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 formatter.write_str(self.as_str())
156 }
157}
158
159#[derive(Debug)]
160pub struct ReviewResult {
161 pub exit_code: i32,
162 pub output: Output,
163}
164
165impl ReviewResult {
166 pub fn verdict(&self) -> Verdict {
167 if self.exit_code == 0 {
168 Verdict::Green
169 } else {
170 Verdict::Red
171 }
172 }
173}
174
175#[derive(Debug)]
177pub enum Outcome {
178 Completed(ReviewResult),
179 OperationalError(Error),
180}
181
182#[derive(Debug, Error)]
183pub enum Error {
184 #[error("timeoutMs must be between 1 and 2147483647")]
185 InvalidTimeout,
186 #[error("runtime output directory must be outside the review workspace")]
187 OutputInsideWorkspace,
188 #[error("runtime environment preparation failed: {0}")]
189 Environment(#[from] io::Error),
190 #[error(transparent)]
191 Process(#[from] process::Error),
192 #[error("runtime process terminated without a verdict (signal {signal:?})")]
193 AbnormalExit {
194 signal: Option<i32>,
195 output: Box<Output>,
196 },
197}
198
199pub struct Execution {
201 cancellation: CancellationToken,
202 supervisor: tokio::task::JoinHandle<Outcome>,
203}
204
205impl Execution {
206 pub async fn wait(&mut self) -> Outcome {
209 let _cancel_on_drop = self.cancellation.clone().drop_guard();
210 crate::task::joined((&mut self.supervisor).await)
211 .unwrap_or_else(|error| Outcome::OperationalError(Error::Process(error.into())))
212 }
213}
214
215impl Drop for Execution {
216 fn drop(&mut self) {
217 self.cancellation.cancel();
218 }
219}
220
221pub async fn execute<F, R>(
224 command: Command,
225 cancellation: CancellationToken,
226 register: F,
227) -> Outcome
228where
229 F: FnOnce(ChildIdentity) -> R + Send + 'static,
230 R: Future<Output = io::Result<()>> + Send + 'static,
231{
232 start(command, cancellation, register).wait().await
233}
234
235pub fn start<F, R>(command: Command, cancellation: CancellationToken, register: F) -> Execution
237where
238 F: FnOnce(ChildIdentity) -> R + Send + 'static,
239 R: Future<Output = io::Result<()>> + Send + 'static,
240{
241 let cancellation = cancellation.child_token();
242 let supervisor = tokio::spawn(supervise(command, cancellation.clone(), register));
243 Execution {
244 cancellation,
245 supervisor,
246 }
247}
248
249async fn supervise<F, R>(
250 mut command: Command,
251 cancellation: CancellationToken,
252 register: F,
253) -> Outcome
254where
255 F: FnOnce(ChildIdentity) -> R + Send + 'static,
256 R: Future<Output = io::Result<()>> + Send + 'static,
257{
258 command.command.cwd = command.cwd;
259 let scratch = command.directory.join("tmp");
262 let result =
263 process::run_logged(command.command, command.directory, cancellation, register).await;
264 let cleanup = crate::task::joined(
265 tokio::task::spawn_blocking(move || crate::platform::remove_tree(&scratch)).await,
266 )
267 .map_err(io::Error::other)
268 .and_then(std::convert::identity);
269 if let Err(error) = cleanup
270 && error.kind() != io::ErrorKind::NotFound
271 && result.is_ok()
272 {
273 return Outcome::OperationalError(Error::Environment(error));
274 }
275 match result {
276 Ok(mut output) => {
277 output.stdout = clean_output(&output.stdout);
278 output.stderr = clean_output(&output.stderr);
279 match output.status.end() {
280 crate::platform::ProcessEnd::Exited(exit_code) => {
281 Outcome::Completed(ReviewResult { exit_code, output })
282 }
283 crate::platform::ProcessEnd::Signaled(signal) => {
284 Outcome::OperationalError(Error::AbnormalExit {
285 signal,
286 output: Box::new(output),
287 })
288 }
289 }
290 }
291 Err(error) => Outcome::OperationalError(Error::Process(error)),
292 }
293}
294
295pub(crate) use artifactize_tools::result::clean_output;