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(|| format!("Failed to open master lock file: {}", master_path.display()))?;
241
242        master_file
243            .lock_exclusive()
244            .wrap_err("Failed to acquire master lock")?;
245
246        let mut locks = Vec::new();
247
248        // 3. Acquire individual locks while holding the master lock
249        for id in sorted_ids {
250            let hash = {
251                use std::hash::{Hash, Hasher};
252                let mut hasher = std::collections::hash_map::DefaultHasher::new();
253                id.hash(&mut hasher);
254                format!("{:x}", hasher.finish())
255            };
256
257            let lock_path = get_temp_lock_filepath(&hash);
258            let lock_file = File::options()
259                .read(true)
260                .write(true)
261                .create(true)
262                .open(&lock_path)
263                .wrap_err_with(|| format!("Failed to open lock file: {lock_path}"))?;
264
265            if let Err(_) = lock_file.try_lock_exclusive() {
266                let mut pid_str = String::new();
267                let mut file = &lock_file;
268                let _ = file.read_to_string(&mut pid_str);
269                let pid_info = if pid_str.is_empty() {
270                    String::new()
271                } else {
272                    format!(" (held by PID {})", pid_str.trim())
273                };
274
275                eprintln!("Waiting for command lock for {} {}...", id, pid_info);
276
277                // We are holding the master lock, so we serialize all acquisitions.
278                // If we block here, other processes waiting for DIFFERENT locks will also be blocked
279                // at the master lock. This is acceptable for a CLI tool and prevents deadlock.
280                lock_file
281                    .lock_exclusive()
282                    .wrap_err_with(|| format!("Failed to lock command file: {lock_path}"))?;
283            }
284
285            // Write current PID to the lock file
286            let mut file = &lock_file;
287            let _ = file.set_len(0);
288            let _ = file.seek(std::io::SeekFrom::Start(0));
289            let _ = write!(file, "{}", std::process::id());
290            let _ = file.flush();
291
292            locks.push((lock_file, lock_path));
293        }
294
295        // 4. Release master lock
296        let _ = master_file.unlock();
297
298        Ok(Self { locks })
299    }
300}
301
302impl Drop for CommandLock {
303    fn drop(&mut self) {
304        for (file, _) in &mut self.locks {
305            let _ = file.unlock();
306        }
307    }
308}
309
310fn get_temp_filepath() -> String {
311    let mut builder = TempFileBuilder::new();
312    let prefix = format!("tmp_{}_", env!("CARGO_PKG_NAME"));
313    builder.prefix(&prefix);
314    builder.suffix(".log");
315
316    let builder = builder.tempfile_in(std::env::temp_dir());
317
318    let file = builder.expect("Failed to create temp log file");
319    let (_file, path) = file.keep().expect("Failed to persist temp log file");
320
321    path.to_string_lossy().into_owned()
322}
323
324fn get_temp_lock_filepath(hash: &str) -> String {
325    std::env::temp_dir()
326        .join(env!("CARGO_PKG_NAME"))
327        .join(format!("command_{}.lock", hash))
328        .to_string_lossy()
329        .into_owned()
330}
331
332/// require mutex
333pub fn check_gag() -> bool {
334    pub fn check_gag() -> Option<()> {
335        let gag = gag::Redirect::stdout(
336            std::fs::OpenOptions::new()
337                .truncate(true)
338                .read(true)
339                .create(true)
340                .write(true)
341                .open(get_temp_filepath())
342                .ok()?,
343        )
344        .ok()?;
345
346        const WHITE_SPACE: &str = " \t\n\r";
347
348        print!("{WHITE_SPACE}");
349        std::io::Write::flush(&mut std::io::stdout()).ok()?;
350
351        let mut stdout = gag.into_inner();
352        let mut buf = String::new();
353        stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
354        stdout.read_to_string(&mut buf).ok()?;
355
356        Some(if buf.contains(WHITE_SPACE) {
357            ()
358        } else {
359            return None;
360        })
361    }
362
363    check_gag().is_some()
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
371
372    #[cfg_attr(not(feature = "fallback"), ignore = "fallback feature disabled")]
373    #[test]
374    /// if not use nocapture arg, skip test.
375    /// because gag crate require it.
376    fn test_fallback_command() {
377        if DISABLE_FALLBACK {
378            return;
379        }
380
381        let _lock = MUTEX.lock().unwrap();
382        if !check_gag() {
383            return;
384        }
385
386        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
387            println!("Fallback function called with args: {:?}", args);
388            0
389        });
390        cmd.arg("arg1").arg("arg2");
391
392        let child = cmd.spawn().expect("Failed to spawn command");
393        let output = child.wait_with_output().expect("Failed to get output");
394
395        assert!(output.success);
396        let stdout_str = String::from_utf8_lossy(&output.stdout);
397        assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
398
399        drop(_lock);
400    }
401
402    #[cfg(feature = "fallback")]
403    #[test]
404    fn test_fallback_wasm_merge() {
405        let _lock = MUTEX.lock().unwrap();
406        if !check_gag() {
407            return;
408        }
409
410        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
411            wasm_merge_sys::run_wasm_merge(&args)
412        });
413        cmd.arg("--help");
414
415        let child = cmd.spawn().expect("Failed to spawn command");
416        let output = child.wait_with_output().expect("Failed to get output");
417
418        assert!(output.success);
419        let stdout_str = String::from_utf8_lossy(&output.stdout);
420        panic!("Output: {}", stdout_str);
421
422        drop(_lock);
423    }
424}