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 output(
104 mut self,
105 input: Vec<u8>,
106 cancellation: CancellationToken,
107 ) -> Result<Output, process::Error> {
108 self.command.cwd = self.cwd;
109 process::run_unregistered(
110 self.command,
111 Some(input),
112 process::OUTPUT_LIMIT,
113 cancellation,
114 )
115 .await
116 }
117
118 pub(crate) async fn tool_output(
120 mut self,
121 input: Vec<u8>,
122 output_limit: usize,
123 cancellation: CancellationToken,
124 ) -> Result<Output, process::Error> {
125 self.command.cwd = self.cwd;
126 process::run_unregistered(self.command, Some(input), output_limit, cancellation).await
127 }
128}
129
130#[derive(
131 Debug,
132 Clone,
133 Copy,
134 PartialEq,
135 Eq,
136 PartialOrd,
137 Ord,
138 serde::Serialize,
139 serde::Deserialize,
140 clap::ValueEnum,
141)]
142#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
143#[value(rename_all = "SCREAMING_SNAKE_CASE")]
144pub enum Verdict {
145 Green,
146 Red,
147}
148
149impl Verdict {
150 pub fn as_str(self) -> &'static str {
151 match self {
152 Self::Green => "GREEN",
153 Self::Red => "RED",
154 }
155 }
156}
157
158impl std::fmt::Display for Verdict {
159 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160 formatter.write_str(self.as_str())
161 }
162}
163
164#[derive(Debug)]
165pub struct ReviewResult {
166 pub exit_code: i32,
167 pub output: Output,
168}
169
170impl ReviewResult {
171 pub fn verdict(&self) -> Verdict {
172 if self.exit_code == 0 {
173 Verdict::Green
174 } else {
175 Verdict::Red
176 }
177 }
178}
179
180#[derive(Debug)]
182pub enum Outcome {
183 Completed(ReviewResult),
184 OperationalError(Error),
185}
186
187#[derive(Debug, Error)]
188pub enum Error {
189 #[error("timeoutMs must be between 1 and 2147483647")]
190 InvalidTimeout,
191 #[error("runtime output directory must be outside the review workspace")]
192 OutputInsideWorkspace,
193 #[error("runtime environment preparation failed: {0}")]
194 Environment(#[from] io::Error),
195 #[error(transparent)]
196 Process(#[from] process::Error),
197 #[error("runtime process terminated without a verdict (signal {signal:?})")]
198 AbnormalExit {
199 signal: Option<i32>,
200 output: Box<Output>,
201 },
202}
203
204pub struct Execution {
206 cancellation: CancellationToken,
207 supervisor: tokio::task::JoinHandle<Outcome>,
208}
209
210impl Execution {
211 pub async fn wait(&mut self) -> Outcome {
214 let _cancel_on_drop = self.cancellation.clone().drop_guard();
215 crate::task::joined((&mut self.supervisor).await)
216 .unwrap_or_else(|error| Outcome::OperationalError(Error::Process(error.into())))
217 }
218}
219
220impl Drop for Execution {
221 fn drop(&mut self) {
222 self.cancellation.cancel();
223 }
224}
225
226pub async fn execute<F, R>(
229 command: Command,
230 cancellation: CancellationToken,
231 register: F,
232) -> Outcome
233where
234 F: FnOnce(ChildIdentity) -> R + Send + 'static,
235 R: Future<Output = io::Result<()>> + Send + 'static,
236{
237 start(command, cancellation, register).wait().await
238}
239
240pub fn start<F, R>(command: Command, cancellation: CancellationToken, register: F) -> Execution
242where
243 F: FnOnce(ChildIdentity) -> R + Send + 'static,
244 R: Future<Output = io::Result<()>> + Send + 'static,
245{
246 let cancellation = cancellation.child_token();
247 let supervisor = tokio::spawn(supervise(command, cancellation.clone(), register));
248 Execution {
249 cancellation,
250 supervisor,
251 }
252}
253
254async fn supervise<F, R>(
255 mut command: Command,
256 cancellation: CancellationToken,
257 register: F,
258) -> Outcome
259where
260 F: FnOnce(ChildIdentity) -> R + Send + 'static,
261 R: Future<Output = io::Result<()>> + Send + 'static,
262{
263 command.command.cwd = command.cwd;
264 let scratch = command.directory.join("tmp");
267 let result =
268 process::run_logged(command.command, command.directory, cancellation, register).await;
269 let cleanup = crate::task::joined(
270 tokio::task::spawn_blocking(move || crate::platform::remove_tree(&scratch)).await,
271 )
272 .map_err(io::Error::other)
273 .and_then(std::convert::identity);
274 if let Err(error) = cleanup
275 && error.kind() != io::ErrorKind::NotFound
276 && result.is_ok()
277 {
278 return Outcome::OperationalError(Error::Environment(error));
279 }
280 match result {
281 Ok(mut output) => {
282 output.stdout = clean_output(&output.stdout);
283 output.stderr = clean_output(&output.stderr);
284 match output.status.end() {
285 crate::platform::ProcessEnd::Exited(exit_code) => {
286 Outcome::Completed(ReviewResult { exit_code, output })
287 }
288 crate::platform::ProcessEnd::Signaled(signal) => {
289 Outcome::OperationalError(Error::AbnormalExit {
290 signal,
291 output: Box::new(output),
292 })
293 }
294 }
295 }
296 Err(error) => Outcome::OperationalError(Error::Process(error)),
297 }
298}
299
300pub(crate) use artifactize_tools::result::clean_output;