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