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