-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathnode_runtime.rs
679 lines (593 loc) · 21.1 KB
/
node_runtime.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
mod archive;
use anyhow::{anyhow, bail, Context, Result};
pub use archive::extract_zip;
use async_compression::futures::bufread::GzipDecoder;
use async_tar::Archive;
use futures::AsyncReadExt;
use http_client::{HttpClient, Uri};
use semver::Version;
use serde::Deserialize;
use smol::io::BufReader;
use smol::{fs, lock::Mutex, process::Command};
use std::ffi::OsString;
use std::io;
use std::process::{Output, Stdio};
use std::{
env::consts,
path::{Path, PathBuf},
sync::Arc,
};
use util::ResultExt;
#[cfg(windows)]
use smol::process::windows::CommandExt;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct NodeBinaryOptions {
pub allow_path_lookup: bool,
pub allow_binary_download: bool,
pub use_paths: Option<(PathBuf, PathBuf)>,
}
#[derive(Clone)]
pub struct NodeRuntime(Arc<Mutex<NodeRuntimeState>>);
struct NodeRuntimeState {
http: Arc<dyn HttpClient>,
instance: Option<Box<dyn NodeRuntimeTrait>>,
last_options: Option<NodeBinaryOptions>,
options: async_watch::Receiver<Option<NodeBinaryOptions>>,
}
impl NodeRuntime {
pub fn new(
http: Arc<dyn HttpClient>,
options: async_watch::Receiver<Option<NodeBinaryOptions>>,
) -> Self {
NodeRuntime(Arc::new(Mutex::new(NodeRuntimeState {
http,
instance: None,
last_options: None,
options,
})))
}
pub fn unavailable() -> Self {
NodeRuntime(Arc::new(Mutex::new(NodeRuntimeState {
http: Arc::new(http_client::BlockedHttpClient),
instance: None,
last_options: None,
options: async_watch::channel(Some(NodeBinaryOptions::default())).1,
})))
}
async fn instance(&self) -> Result<Box<dyn NodeRuntimeTrait>> {
let mut state = self.0.lock().await;
while state.options.borrow().is_none() {
state.options.changed().await?;
}
let options = state.options.borrow().clone().unwrap();
if state.last_options.as_ref() != Some(&options) {
state.instance.take();
}
if let Some(instance) = state.instance.as_ref() {
return Ok(instance.boxed_clone());
}
if let Some((node, npm)) = options.use_paths.as_ref() {
let instance = SystemNodeRuntime::new(node.clone(), npm.clone()).await?;
state.instance = Some(instance.boxed_clone());
return Ok(instance);
}
if options.allow_path_lookup {
if let Some(instance) = SystemNodeRuntime::detect().await {
state.instance = Some(instance.boxed_clone());
return Ok(instance);
}
}
let instance = if options.allow_binary_download {
ManagedNodeRuntime::install_if_needed(&state.http).await?
} else {
Box::new(UnavailableNodeRuntime)
};
state.instance = Some(instance.boxed_clone());
return Ok(instance);
}
pub async fn binary_path(&self) -> Result<PathBuf> {
self.instance().await?.binary_path()
}
pub async fn run_npm_subcommand(
&self,
directory: &Path,
subcommand: &str,
args: &[&str],
) -> Result<Output> {
let http = self.0.lock().await.http.clone();
self.instance()
.await?
.run_npm_subcommand(Some(directory), http.proxy(), subcommand, args)
.await
}
pub async fn npm_package_installed_version(
&self,
local_package_directory: &Path,
name: &str,
) -> Result<Option<String>> {
self.instance()
.await?
.npm_package_installed_version(local_package_directory, name)
.await
}
pub async fn npm_package_latest_version(&self, name: &str) -> Result<String> {
let http = self.0.lock().await.http.clone();
let output = self
.instance()
.await?
.run_npm_subcommand(
None,
http.proxy(),
"info",
&[
name,
"--json",
"--fetch-retry-mintimeout",
"2000",
"--fetch-retry-maxtimeout",
"5000",
"--fetch-timeout",
"5000",
],
)
.await?;
let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
info.dist_tags
.latest
.or_else(|| info.versions.pop())
.ok_or_else(|| anyhow!("no version found for npm package {}", name))
}
pub async fn npm_install_packages(
&self,
directory: &Path,
packages: &[(&str, &str)],
) -> Result<()> {
if packages.is_empty() {
return Ok(());
}
let packages: Vec<_> = packages
.iter()
.map(|(name, version)| format!("{name}@{version}"))
.collect();
let mut arguments: Vec<_> = packages.iter().map(|p| p.as_str()).collect();
arguments.extend_from_slice(&[
"--save-exact",
"--fetch-retry-mintimeout",
"2000",
"--fetch-retry-maxtimeout",
"5000",
"--fetch-timeout",
"5000",
]);
// This is also wrong because the directory is wrong.
self.run_npm_subcommand(directory, "install", &arguments)
.await?;
Ok(())
}
pub async fn should_install_npm_package(
&self,
package_name: &str,
local_executable_path: &Path,
local_package_directory: &Path,
latest_version: &str,
) -> bool {
// In the case of the local system not having the package installed,
// or in the instances where we fail to parse package.json data,
// we attempt to install the package.
if fs::metadata(local_executable_path).await.is_err() {
return true;
}
let Some(installed_version) = self
.npm_package_installed_version(local_package_directory, package_name)
.await
.log_err()
.flatten()
else {
return true;
};
let Some(installed_version) = Version::parse(&installed_version).log_err() else {
return true;
};
let Some(latest_version) = Version::parse(latest_version).log_err() else {
return true;
};
installed_version < latest_version
}
}
enum ArchiveType {
TarGz,
Zip,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct NpmInfo {
#[serde(default)]
dist_tags: NpmInfoDistTags,
versions: Vec<String>,
}
#[derive(Debug, Deserialize, Default)]
pub struct NpmInfoDistTags {
latest: Option<String>,
}
#[async_trait::async_trait]
trait NodeRuntimeTrait: Send + Sync {
fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait>;
fn binary_path(&self) -> Result<PathBuf>;
async fn run_npm_subcommand(
&self,
directory: Option<&Path>,
proxy: Option<&Uri>,
subcommand: &str,
args: &[&str],
) -> Result<Output>;
async fn npm_package_installed_version(
&self,
local_package_directory: &Path,
name: &str,
) -> Result<Option<String>>;
}
#[derive(Clone)]
struct ManagedNodeRuntime {
installation_path: PathBuf,
}
impl ManagedNodeRuntime {
const VERSION: &str = "v22.5.1";
#[cfg(not(windows))]
const NODE_PATH: &str = "bin/node";
#[cfg(windows)]
const NODE_PATH: &str = "node.exe";
#[cfg(not(windows))]
const NPM_PATH: &str = "bin/npm";
#[cfg(windows)]
const NPM_PATH: &str = "node_modules/npm/bin/npm-cli.js";
async fn node_environment_path(&self) -> Result<OsString> {
let node_binary = self.installation_path.join(Self::NODE_PATH);
let mut env_path = vec![node_binary
.parent()
.expect("invalid node binary path")
.to_path_buf()];
if let Some(existing_path) = std::env::var_os("PATH") {
let mut paths = std::env::split_paths(&existing_path).collect::<Vec<_>>();
env_path.append(&mut paths);
}
std::env::join_paths(env_path).context("failed to create PATH env variable")
}
async fn install_if_needed(http: &Arc<dyn HttpClient>) -> Result<Box<dyn NodeRuntimeTrait>> {
log::info!("Node runtime install_if_needed");
let os = match consts::OS {
"macos" => "darwin",
"linux" => "linux",
"windows" => "win",
other => bail!("Running on unsupported os: {other}"),
};
let arch = match consts::ARCH {
"x86_64" => "x64",
"aarch64" => "arm64",
other => bail!("Running on unsupported architecture: {other}"),
};
let version = Self::VERSION;
let folder_name = format!("node-{version}-{os}-{arch}");
let node_containing_dir = paths::support_dir().join("node");
let node_dir = node_containing_dir.join(folder_name);
let node_binary = node_dir.join(Self::NODE_PATH);
let npm_file = node_dir.join(Self::NPM_PATH);
let mut command = Command::new(&node_binary);
command
.env_clear()
.arg(npm_file)
.arg("--version")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.args(["--cache".into(), node_dir.join("cache")])
.args(["--userconfig".into(), node_dir.join("blank_user_npmrc")])
.args(["--globalconfig".into(), node_dir.join("blank_global_npmrc")]);
#[cfg(windows)]
command.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
let result = command.status().await;
let valid = matches!(result, Ok(status) if status.success());
if !valid {
_ = fs::remove_dir_all(&node_containing_dir).await;
fs::create_dir(&node_containing_dir)
.await
.context("error creating node containing dir")?;
let archive_type = match consts::OS {
"macos" | "linux" => ArchiveType::TarGz,
"windows" => ArchiveType::Zip,
other => bail!("Running on unsupported os: {other}"),
};
let version = Self::VERSION;
let file_name = format!(
"node-{version}-{os}-{arch}.{extension}",
extension = match archive_type {
ArchiveType::TarGz => "tar.gz",
ArchiveType::Zip => "zip",
}
);
let url = format!("https://nodejs.org/dist/{version}/{file_name}");
let mut response = http
.get(&url, Default::default(), true)
.await
.context("error downloading Node binary tarball")?;
let body = response.body_mut();
match archive_type {
ArchiveType::TarGz => {
let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
let archive = Archive::new(decompressed_bytes);
archive.unpack(&node_containing_dir).await?;
}
ArchiveType::Zip => archive::extract_zip(&node_containing_dir, body).await?,
}
}
// Note: Not in the `if !valid {}` so we can populate these for existing installations
_ = fs::create_dir(node_dir.join("cache")).await;
_ = fs::write(node_dir.join("blank_user_npmrc"), []).await;
_ = fs::write(node_dir.join("blank_global_npmrc"), []).await;
anyhow::Ok(Box::new(ManagedNodeRuntime {
installation_path: node_dir,
}))
}
}
#[async_trait::async_trait]
impl NodeRuntimeTrait for ManagedNodeRuntime {
fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
Box::new(self.clone())
}
fn binary_path(&self) -> Result<PathBuf> {
Ok(self.installation_path.join(Self::NODE_PATH))
}
async fn run_npm_subcommand(
&self,
directory: Option<&Path>,
proxy: Option<&Uri>,
subcommand: &str,
args: &[&str],
) -> Result<Output> {
let attempt = || async move {
let node_binary = self.installation_path.join(Self::NODE_PATH);
let npm_file = self.installation_path.join(Self::NPM_PATH);
let env_path = self.node_environment_path().await?;
if smol::fs::metadata(&node_binary).await.is_err() {
return Err(anyhow!("missing node binary file"));
}
if smol::fs::metadata(&npm_file).await.is_err() {
return Err(anyhow!("missing npm file"));
}
let mut command = Command::new(node_binary);
command.env_clear();
command.env("PATH", env_path);
command.arg(npm_file).arg(subcommand);
command.args(["--cache".into(), self.installation_path.join("cache")]);
command.args([
"--userconfig".into(),
self.installation_path.join("blank_user_npmrc"),
]);
command.args([
"--globalconfig".into(),
self.installation_path.join("blank_global_npmrc"),
]);
command.args(args);
configure_npm_command(&mut command, directory, proxy);
command.output().await.map_err(|e| anyhow!("{e}"))
};
let mut output = attempt().await;
if output.is_err() {
output = attempt().await;
if output.is_err() {
return Err(anyhow!(
"failed to launch npm subcommand {subcommand} subcommand\nerr: {:?}",
output.err()
));
}
}
if let Ok(output) = &output {
if !output.status.success() {
return Err(anyhow!(
"failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
}
output.map_err(|e| anyhow!("{e}"))
}
async fn npm_package_installed_version(
&self,
local_package_directory: &Path,
name: &str,
) -> Result<Option<String>> {
read_package_installed_version(local_package_directory.join("node_modules"), name).await
}
}
#[derive(Clone)]
pub struct SystemNodeRuntime {
node: PathBuf,
npm: PathBuf,
global_node_modules: PathBuf,
scratch_dir: PathBuf,
}
impl SystemNodeRuntime {
const MIN_VERSION: semver::Version = Version::new(18, 0, 0);
async fn new(node: PathBuf, npm: PathBuf) -> Result<Box<dyn NodeRuntimeTrait>> {
let output = Command::new(&node)
.arg("--version")
.output()
.await
.with_context(|| format!("running node from {:?}", node))?;
if !output.status.success() {
anyhow::bail!(
"failed to run node --version. stdout: {}, stderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
let version_str = String::from_utf8_lossy(&output.stdout);
let version = semver::Version::parse(version_str.trim().trim_start_matches('v'))?;
if version < Self::MIN_VERSION {
anyhow::bail!(
"node at {} is too old. want: {}, got: {}",
node.to_string_lossy(),
Self::MIN_VERSION,
version
)
}
let scratch_dir = paths::support_dir().join("node");
fs::create_dir(&scratch_dir).await.ok();
fs::create_dir(scratch_dir.join("cache")).await.ok();
fs::write(scratch_dir.join("blank_user_npmrc"), [])
.await
.ok();
fs::write(scratch_dir.join("blank_global_npmrc"), [])
.await
.ok();
let mut this = Self {
node,
npm,
global_node_modules: PathBuf::default(),
scratch_dir,
};
let output = this.run_npm_subcommand(None, None, "root", &["-g"]).await?;
this.global_node_modules =
PathBuf::from(String::from_utf8_lossy(&output.stdout).to_string());
Ok(Box::new(this))
}
async fn detect() -> Option<Box<dyn NodeRuntimeTrait>> {
let node = which::which("node").ok()?;
let npm = which::which("npm").ok()?;
Self::new(node, npm).await.log_err()
}
}
#[async_trait::async_trait]
impl NodeRuntimeTrait for SystemNodeRuntime {
fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
Box::new(self.clone())
}
fn binary_path(&self) -> Result<PathBuf> {
Ok(self.node.clone())
}
async fn run_npm_subcommand(
&self,
directory: Option<&Path>,
proxy: Option<&Uri>,
subcommand: &str,
args: &[&str],
) -> anyhow::Result<Output> {
let mut command = Command::new(self.npm.clone());
command
.env_clear()
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
.arg(subcommand)
.args(["--cache".into(), self.scratch_dir.join("cache")])
.args([
"--userconfig".into(),
self.scratch_dir.join("blank_user_npmrc"),
])
.args([
"--globalconfig".into(),
self.scratch_dir.join("blank_global_npmrc"),
])
.args(args);
configure_npm_command(&mut command, directory, proxy);
let output = command.output().await?;
if !output.status.success() {
return Err(anyhow!(
"failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
Ok(output)
}
async fn npm_package_installed_version(
&self,
local_package_directory: &Path,
name: &str,
) -> Result<Option<String>> {
read_package_installed_version(local_package_directory.join("node_modules"), name).await
// todo: allow returning a globally installed version (requires callers not to hard-code the path)
}
}
pub async fn read_package_installed_version(
node_module_directory: PathBuf,
name: &str,
) -> Result<Option<String>> {
let package_json_path = node_module_directory.join(name).join("package.json");
let mut file = match fs::File::open(package_json_path).await {
Ok(file) => file,
Err(err) => {
if err.kind() == io::ErrorKind::NotFound {
return Ok(None);
}
Err(err)?
}
};
#[derive(Deserialize)]
struct PackageJson {
version: String,
}
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
let package_json: PackageJson = serde_json::from_str(&contents)?;
Ok(Some(package_json.version))
}
pub struct UnavailableNodeRuntime;
#[async_trait::async_trait]
impl NodeRuntimeTrait for UnavailableNodeRuntime {
fn boxed_clone(&self) -> Box<dyn NodeRuntimeTrait> {
Box::new(UnavailableNodeRuntime)
}
fn binary_path(&self) -> Result<PathBuf> {
bail!("binary_path: no node runtime available")
}
async fn run_npm_subcommand(
&self,
_: Option<&Path>,
_: Option<&Uri>,
_: &str,
_: &[&str],
) -> anyhow::Result<Output> {
bail!("run_npm_subcommand: no node runtime available")
}
async fn npm_package_installed_version(
&self,
_local_package_directory: &Path,
_: &str,
) -> Result<Option<String>> {
bail!("npm_package_installed_version: no node runtime available")
}
}
fn configure_npm_command(command: &mut Command, directory: Option<&Path>, proxy: Option<&Uri>) {
if let Some(directory) = directory {
command.current_dir(directory);
command.args(["--prefix".into(), directory.to_path_buf()]);
}
if let Some(proxy) = proxy {
// Map proxy settings from `http://localhost:10809` to `http://127.0.0.1:10809`
// NodeRuntime without environment information can not parse `localhost`
// correctly.
// TODO: map to `[::1]` if we are using ipv6
let proxy = proxy
.to_string()
.to_ascii_lowercase()
.replace("localhost", "127.0.0.1");
command.args(["--proxy", &proxy]);
}
#[cfg(windows)]
{
// SYSTEMROOT is a critical environment variables for Windows.
if let Some(val) = std::env::var("SYSTEMROOT")
.context("Missing environment variable: SYSTEMROOT!")
.log_err()
{
command.env("SYSTEMROOT", val);
}
// Without ComSpec, the post-install will always fail.
if let Some(val) = std::env::var("ComSpec")
.context("Missing environment variable: ComSpec!")
.log_err()
{
command.env("ComSpec", val);
}
command.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
}
}