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