Skip to main content

wasi_virt_layer_cli/
fallback_command.rs

1use std::{
2    fs::File,
3    io::{Read as _, Seek as _},
4    path::Path,
5};
6
7use eyre::Context as _;
8use fs2::FileExt as _;
9use tempfile::Builder as TempFileBuilder;
10
11/// A command that can fall back to a Rust function if the binary is not found.
12pub struct FallbackCommand<F>
13where
14    F: FnOnce(&[String]) -> i32 + Send + 'static,
15{
16    bin: String,
17    args: Vec<String>,
18    func: Option<F>,
19}
20
21const DISABLE_FALLBACK: bool = true;
22
23/// A file-based lock to prevent concurrent execution of commands.
24pub struct CommandLock(File);
25
26impl<F> FallbackCommand<F>
27where
28    F: FnOnce(&[String]) -> i32 + Send + 'static,
29{
30    /// Creates a new `FallbackCommand` with the specified binary and fallback function.
31    pub fn new(bin: impl AsRef<str>, func: F) -> Self {
32        Self {
33            bin: bin.as_ref().to_string(),
34            args: Vec::new(),
35            func: Some(func),
36        }
37    }
38
39    /// Adds an argument to the command.
40    pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self {
41        self.args.push(arg.as_ref().to_string());
42        self
43    }
44
45    /// Adds multiple arguments to the command.
46    pub fn args<I, S>(&mut self, args: I) -> &mut Self
47    where
48        I: IntoIterator<Item = S>,
49        S: AsRef<str>,
50    {
51        for arg in args {
52            self.arg(arg.as_ref());
53        }
54        self
55    }
56
57    /// Spawns the command, either as a child process or as a fallback thread.
58    pub fn spawn(&mut self) -> std::io::Result<FallbackChild> {
59        let mut cmd = std::process::Command::new(&self.bin);
60        cmd.args(&self.args);
61        let piped_out = std::process::Stdio::piped();
62        let piped_err = std::process::Stdio::piped();
63        cmd.stdout(piped_out);
64        cmd.stderr(piped_err);
65        match cmd.spawn() {
66            Ok(child) => Ok(FallbackChild::new_process(child)),
67            Err(e) if e.kind() == std::io::ErrorKind::NotFound && DISABLE_FALLBACK => {
68                let _ = self.func.take();
69                Err(e)
70            }
71            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
72                // Fallback to the provided function
73                let args = self.args.clone();
74                let func = self.func.take().expect("Function already taken");
75                let handle = std::thread::spawn(move || {
76                    let log = std::fs::OpenOptions::new()
77                        .truncate(true)
78                        .read(true)
79                        .create(true)
80                        .write(true)
81                        .open(get_temp_filepath())
82                        .unwrap();
83
84                    let print_redirect = gag::Redirect::stdout(log).unwrap();
85
86                    let result = (func)(&args);
87
88                    // Extract redirect
89                    let mut log = print_redirect.into_inner();
90
91                    let mut buf = String::new();
92                    log.seek(std::io::SeekFrom::Start(0)).unwrap();
93                    log.read_to_string(&mut buf).unwrap();
94
95                    FallbackOutput {
96                        stdout: buf.into_bytes(),
97                        stderr: Vec::new(),
98                        success: result == 0,
99                    }
100                });
101                Ok(FallbackChild::new_thread(handle))
102            }
103            Err(e) => Err(e),
104        }
105    }
106}
107
108/// A handle to a spawned fallback command, which could be a process or a thread.
109pub enum FallbackChild {
110    /// A child process handle.
111    Process(std::process::Child),
112    /// A handle to a thread running the fallback function.
113    Thread(std::thread::JoinHandle<FallbackOutput>),
114}
115
116impl FallbackChild {
117    fn new_process(child: std::process::Child) -> Self {
118        FallbackChild::Process(child)
119    }
120
121    fn new_thread(handle: std::thread::JoinHandle<FallbackOutput>) -> Self {
122        FallbackChild::Thread(handle)
123    }
124
125    /// Waits for the command to finish and returns its output.
126    pub fn wait_with_output(self) -> std::io::Result<FallbackOutput> {
127        match self {
128            FallbackChild::Process(child) => {
129                let output = child.wait_with_output()?;
130                Ok(FallbackOutput {
131                    stdout: output.stdout,
132                    stderr: output.stderr,
133                    success: output.status.success(),
134                })
135            }
136            FallbackChild::Thread(handle) => {
137                let out = handle.join().expect("Thread panicked");
138                Ok(out)
139            }
140        }
141    }
142}
143
144/// The output of a finished fallback command.
145pub struct FallbackOutput {
146    /// The standard output of the command.
147    pub stdout: Vec<u8>,
148    /// The standard error of the command.
149    pub stderr: Vec<u8>,
150    /// Whether the command exited successfully.
151    pub success: bool,
152}
153
154impl CommandLock {
155    /// Acquires the command lock.
156    pub fn acquire() -> eyre::Result<Self> {
157        let lock_path = get_temp_lock_filepath();
158
159        if let Some(parent) = Path::new(&lock_path).parent() {
160            std::fs::create_dir_all(parent).wrap_err_with(|| {
161                format!("Failed to create temp lock dir: {}", parent.display())
162            })?;
163        }
164
165        let lock_file = File::create(&lock_path)
166            .wrap_err_with(|| format!("Failed to create lock file: {lock_path}"))?;
167        lock_file
168            .lock_exclusive()
169            .wrap_err_with(|| format!("Failed to lock command file: {lock_path}"))?;
170
171        Ok(Self(lock_file))
172    }
173}
174
175impl Drop for CommandLock {
176    fn drop(&mut self) {
177        let _ = self.0.unlock();
178    }
179}
180
181fn get_temp_filepath() -> String {
182    let mut builder = TempFileBuilder::new();
183    let prefix = format!("tmp_{}_", env!("CARGO_PKG_NAME"));
184    builder.prefix(&prefix);
185    builder.suffix(".log");
186
187    #[cfg(windows)]
188    let builder = builder.tempfile_in(dirs::data_local_dir().unwrap().join("Temp"));
189
190    #[cfg(unix)]
191    let builder = builder.tempfile_in("/tmp");
192
193    let file = builder.expect("Failed to create temp log file");
194    let (_file, path) = file.keep().expect("Failed to persist temp log file");
195
196    path.to_string_lossy().into_owned()
197}
198
199fn get_temp_lock_filepath() -> String {
200    #[cfg(windows)]
201    return dirs::data_local_dir()
202        .unwrap()
203        .join("Temp")
204        .join(env!("CARGO_PKG_NAME"))
205        .join("command.lock")
206        .to_string_lossy()
207        .into();
208
209    #[cfg(unix)]
210    return Path::new("/tmp")
211        .join(env!("CARGO_PKG_NAME"))
212        .join("command.lock")
213        .to_string_lossy()
214        .into_owned();
215}
216
217/// require mutex
218pub fn check_gag() -> bool {
219    pub fn check_gag() -> Option<()> {
220        let gag = gag::Redirect::stdout(
221            std::fs::OpenOptions::new()
222                .truncate(true)
223                .read(true)
224                .create(true)
225                .write(true)
226                .open(get_temp_filepath())
227                .ok()?,
228        )
229        .ok()?;
230
231        const WHITE_SPACE: &str = " \t\n\r";
232
233        print!("{WHITE_SPACE}");
234        std::io::Write::flush(&mut std::io::stdout()).ok()?;
235
236        let mut stdout = gag.into_inner();
237        let mut buf = String::new();
238        stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
239        stdout.read_to_string(&mut buf).ok()?;
240
241        Some(if buf.contains(WHITE_SPACE) {
242            ()
243        } else {
244            return None;
245        })
246    }
247
248    check_gag().is_some()
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
256
257    #[test]
258    /// if not use nocapture arg, skip test.
259    /// because gag crate require it.
260    fn test_fallback_command() {
261        if DISABLE_FALLBACK {
262            return;
263        }
264
265        let _lock = MUTEX.lock().unwrap();
266        if !check_gag() {
267            return;
268        }
269
270        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
271            println!("Fallback function called with args: {:?}", args);
272            0
273        });
274        cmd.arg("arg1").arg("arg2");
275
276        let child = cmd.spawn().expect("Failed to spawn command");
277        let output = child.wait_with_output().expect("Failed to get output");
278
279        assert!(output.success);
280        let stdout_str = String::from_utf8_lossy(&output.stdout);
281        assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
282
283        drop(_lock);
284    }
285
286    #[cfg(feature = "fallback")]
287    #[test]
288    fn test_fallback_wasm_merge() {
289        let _lock = MUTEX.lock().unwrap();
290        if !check_gag() {
291            return;
292        }
293
294        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
295            wasm_merge_sys::run_wasm_merge(&args)
296        });
297        cmd.arg("--help");
298
299        let child = cmd.spawn().expect("Failed to spawn command");
300        let output = child.wait_with_output().expect("Failed to get output");
301
302        assert!(output.success);
303        let stdout_str = String::from_utf8_lossy(&output.stdout);
304        panic!("Output: {}", stdout_str);
305
306        drop(_lock);
307    }
308}