node_runtime.rs

  1use anyhow::{anyhow, bail, Context, Result};
  2use async_compression::futures::bufread::GzipDecoder;
  3use async_tar::Archive;
  4use serde::Deserialize;
  5use smol::{fs, io::BufReader, lock::Mutex, process::Command};
  6use std::process::{Output, Stdio};
  7use std::{
  8    env::consts,
  9    path::{Path, PathBuf},
 10    sync::Arc,
 11};
 12use util::http::HttpClient;
 13
 14const VERSION: &str = "v18.15.0";
 15
 16#[derive(Debug, Deserialize)]
 17#[serde(rename_all = "kebab-case")]
 18pub struct NpmInfo {
 19    #[serde(default)]
 20    dist_tags: NpmInfoDistTags,
 21    versions: Vec<String>,
 22}
 23
 24#[derive(Debug, Deserialize, Default)]
 25pub struct NpmInfoDistTags {
 26    latest: Option<String>,
 27}
 28
 29#[async_trait::async_trait]
 30pub trait NodeRuntime: Send + Sync {
 31    async fn binary_path(&self) -> Result<PathBuf>;
 32
 33    async fn run_npm_subcommand(
 34        &self,
 35        directory: Option<&Path>,
 36        subcommand: &str,
 37        args: &[&str],
 38    ) -> Result<Output>;
 39
 40    async fn npm_package_latest_version(&self, name: &str) -> Result<String>;
 41
 42    async fn npm_install_packages(&self, directory: &Path, packages: &[(&str, &str)])
 43        -> Result<()>;
 44}
 45
 46pub struct RealNodeRuntime {
 47    http: Arc<dyn HttpClient>,
 48    installation_lock: Mutex<()>,
 49}
 50
 51impl RealNodeRuntime {
 52    pub fn new(http: Arc<dyn HttpClient>) -> Arc<dyn NodeRuntime> {
 53        Arc::new(RealNodeRuntime {
 54            http,
 55            installation_lock: Mutex::new(()),
 56        })
 57    }
 58
 59    async fn install_if_needed(&self) -> Result<PathBuf> {
 60        let _lock = self.installation_lock.lock().await;
 61        log::info!("Node runtime install_if_needed");
 62
 63        let arch = match consts::ARCH {
 64            "x86_64" => "x64",
 65            "aarch64" => "arm64",
 66            other => bail!("Running on unsupported platform: {other}"),
 67        };
 68
 69        let folder_name = format!("node-{VERSION}-darwin-{arch}");
 70        let node_containing_dir = util::paths::SUPPORT_DIR.join("node");
 71        let node_dir = node_containing_dir.join(folder_name);
 72        let node_binary = node_dir.join("bin/node");
 73        let npm_file = node_dir.join("bin/npm");
 74
 75        let result = Command::new(&node_binary)
 76            .env_clear()
 77            .arg(npm_file)
 78            .arg("--version")
 79            .stdin(Stdio::null())
 80            .stdout(Stdio::null())
 81            .stderr(Stdio::null())
 82            .args(["--cache".into(), node_dir.join("cache")])
 83            .args(["--userconfig".into(), node_dir.join("blank_user_npmrc")])
 84            .args(["--globalconfig".into(), node_dir.join("blank_global_npmrc")])
 85            .status()
 86            .await;
 87        let valid = matches!(result, Ok(status) if status.success());
 88
 89        if !valid {
 90            _ = fs::remove_dir_all(&node_containing_dir).await;
 91            fs::create_dir(&node_containing_dir)
 92                .await
 93                .context("error creating node containing dir")?;
 94
 95            let file_name = format!("node-{VERSION}-darwin-{arch}.tar.gz");
 96            let url = format!("https://nodejs.org/dist/{VERSION}/{file_name}");
 97            let mut response = self
 98                .http
 99                .get(&url, Default::default(), true)
100                .await
101                .context("error downloading Node binary tarball")?;
102
103            let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
104            let archive = Archive::new(decompressed_bytes);
105            archive.unpack(&node_containing_dir).await?;
106        }
107
108        // Note: Not in the `if !valid {}` so we can populate these for existing installations
109        _ = fs::create_dir(node_dir.join("cache")).await;
110        _ = fs::write(node_dir.join("blank_user_npmrc"), []).await;
111        _ = fs::write(node_dir.join("blank_global_npmrc"), []).await;
112
113        anyhow::Ok(node_dir)
114    }
115}
116
117#[async_trait::async_trait]
118impl NodeRuntime for RealNodeRuntime {
119    async fn binary_path(&self) -> Result<PathBuf> {
120        let installation_path = self.install_if_needed().await?;
121        Ok(installation_path.join("bin/node"))
122    }
123
124    async fn run_npm_subcommand(
125        &self,
126        directory: Option<&Path>,
127        subcommand: &str,
128        args: &[&str],
129    ) -> Result<Output> {
130        let attempt = || async move {
131            let installation_path = self.install_if_needed().await?;
132
133            let mut env_path = installation_path.join("bin").into_os_string();
134            if let Some(existing_path) = std::env::var_os("PATH") {
135                if !existing_path.is_empty() {
136                    env_path.push(":");
137                    env_path.push(&existing_path);
138                }
139            }
140
141            let node_binary = installation_path.join("bin/node");
142            let npm_file = installation_path.join("bin/npm");
143
144            if smol::fs::metadata(&node_binary).await.is_err() {
145                return Err(anyhow!("missing node binary file"));
146            }
147
148            if smol::fs::metadata(&npm_file).await.is_err() {
149                return Err(anyhow!("missing npm file"));
150            }
151
152            let mut command = Command::new(node_binary);
153            command.env_clear();
154            command.env("PATH", env_path);
155            command.arg(npm_file).arg(subcommand);
156            command.args(["--cache".into(), installation_path.join("cache")]);
157            command.args([
158                "--userconfig".into(),
159                installation_path.join("blank_user_npmrc"),
160            ]);
161            command.args([
162                "--globalconfig".into(),
163                installation_path.join("blank_global_npmrc"),
164            ]);
165            command.args(args);
166
167            if let Some(directory) = directory {
168                command.current_dir(directory);
169                command.args(["--prefix".into(), directory.to_path_buf()]);
170            }
171
172            command.output().await.map_err(|e| anyhow!("{e}"))
173        };
174
175        let mut output = attempt().await;
176        if output.is_err() {
177            output = attempt().await;
178            if output.is_err() {
179                return Err(anyhow!(
180                    "failed to launch npm subcommand {subcommand} subcommand"
181                ));
182            }
183        }
184
185        if let Ok(output) = &output {
186            if !output.status.success() {
187                return Err(anyhow!(
188                    "failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
189                    String::from_utf8_lossy(&output.stdout),
190                    String::from_utf8_lossy(&output.stderr)
191                ));
192            }
193        }
194
195        output.map_err(|e| anyhow!("{e}"))
196    }
197
198    async fn npm_package_latest_version(&self, name: &str) -> Result<String> {
199        let output = self
200            .run_npm_subcommand(
201                None,
202                "info",
203                &[
204                    name,
205                    "--json",
206                    "--fetch-retry-mintimeout",
207                    "2000",
208                    "--fetch-retry-maxtimeout",
209                    "5000",
210                    "--fetch-timeout",
211                    "5000",
212                ],
213            )
214            .await?;
215
216        let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
217        info.dist_tags
218            .latest
219            .or_else(|| info.versions.pop())
220            .ok_or_else(|| anyhow!("no version found for npm package {}", name))
221    }
222
223    async fn npm_install_packages(
224        &self,
225        directory: &Path,
226        packages: &[(&str, &str)],
227    ) -> Result<()> {
228        let packages: Vec<_> = packages
229            .into_iter()
230            .map(|(name, version)| format!("{name}@{version}"))
231            .collect();
232
233        let mut arguments: Vec<_> = packages.iter().map(|p| p.as_str()).collect();
234        arguments.extend_from_slice(&[
235            "--fetch-retry-mintimeout",
236            "2000",
237            "--fetch-retry-maxtimeout",
238            "5000",
239            "--fetch-timeout",
240            "5000",
241        ]);
242
243        self.run_npm_subcommand(Some(directory), "install", &arguments)
244            .await?;
245        Ok(())
246    }
247}
248
249pub struct FakeNodeRuntime;
250
251impl FakeNodeRuntime {
252    pub fn new() -> Arc<dyn NodeRuntime> {
253        Arc::new(Self)
254    }
255}
256
257#[async_trait::async_trait]
258impl NodeRuntime for FakeNodeRuntime {
259    async fn binary_path(&self) -> anyhow::Result<PathBuf> {
260        unreachable!()
261    }
262
263    async fn run_npm_subcommand(
264        &self,
265        _: Option<&Path>,
266        subcommand: &str,
267        args: &[&str],
268    ) -> anyhow::Result<Output> {
269        unreachable!("Should not run npm subcommand '{subcommand}' with args {args:?}")
270    }
271
272    async fn npm_package_latest_version(&self, name: &str) -> anyhow::Result<String> {
273        unreachable!("Should not query npm package '{name}' for latest version")
274    }
275
276    async fn npm_install_packages(
277        &self,
278        _: &Path,
279        packages: &[(&str, &str)],
280    ) -> anyhow::Result<()> {
281        unreachable!("Should not install packages {packages:?}")
282    }
283}