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 struct FallbackCommand<F>
12where
13    F: FnOnce(&[String]) -> i32 + Send + 'static,
14{
15    bin: String,
16    args: Vec<String>,
17    func: Option<F>,
18}
19
20const DISABLE_FALLBACK: bool = true;
21
22pub struct CommandLock(File);
23
24impl<F> FallbackCommand<F>
25where
26    F: FnOnce(&[String]) -> i32 + Send + 'static,
27{
28    pub fn new(bin: impl AsRef<str>, func: F) -> Self {
29        Self {
30            bin: bin.as_ref().to_string(),
31            args: Vec::new(),
32            func: Some(func),
33        }
34    }
35
36    pub fn arg(&mut self, arg: impl AsRef<str>) -> &mut Self {
37        self.args.push(arg.as_ref().to_string());
38        self
39    }
40
41    pub fn args<I, S>(&mut self, args: I) -> &mut Self
42    where
43        I: IntoIterator<Item = S>,
44        S: AsRef<str>,
45    {
46        for arg in args {
47            self.arg(arg.as_ref());
48        }
49        self
50    }
51
52    pub fn spawn(&mut self) -> std::io::Result<FallbackChild> {
53        let mut cmd = std::process::Command::new(&self.bin);
54        cmd.args(&self.args);
55        let piped_out = std::process::Stdio::piped();
56        let piped_err = std::process::Stdio::piped();
57        cmd.stdout(piped_out);
58        cmd.stderr(piped_err);
59        match cmd.spawn() {
60            Ok(child) => Ok(FallbackChild::new_process(child)),
61            Err(e) if e.kind() == std::io::ErrorKind::NotFound && DISABLE_FALLBACK => {
62                let _ = self.func.take();
63                Err(e)
64            }
65            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
66                // Fallback to the provided function
67                let args = self.args.clone();
68                let func = self.func.take().expect("Function already taken");
69                let handle = std::thread::spawn(move || {
70                    let log = std::fs::OpenOptions::new()
71                        .truncate(true)
72                        .read(true)
73                        .create(true)
74                        .write(true)
75                        .open(get_temp_filepath())
76                        .unwrap();
77
78                    let print_redirect = gag::Redirect::stdout(log).unwrap();
79
80                    let result = (func)(&args);
81
82                    // Extract redirect
83                    let mut log = print_redirect.into_inner();
84
85                    let mut buf = String::new();
86                    log.seek(std::io::SeekFrom::Start(0)).unwrap();
87                    log.read_to_string(&mut buf).unwrap();
88
89                    FallbackOutput {
90                        stdout: buf.into_bytes(),
91                        stderr: Vec::new(),
92                        success: result == 0,
93                    }
94                });
95                Ok(FallbackChild::new_thread(handle))
96            }
97            Err(e) => Err(e),
98        }
99    }
100}
101
102pub enum FallbackChild {
103    Process(std::process::Child),
104    Thread(std::thread::JoinHandle<FallbackOutput>),
105}
106
107impl FallbackChild {
108    fn new_process(child: std::process::Child) -> Self {
109        FallbackChild::Process(child)
110    }
111
112    fn new_thread(handle: std::thread::JoinHandle<FallbackOutput>) -> Self {
113        FallbackChild::Thread(handle)
114    }
115
116    pub fn wait_with_output(self) -> std::io::Result<FallbackOutput> {
117        match self {
118            FallbackChild::Process(child) => {
119                let output = child.wait_with_output()?;
120                Ok(FallbackOutput {
121                    stdout: output.stdout,
122                    stderr: output.stderr,
123                    success: output.status.success(),
124                })
125            }
126            FallbackChild::Thread(handle) => {
127                let out = handle.join().expect("Thread panicked");
128                Ok(out)
129            }
130        }
131    }
132}
133
134pub struct FallbackOutput {
135    pub stdout: Vec<u8>,
136    pub stderr: Vec<u8>,
137    pub success: bool,
138}
139
140impl CommandLock {
141    pub fn acquire() -> eyre::Result<Self> {
142        let lock_path = get_temp_lock_filepath();
143
144        if let Some(parent) = Path::new(&lock_path).parent() {
145            std::fs::create_dir_all(parent).wrap_err_with(|| {
146                format!("Failed to create temp lock dir: {}", parent.display())
147            })?;
148        }
149
150        let lock_file = File::create(&lock_path)
151            .wrap_err_with(|| format!("Failed to create lock file: {lock_path}"))?;
152        lock_file
153            .lock_exclusive()
154            .wrap_err_with(|| format!("Failed to lock command file: {lock_path}"))?;
155
156        Ok(Self(lock_file))
157    }
158}
159
160impl Drop for CommandLock {
161    fn drop(&mut self) {
162        let _ = self.0.unlock();
163    }
164}
165
166fn get_temp_filepath() -> String {
167    let mut builder = TempFileBuilder::new();
168    let prefix = format!("tmp_{}_", env!("CARGO_PKG_NAME"));
169    builder.prefix(&prefix);
170    builder.suffix(".log");
171
172    #[cfg(windows)]
173    let builder = builder.tempfile_in(dirs::data_local_dir().unwrap().join("Temp"));
174
175    #[cfg(unix)]
176    let builder = builder.tempfile_in("/tmp");
177
178    let file = builder.expect("Failed to create temp log file");
179    let (_file, path) = file.keep().expect("Failed to persist temp log file");
180
181    path.to_string_lossy().into_owned()
182}
183
184fn get_temp_lock_filepath() -> String {
185    #[cfg(windows)]
186    return dirs::data_local_dir()
187        .unwrap()
188        .join("Temp")
189        .join(env!("CARGO_PKG_NAME"))
190        .join("command.lock")
191        .to_string_lossy()
192        .into();
193
194    #[cfg(unix)]
195    return Path::new("/tmp")
196        .join(env!("CARGO_PKG_NAME"))
197        .join("command.lock")
198        .to_string_lossy()
199        .into_owned();
200}
201
202/// require mutex
203pub fn check_gag() -> bool {
204    pub fn check_gag() -> Option<()> {
205        let gag = gag::Redirect::stdout(
206            std::fs::OpenOptions::new()
207                .truncate(true)
208                .read(true)
209                .create(true)
210                .write(true)
211                .open(get_temp_filepath())
212                .ok()?,
213        )
214        .ok()?;
215
216        const WHITE_SPACE: &str = " \t\n\r";
217
218        print!("{WHITE_SPACE}");
219        std::io::Write::flush(&mut std::io::stdout()).ok()?;
220
221        let mut stdout = gag.into_inner();
222        let mut buf = String::new();
223        stdout.seek(std::io::SeekFrom::Start(0)).ok()?;
224        stdout.read_to_string(&mut buf).ok()?;
225
226        Some(if buf.contains(WHITE_SPACE) {
227            ()
228        } else {
229            return None;
230        })
231    }
232
233    check_gag().is_some()
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    static MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
241
242    #[test]
243    /// if not use nocapture arg, skip test.
244    /// because gag crate require it.
245    fn test_fallback_command() {
246        if DISABLE_FALLBACK {
247            return;
248        }
249
250        let _lock = MUTEX.lock().unwrap();
251        if !check_gag() {
252            return;
253        }
254
255        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
256            println!("Fallback function called with args: {:?}", args);
257            0
258        });
259        cmd.arg("arg1").arg("arg2");
260
261        let child = cmd.spawn().expect("Failed to spawn command");
262        let output = child.wait_with_output().expect("Failed to get output");
263
264        assert!(output.success);
265        let stdout_str = String::from_utf8_lossy(&output.stdout);
266        assert!(stdout_str.contains("Fallback function called with args: [\"arg1\", \"arg2\"]"));
267
268        drop(_lock);
269    }
270
271    #[cfg(feature = "fallback")]
272    #[test]
273    fn test_fallback_wasm_merge() {
274        let _lock = MUTEX.lock().unwrap();
275        if !check_gag() {
276            return;
277        }
278
279        let mut cmd = FallbackCommand::new("non_existent_command", |args: &[String]| {
280            wasm_merge_sys::run_wasm_merge(&args)
281        });
282        cmd.arg("--help");
283
284        let child = cmd.spawn().expect("Failed to spawn command");
285        let output = child.wait_with_output().expect("Failed to get output");
286
287        assert!(output.success);
288        let stdout_str = String::from_utf8_lossy(&output.stdout);
289        panic!("Output: {}", stdout_str);
290
291        drop(_lock);
292    }
293}