Skip to main content

wasi_virt_layer_cli/
fallback_command.rs

1use std::{
2    fs::File,
3    io::{Read as _, Seek as _, Write 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 {
80    locks: Vec<(File, String)>,
81}
82
83impl<F> FallbackCommand<F>
84where
85    F: FnOnce(&[String]) -> i32 + Send + 'static,
86{
87    /// Creates a new `FallbackCommand` with the specified binary and fallback function.
88    pub fn new(bin: impl AsRef<str>, func: F) -> Self {
89        Self {
90            bin: bin.as_ref().to_string(),
91            args: Vec::new(),
92            func: Some(func),
93        }
94    }
95
96    /// Adds an argument to the command.
97    pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self {
98        self.args.push(arg.as_ref().to_string());
99        self
100    }
101
102    /// Adds multiple arguments to the command.
103    pub fn args<I, S>(&mut self, args: I) -> &mut Self
104    where
105        I: IntoIterator<Item = S>,
106        S: AsRef<str>,
107    {
108        for arg in args {
109            self.arg(arg.as_ref());
110        }
111        self
112    }
113
114    /// Spawns the command, either as a child process or as a fallback thread.
115    pub fn spawn(&mut self) -> std::io::Result<FallbackChild> {
116        let mut cmd = std::process::Command::new(&self.bin);
117        let setter = |cmd: &mut std::process::Command| {
118            cmd.args(&self.args);
119            let piped_out = std::process::Stdio::piped();
120            let piped_err = std::process::Stdio::piped();
121            cmd.stdout(piped_out);
122            cmd.stderr(piped_err);
123        };
124        setter(&mut cmd);
125        match cmd.spawn() {
126            Ok(child) => Ok(FallbackChild::new_process(child)),
127            Err(e) if e.kind() == std::io::ErrorKind::NotFound && DISABLE_FALLBACK => {
128                let _ = self.func.take();
129                Err(e)
130            }
131            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
132                // // Fallback to the provided function
133                // let args = self.args.clone();
134                // let func = self.func.take().expect("Function already taken");
135                // let handle = std::thread::spawn(move || {
136                //     let log = std::fs::OpenOptions::new()
137                //         .truncate(true)
138                //         .read(true)
139                //         .create(true)
140                //         .write(true)
141                //         .open(get_temp_filepath())
142                //         .unwrap();
143
144                //     let print_redirect = gag::Redirect::stdout(log).unwrap();
145
146                //     let result = (func)(&args);
147
148                //     // Extract redirect
149                //     let mut log = print_redirect.into_inner();
150
151                //     let mut buf = String::new();
152                //     log.seek(std::io::SeekFrom::Start(0)).unwrap();
153                //     log.read_to_string(&mut buf).unwrap();
154
155                //     FallbackOutput {
156                //         stdout: buf.into_bytes(),
157                //         stderr: Vec::new(),
158                //         success: result == 0,
159                //     }
160                // });
161                // Ok(FallbackChild::new_thread(handle))
162
163                // Fallback to self call with env var
164                let mut cmd = std::process::Command::new(std::env::current_exe().unwrap());
165                setter(&mut cmd);
166                cmd.env(COMMAND_ALTERNATE_ENV_VAR, &self.bin);
167                let child = cmd.spawn()?;
168                Ok(FallbackChild::new_process(child))
169            }
170            Err(e) => Err(e),
171        }
172    }
173}
174
175/// A handle to a spawned fallback command, which could be a process or a thread.
176pub enum FallbackChild {
177    /// A child process handle.
178    Process(std::process::Child),
179    /// A handle to a thread running the fallback function.
180    Thread(std::thread::JoinHandle<FallbackOutput>),
181}
182
183impl FallbackChild {
184    fn new_process(child: std::process::Child) -> Self {
185        FallbackChild::Process(child)
186    }
187
188    #[allow(unused)]
189    fn new_thread(handle: std::thread::JoinHandle<FallbackOutput>) -> Self {
190        FallbackChild::Thread(handle)
191    }
192
193    /// Waits for the command to finish and returns its output.
194    pub fn wait_with_output(self) -> std::io::Result<FallbackOutput> {
195        match self {
196            FallbackChild::Process(child) => {
197                let output = child.wait_with_output()?;
198                Ok(FallbackOutput {
199                    stdout: output.stdout,
200                    stderr: output.stderr,
201                    success: output.status.success(),
202                })
203            }
204            FallbackChild::Thread(handle) => {
205                let out = handle.join().expect("Thread panicked");
206                Ok(out)
207            }
208        }
209    }
210}
211
212/// The output of a finished fallback command.
213pub struct FallbackOutput {
214    /// The standard output of the command.
215    pub stdout: Vec<u8>,
216    /// The standard error of the command.
217    pub stderr: Vec<u8>,
218    /// Whether the command exited successfully.
219    pub success: bool,
220}
221
222impl CommandLock {
223    /// Acquires the command locks for the specified identifiers using a master-lock strategy to prevent deadlocks.
224    pub fn acquire(ids: &[String]) -> eyre::Result<Self> {
225        let mut sorted_ids = ids.to_vec();
226        sorted_ids.sort();
227        sorted_ids.dedup();
228
229        // 1. Ensure temp dir exists
230        let temp_dir = std::env::temp_dir().join(env!("CARGO_PKG_NAME"));
231        std::fs::create_dir_all(&temp_dir).wrap_err("Failed to create temp lock directory")?;
232
233        // 2. Acquire Master Lock to serialize acquisition phase
234        let master_path = temp_dir.join("master.lock");
235        let master_file = File::options()
236            .read(true)
237            .write(true)
238            .create(true)
239            .open(&master_path)
240            .wrap_err_with(|| {
241                format!("Failed to open master lock file: {}", master_path.display())
242            })?;
243
244        master_file
245            .lock_exclusive()
246            .wrap_err("Failed to acquire master lock")?;
247
248        let mut locks = Vec::new();
249
250        // 3. Acquire individual locks while holding the master lock
251        for id in sorted_ids {
252            let hash = {
253                use std::hash::{Hash, Hasher};
254                let mut hasher = std::collections::hash_map::DefaultHasher::new();
255                id.hash(&mut hasher);
256                format!("{:x}", hasher.finish())
257            };
258
259            let lock_path = get_temp_lock_filepath(&hash);
260            let lock_file = File::options()
261                .read(true)
262                .write(true)
263                .create(true)
264                .open(&lock_path)
265                .wrap_err_with(|| format!("Failed to open lock file: {lock_path}"))?;
266
267            if let Err(_) = lock_file.try_lock_exclusive() {
268                let mut pid_str = String::new();
269                let mut file = &lock_file;
270                let _ = file.read_to_string(&mut pid_str);
271                let pid_info = if pid_str.is_empty() {
272                    String::new()
273                } else {
274                    format!(" (held by PID {})", pid_str.trim())
275                };
276
277                eprintln!("Waiting for command lock for {} {}...", id, pid_info);
278
279                // We are holding the master lock, so we serialize all acquisitions.
280                // If we block here, other processes waiting for DIFFERENT locks will also be blocked
281                // at the master lock. This is acceptable for a CLI tool and prevents deadlock.
282                lock_file
283                    .lock_exclusive()
284                    .wrap_err_with(|| format!("Failed to lock command file: {lock_path}"))?;
285            }
286
287            // Write current PID to the lock file
288            let mut file = &lock_file;
289            let _ = file.set_len(0);
290            let _ = file.seek(std::io::SeekFrom::Start(0));
291            let _ = write!(file, "{}", std::process::id());
292            let _ = file.flush();
293
294            locks.push((lock_file, lock_path));
295        }
296
297        // 4. Release master lock
298        let _ = master_file.unlock();
299
300        Ok(Self { locks })
301    }
302}
303
304impl Drop for CommandLock {
305    fn drop(&mut self) {
306        for (file, _) in &mut self.locks {
307            let _ = file.unlock();
308        }
309    }
310}
311
312fn get_temp_filepath() -> String {
313    let mut builder = TempFileBuilder::new();
314    let prefix = format!("tmp_{}_", env!("CARGO_PKG_NAME"));
315    builder.prefix(&prefix);
316    builder.suffix(".log");
317
318    let builder = builder.tempfile_in(std::env::temp_dir());
319
320    let file = builder.expect("Failed to create temp log file");
321    let (_file, path) = file.keep().expect("Failed to persist temp log file");
322
323    path.to_string_lossy().into_owned()
324}
325
326fn get_temp_lock_filepath(hash: &str) -> String {
327    std::env::temp_dir()
328        .join(env!("CARGO_PKG_NAME"))
329        .join(format!("command_{}.lock", hash))
330        .to_string_lossy()
331        .into_owned()
332}
333
334/// require mutex
335pub fn check_gag() -> bool {
336    pub fn check_gag() -> Option<()> {
337        let gag = gag::Redirect::stdout(
338            std::fs::OpenOptions::new()
339                .truncate(true)
340                .read(true)
341                .create(true)
342                .write(true)
343                .open(get_temp_filepath())
344                .ok()?,
345        )
346        .ok()?;
347
348        const WHITE_SPACE: &str = " \t\n\r";
349
350        print!("{WHITE_SPACE}");
351        std::io::Write::flush(&mut std::io::stdout()).ok()?;
352
353        let mut stdout = gag.into_inner();
354        let mut buf = String::new();
355        stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
356        stdout.read_to_string(&mut buf).ok()?;
357
358        Some(if buf.contains(WHITE_SPACE) {
359            ()
360        } else {
361            return None;
362        })
363    }
364
365    check_gag().is_some()
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
373
374    #[cfg_attr(not(feature = "fallback"), ignore = "fallback feature disabled")]
375    #[test]
376    /// if not use nocapture arg, skip test.
377    /// because gag crate require it.
378    fn test_fallback_command() {
379        if DISABLE_FALLBACK {
380            return;
381        }
382
383        let _lock = MUTEX.lock().unwrap();
384        if !check_gag() {
385            return;
386        }
387
388        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
389            println!("Fallback function called with args: {:?}", args);
390            0
391        });
392        cmd.arg("arg1").arg("arg2");
393
394        let child = cmd.spawn().expect("Failed to spawn command");
395        let output = child.wait_with_output().expect("Failed to get output");
396
397        assert!(output.success);
398        let stdout_str = String::from_utf8_lossy(&output.stdout);
399        assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
400
401        drop(_lock);
402    }
403
404    #[cfg(feature = "fallback")]
405    #[test]
406    fn test_fallback_wasm_merge() {
407        let _lock = MUTEX.lock().unwrap();
408        if !check_gag() {
409            return;
410        }
411
412        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
413            wasm_merge_sys::run_wasm_merge(&args)
414        });
415        cmd.arg("--help");
416
417        let child = cmd.spawn().expect("Failed to spawn command");
418        let output = child.wait_with_output().expect("Failed to get output");
419
420        assert!(output.success);
421        let stdout_str = String::from_utf8_lossy(&output.stdout);
422        panic!("Output: {}", stdout_str);
423
424        drop(_lock);
425    }
426}