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