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