mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 16:04:21 +00:00
Merge pull request #4376 from dengliu/fix/npm-public-registry-fallback
fix(tools): retry npm installs against registry.npmjs.org on mirror misses
This commit is contained in:
@@ -656,6 +656,20 @@ fn install_npm(
|
||||
platform: Platform,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
}
|
||||
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, version) = split_npm_spec(&p.package);
|
||||
let spec = match version {
|
||||
@@ -663,10 +677,27 @@ fn install_npm(
|
||||
_ => format!("{name}@{}", entry.version),
|
||||
};
|
||||
check_spec(&spec)?;
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.arg("install").arg("--prefix").arg(dir).args(["--no-audit", "--no-fund"]).arg(&spec).current_dir(dir);
|
||||
ide_tools::run_streamed(cmd, cancel, emit)?;
|
||||
let specs = [spec.clone()];
|
||||
ide_tools::run_npm_with_public_fallback(
|
||||
|extra| {
|
||||
if !extra.is_empty() {
|
||||
let _ = fs::remove_dir_all(dir.join("node_modules"));
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.arg("install")
|
||||
.arg("--prefix")
|
||||
.arg(dir)
|
||||
.args(["--no-audit", "--no-fund"])
|
||||
.args(extra)
|
||||
.arg(&spec)
|
||||
.current_dir(dir);
|
||||
cmd
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
let modules = dir.join("node_modules");
|
||||
let manifest: serde_json::Value = fs::read_to_string(modules.join(name).join("package.json"))
|
||||
.ok()
|
||||
@@ -961,6 +992,58 @@ mod tests {
|
||||
assert!(check_url("ftp://x/a").is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
let log = dir.path().join("npm-calls.log");
|
||||
let npm = dir.path().join("npm");
|
||||
fs::write(
|
||||
&npm,
|
||||
format!(
|
||||
r#"#!/bin/sh
|
||||
echo "$@" >> '{}'
|
||||
case " $* " in
|
||||
*" --registry=https://registry.npmjs.org/ --@acme:registry=https://registry.npmjs.org/ "*)
|
||||
prefix=""; while [ $# -gt 0 ]; do [ "$1" = "--prefix" ] && prefix="$2"; shift; done
|
||||
mkdir -p "$prefix/node_modules/.bin" "$prefix/node_modules/@acme/agent-acp"
|
||||
printf '#!/bin/sh\necho 1.2.0\n' > "$prefix/node_modules/.bin/agent-acp"
|
||||
chmod +x "$prefix/node_modules/.bin/agent-acp"
|
||||
printf '{{"bin":"cli.js"}}\n' > "$prefix/node_modules/@acme/agent-acp/package.json"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "npm error code ETARGET" >&2
|
||||
echo "npm error notarget No matching version found for @acme/agent-acp@1.2.0." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
"#,
|
||||
log.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
archive::make_executable(&npm).unwrap();
|
||||
|
||||
let index = r#"{"agents":[
|
||||
{"id":"acme","name":"Acme","version":"1.2.0",
|
||||
"distribution":{"npx":{"package":"@acme/agent-acp@1.2.0","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
assert!(calls[1].contains("--registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksums_are_verified() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
+43
-16
@@ -35,7 +35,10 @@ use parking_lot::Mutex;
|
||||
use platform::{Os, Platform};
|
||||
pub use process::progress_event;
|
||||
use process::run_collect;
|
||||
pub use process::{Emit, Http, run_quiet, run_streamed};
|
||||
pub use process::{
|
||||
Emit, Http, PUBLIC_NPM_REGISTRY, is_npm_registry_miss, npm_public_registry_args, run_npm_with_public_fallback,
|
||||
run_quiet, run_streamed,
|
||||
};
|
||||
pub use registry::{Method, ReleaseSource, TOOLS, ToolKind, ToolSpec};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -1045,15 +1048,28 @@ impl Tools {
|
||||
fn install_npm(&self, packages: &[&str], cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
let (manager, pnpm) = self.npm_manager()?;
|
||||
self.ensure_package_json()?;
|
||||
let mut c = self.command(manager);
|
||||
let specs = packages.iter().map(|p| if npm_name(p) == *p { format!("{p}@latest") } else { p.to_string() });
|
||||
if pnpm {
|
||||
c.arg("add").arg("--dir").arg(&self.root).args(specs);
|
||||
} else {
|
||||
c.args(["install", "--no-fund", "--no-audit", "--loglevel=http", "--prefix"]).arg(&self.root).args(specs);
|
||||
}
|
||||
c.current_dir(&self.root);
|
||||
run_streamed(c, cancel, emit).map(drop)
|
||||
let specs: Vec<String> =
|
||||
packages.iter().map(|p| if npm_name(p) == *p { format!("{p}@latest") } else { (*p).to_string() }).collect();
|
||||
run_npm_with_public_fallback(
|
||||
|extra| {
|
||||
let mut c = self.command(&manager);
|
||||
if pnpm {
|
||||
c.arg("add").arg("--dir").arg(&self.root).args(extra).args(&specs);
|
||||
} else {
|
||||
c.args(["install", "--no-fund", "--no-audit", "--loglevel=http", "--prefix"])
|
||||
.arg(&self.root)
|
||||
.args(extra)
|
||||
.args(&specs);
|
||||
}
|
||||
c.current_dir(&self.root);
|
||||
c
|
||||
},
|
||||
&specs,
|
||||
pnpm,
|
||||
cancel,
|
||||
emit,
|
||||
)
|
||||
.map(drop)
|
||||
}
|
||||
|
||||
fn install_go(&self, spec: &ToolSpec, module: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
@@ -1572,14 +1588,25 @@ impl Tools {
|
||||
Ok(Some(self.resolve_release(&http, source, assets, cancel)?.version))
|
||||
}
|
||||
Method::Npm { packages } => {
|
||||
let (manager, _) = self.npm_manager()?;
|
||||
let mut c = self.command(manager);
|
||||
let (manager, pnpm) = self.npm_manager()?;
|
||||
let view = |extra: &[String]| {
|
||||
let mut c = self.command(&manager);
|
||||
c.args(["view", packages[0], "version"]).args(extra).current_dir(&self.root);
|
||||
run_quiet(c, Duration::from_secs(60))
|
||||
};
|
||||
// The registry the user's npm configuration names (a mirror, a proxy). A cold npm
|
||||
// on a slow registry takes several seconds per package, more when run side by side.
|
||||
c.args(["view", packages[0], "version"]).current_dir(&self.root);
|
||||
match run_quiet(c, Duration::from_secs(60)) {
|
||||
Some((true, out)) => Ok(out.lines().map(str::trim).rfind(|l| !l.is_empty()).map(String::from)),
|
||||
_ => Err(IdeError::unavailable(format!("cannot look up the latest {}", packages[0]))),
|
||||
let out = match view(&[]) {
|
||||
Some((true, out)) => Some(out),
|
||||
Some((false, out)) if is_npm_registry_miss(&out) => {
|
||||
let extra = npm_public_registry_args([packages[0]], pnpm);
|
||||
view(&extra).and_then(|(ok, retry)| ok.then_some(retry))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match out {
|
||||
Some(out) => Ok(out.lines().map(str::trim).rfind(|l| !l.is_empty()).map(String::from)),
|
||||
None => Err(IdeError::unavailable(format!("cannot look up the latest {}", packages[0]))),
|
||||
}
|
||||
}
|
||||
_ => Ok(None),
|
||||
|
||||
@@ -23,25 +23,101 @@ fn describe(cmd: &Command) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
pub const PUBLIC_NPM_REGISTRY: &str = "https://registry.npmjs.org/";
|
||||
|
||||
fn failed_command(label: &str, output: &str, status: &str) -> IdeError {
|
||||
let tail: Vec<&str> = output.lines().rev().filter(|l| !l.trim().is_empty()).take(3).collect();
|
||||
let tail: Vec<&str> = tail.into_iter().rev().collect();
|
||||
IdeError::new(
|
||||
ErrorKind::Io,
|
||||
format!(
|
||||
"`{label}` failed ({status}){}",
|
||||
if tail.is_empty() { String::new() } else { format!(": {}", tail.join(" / ")) }
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// CLI flags forcing `npm` / `pnpm` onto [`PUBLIC_NPM_REGISTRY`], including `@scope:registry`
|
||||
/// overrides that otherwise take precedence over `--registry` in `~/.npmrc` for scoped packages.
|
||||
pub fn npm_public_registry_args<'a>(specs: impl IntoIterator<Item = &'a str>, pnpm: bool) -> Vec<String> {
|
||||
let mut args = vec![format!("--registry={PUBLIC_NPM_REGISTRY}")];
|
||||
if !pnpm {
|
||||
for spec in specs {
|
||||
if let Some((scope, _)) = spec.split_once('/').filter(|(s, _)| s.starts_with('@') && s.len() > 1) {
|
||||
let flag = format!("--{scope}:registry={PUBLIC_NPM_REGISTRY}");
|
||||
if !args.contains(&flag) {
|
||||
args.push(flag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// Whether `npm` / `pnpm` output indicates a mirror miss or private-registry auth rejection
|
||||
/// (`ETARGET`, `E404`, `E401`, `ENEEDAUTH`, `E403`).
|
||||
pub fn is_npm_registry_miss(output: &str) -> bool {
|
||||
const CODES: &[&str] = &[
|
||||
"ETARGET",
|
||||
"notarget",
|
||||
"No matching version found",
|
||||
"ERR_PNPM_NO_MATCHING_VERSION",
|
||||
"E404",
|
||||
"404 Not Found",
|
||||
"ERR_PNPM_FETCH_404",
|
||||
"E401",
|
||||
"ENEEDAUTH",
|
||||
"ERR_PNPM_FETCH_401",
|
||||
"E403",
|
||||
"ERR_PNPM_FETCH_403",
|
||||
];
|
||||
CODES.iter().any(|code| output.contains(code))
|
||||
}
|
||||
|
||||
/// Runs `cmd`, forwarding each stdout/stderr line as [`InstallEvent::Line`].
|
||||
/// Returns the collected output; fails on non-zero exit or cancellation.
|
||||
pub fn run_streamed(cmd: Command, cancel: &CancellationToken, emit: Emit) -> IdeResult<String> {
|
||||
let label = describe(&cmd);
|
||||
let (ok, output, status) = run_collect(cmd, cancel, emit)?;
|
||||
if !ok {
|
||||
let tail: Vec<&str> = output.lines().rev().filter(|l| !l.trim().is_empty()).take(3).collect();
|
||||
let tail: Vec<&str> = tail.into_iter().rev().collect();
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Io,
|
||||
format!(
|
||||
"`{label}` failed ({status}){}",
|
||||
if tail.is_empty() { String::new() } else { format!(": {}", tail.join(" / ")) }
|
||||
),
|
||||
));
|
||||
return Err(failed_command(&label, &output, &status));
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Runs an `npm` / `pnpm` command against the user's configured registry first (preserving
|
||||
/// corporate mirrors, proxies, and CAs), and retries once against [`PUBLIC_NPM_REGISTRY`] when
|
||||
/// the configured registry misses the package/version or rejects auth. Preserves the primary
|
||||
/// error if the public registry is unreachable.
|
||||
pub fn run_npm_with_public_fallback(
|
||||
mut build: impl FnMut(&[String]) -> Command,
|
||||
specs: &[String],
|
||||
pnpm: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<String> {
|
||||
let primary = build(&[]);
|
||||
let label = describe(&primary);
|
||||
let (ok, output, status) = run_collect(primary, cancel, emit)?;
|
||||
if ok {
|
||||
return Ok(output);
|
||||
}
|
||||
let err = failed_command(&label, &output, &status);
|
||||
if cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
return Err(err);
|
||||
}
|
||||
emit(InstallEvent::Line {
|
||||
text: format!("Configured npm registry missed package; retrying against {PUBLIC_NPM_REGISTRY}…"),
|
||||
});
|
||||
let extra = npm_public_registry_args(specs.iter().map(String::as_str), pnpm);
|
||||
match run_collect(build(&extra), cancel, emit) {
|
||||
Ok((true, retry_out, _)) => Ok(retry_out),
|
||||
Ok((false, _, _)) => Err(err),
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
Err(_) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`run_streamed`] but returns `(success, output, status text)` instead of failing on a non-zero exit.
|
||||
pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) -> IdeResult<(bool, String, String)> {
|
||||
emit(InstallEvent::Line { text: format!("$ {}", describe(&cmd)) });
|
||||
|
||||
@@ -545,6 +545,64 @@ echo "added 1 package""#,
|
||||
assert!(env.root.join("package.json").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_install_retries_against_public_registry_on_mirror_miss_and_preserves_primary_error_when_unreachable() {
|
||||
let env = Env::new();
|
||||
let log = env.root.parent().unwrap().join("npm-fallback.txt");
|
||||
env.script(&env.sys, "node", "exit 0");
|
||||
env.script(
|
||||
&env.sys,
|
||||
"npm",
|
||||
&format!(
|
||||
r#"echo "$@" >> '{log}'
|
||||
case " $* " in
|
||||
*" --registry=https://registry.npmjs.org/ --@vtsls:registry=https://registry.npmjs.org/ "*)
|
||||
prefix=""; while [ $# -gt 0 ]; do [ "$1" = "--prefix" ] && prefix="$2"; shift; done
|
||||
/bin/mkdir -p "$prefix/node_modules/.bin" "$prefix/node_modules/@vtsls/language-server"
|
||||
printf '#!/bin/sh\necho 0.2.9\n' > "$prefix/node_modules/.bin/vtsls"
|
||||
/bin/chmod +x "$prefix/node_modules/.bin/vtsls"
|
||||
echo '{{"version":"0.2.9"}}' > "$prefix/node_modules/@vtsls/language-server/package.json"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "npm error code ETARGET" >&2
|
||||
echo "npm error notarget No matching version found for @vtsls/language-server@latest." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac"#,
|
||||
log = log.display()
|
||||
),
|
||||
);
|
||||
let info = env.tools().install("vtsls", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
assert!(calls[1].contains("--registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert!(calls[1].contains("--@vtsls:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
|
||||
// When public npmjs.org is blocked (e.g. corporate firewall), surface the primary mirror error.
|
||||
env.script(
|
||||
&env.sys,
|
||||
"npm",
|
||||
r#"case " $* " in
|
||||
*" --registry=https://registry.npmjs.org/ "*)
|
||||
echo "npm error code ECONNRESET" >&2
|
||||
exit 1
|
||||
;;
|
||||
*)
|
||||
echo "npm error code ETARGET" >&2
|
||||
echo "npm error notarget No matching version found for pyright@latest." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac"#,
|
||||
);
|
||||
let err = env.tools().install("pyright", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert!(err.message.contains("No matching version found for pyright@latest"), "{}", err.message);
|
||||
assert!(!err.message.contains("ECONNRESET"), "{}", err.message);
|
||||
}
|
||||
|
||||
/// Servers that load TypeScript as a library get one with its JS API: `@latest`
|
||||
/// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25).
|
||||
/// Uninstalling one keeps the TypeScript another installed server still uses.
|
||||
|
||||
Reference in New Issue
Block a user