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