Compare commits

..
Author SHA1 Message Date
l0ng-ai 493bde17a9 feat(agents): open a task's changes in an editor tab
The changed-files chip under the composer opens the task's changes in an
editor tab of their own: the file tree beside one scrolling diff of every
file, with the scope, accept and rollback controls in the diff's toolbar.
The conversation keeps its layout instead of gaining a side pane.

Added and deleted files show their one side alone, and selecting a file
no longer renders every mounted diff again.
2026-11-25 08:50:53 +08:00
777 changed files with 3488 additions and 40083 deletions

No files matched your search

-16
View File
@@ -147,22 +147,6 @@
"prefer-rest-params": "error",
"prefer-spread": "error"
}
},
{
"files": [
"evals/**/*.ts",
"perf/**/*.ts",
"smoke/**/*.ts",
"src/features/vcs/**/*.ts",
"src/features/vcs/**/*.tsx",
"src/features/run/**/*.ts",
"src/features/run/**/*.tsx",
"src/features/database/**/*.ts",
"src/features/database/**/*.tsx"
],
"rules": {
"no-await-in-loop": "error"
}
}
]
}
Generated
-4
View File
@@ -4320,7 +4320,6 @@ dependencies = [
"ide-http",
"ide-sdk",
"ide-ssh",
"libc",
"notify",
"open",
"oracledb",
@@ -4340,7 +4339,6 @@ dependencies = [
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeroize",
"zip",
]
@@ -4517,7 +4515,6 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
"url",
"uuid",
"windows-sys 0.61.2",
"zip",
@@ -6762,7 +6759,6 @@ dependencies = [
"webview2-com",
"windows",
"windows-sys 0.61.2",
"wry",
]
[[package]]
+4 -4
View File
@@ -15,12 +15,12 @@ pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, module_classpaths,
single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
structure_war_plan, structure_web_artifacts,
};
pub use up_to_date::{menu_up_to_date, record_menu_build};
+7 -35
View File
@@ -200,22 +200,19 @@ fn kotlin_line(line: &str) -> Option<RawMessage> {
kotlin_location(rest, severity)
}
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`
/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`).
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`.
fn javac_header(line: &str) -> Option<RawMessage> {
let (path, ln, col, rest) = path_line_col(line)?;
if !looks_like_source_path(path) {
return None;
}
let rest = rest.trim_start_matches(':').trim_start();
let (severity, msg) = ["error:", "错误:", "錯誤:", "エラー:"]
.into_iter()
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Error, m)))
.or_else(|| {
["warning:", "警告:"]
.into_iter()
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Warning, m)))
})?;
let (severity, msg) = if let Some(m) = rest.strip_prefix("error:") {
(Severity::Error, m)
} else {
let m = rest.strip_prefix("warning:")?;
(Severity::Warning, m)
};
Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col))
}
@@ -558,31 +555,6 @@ mod tests {
assert_eq!(out[1].text, "[removal] finalize() has been deprecated");
}
#[test]
fn localized_javac_errors_and_warnings() {
let out = parse(
Format::Gradle,
"/p/src/A.java:12: 错误: 找不到符号\n\
\x20 Foo foo = new Foo();\n\
\x20 ^\n\
\x20 符号: 类 Foo\n\
\x20 位置: 类 A\n\
/p/src/B.java:5: 錯誤: 需要 ';'\n\
\x20 int x = 1\n\
\x20 ^\n\
/p/src/C.java:8: 警告: [deprecation] old() 已过时\n\
\x20 old();\n\
\x20 ^\n",
);
assert_eq!(out.len(), 3, "{out:?}");
assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9)));
assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A");
assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14)));
assert_eq!(out[1].text, "需要 ';'");
assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5)));
assert_eq!(out[2].text, "[deprecation] old() 已过时");
}
#[test]
fn gradle_kotlin() {
let out = parse(
+59 -353
View File
@@ -1,4 +1,4 @@
//! Single-file Java compilation with `javac` for the Recompile action (#2476).
//! Single-file Java compilation with `javac` for the Compile File action (#2476).
//!
//! A module build (`-pl … -am`) still walks every upstream module, and packaging
//! walks the whole reactor; compiling one file only needs that file's module
@@ -6,93 +6,12 @@
use super::*;
use serde::{Deserialize, Serialize};
use std::fs;
use std::process::Command as ProcCommand;
/// Output file of the `dependency:build-classpath` probe, relative to each module.
const CP_FILE: &str = "target/ide-compile-cp.txt";
// Older records include undeclared reactor test outputs even in runtime classpaths.
const CLASSPATH_CACHE_VERSION: u32 = 1;
const GRADLE_COMPILE_CP_INIT_SCRIPT: &str = include_str!("../gradle-compile-cp.init.gradle");
pub(super) fn is_java_file(file: &Path) -> IdeResult<String> {
if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
Ok(file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())
}
pub(super) fn is_test_source(rel: &str) -> bool {
let parts: Vec<&str> = rel.split(['/', '\\']).collect();
parts.windows(2).any(|w| w == ["src", "test"])
}
pub(super) fn java_home_major(env: &BTreeMap<String, String>) -> Option<u32> {
let home = env.get("JAVA_HOME").filter(|h| !h.trim().is_empty())?;
let release = fs::read_to_string(Path::new(home).join("release")).ok()?;
let value = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
let value = value.trim().trim_matches(['"', '\'']);
language_release(value)
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
pub(super) fn release_args(level: Option<u32>, jdk_major: Option<u32>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk_major.is_none_or(|m| m >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
pub(super) fn join_classpath(entries: impl IntoIterator<Item = String>) -> String {
let separator = if cfg!(windows) { ";" } else { ":" };
let mut seen = HashSet::new();
let mut out = Vec::new();
for entry in entries {
if !entry.is_empty() && seen.insert(entry.clone()) {
out.push(entry);
}
}
out.join(separator)
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_javac_step(
javac: &str,
cwd: &Path,
out_dir: &Path,
classpath: &str,
sources: &[PathBuf],
release: Vec<String>,
file: &Path,
env: BTreeMap<String, String>,
) -> IdeResult<BuildStep> {
fs::create_dir_all(out_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
if !classpath.is_empty() {
step.args.extend(["-cp".into(), classpath.to_owned()]);
}
// Classes of the module that were never built (or are older than their source) are read
// from its sources; only `file` is written, so a test compile never puts main classes
// into test-classes.
if !sources.is_empty() {
let separator = if cfg!(windows) { ";" } else { ":" };
step.args.push("-sourcepath".into());
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
step.args.push("-implicit:none".into());
}
step.args.extend(release);
step.args.push(file.to_string_lossy().into_owned());
step.env = env;
step.mkdirs = vec![out_dir.to_path_buf()];
Ok(step)
}
/// The resolved dependency classpath for one module and scope, tied to the same
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
@@ -122,7 +41,12 @@ pub struct SingleFileTarget {
/// Locates the linked Maven module owning a `.java` source file.
pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<SingleFileTarget> {
is_java_file(file)?;
if file.extension().is_none_or(|ext| ext != "java") {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
let Some(m) = &model.maven else {
return Err(IdeError::not_found("no linked Maven project found for module"));
};
@@ -146,7 +70,8 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
let top_dir = subdir(root, &top.dir);
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
// Test sources see the test classpath and compile into test classes.
let test = is_test_source(&rel);
let parts: Vec<&str> = rel.split('/').collect();
let test = parts.windows(2).any(|w| w == ["src", "test"]);
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
}
@@ -187,17 +112,7 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
pub fn single_file_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
single_file_classpath_cancellable(root, model, target, &CancellationToken::new())
}
fn single_file_classpath_cancellable(
root: &Path,
model: &BuildModel,
target: &SingleFileTarget,
cancel: &CancellationToken,
) -> IdeResult<String> {
let scope = if target.test { "test" } else { "compile" };
classpath(root, model, target, scope, false, cancel)
classpath(root, model, target, "test", false)
}
/// Runtime (or test) dependency classpath for a launch module.
@@ -257,12 +172,10 @@ pub fn module_classpaths(
}
let scope = if test { "test" } else { "runtime" };
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
let classpaths = match classpaths(root, model, &targets, scope, true, cancel) {
let classpaths = match classpaths(root, model, &targets, scope, true) {
Ok(classpaths) => classpaths,
// Another module's failure must not cost this launch its own probe.
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => {
classpaths(root, model, &targets[..1], scope, true, cancel)?
}
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => classpaths(root, model, &targets[..1], scope, true)?,
Err(e) => return Err(e),
};
if cancel.is_cancelled() {
@@ -323,9 +236,8 @@ fn classpath(
target: &SingleFileTarget,
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
Ok(classpaths(root, model, &[target], scope, compile_first)?.pop().unwrap())
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -335,7 +247,6 @@ fn classpaths(
targets: &[&SingleFileTarget],
scope: &str,
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<Vec<String>> {
let top = &targets[0].top;
let probe = CP_FILE;
@@ -363,17 +274,16 @@ fn classpaths(
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
if e.kind == ide_core::error::ErrorKind::Cancelled {
e
} else {
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
}
})?;
if !out.success {
let mut command = ProcCommand::new(&top.command);
command.args(&args).envs(&top.env).current_dir(&top_dir);
let status = ide_core::process::prepare(&mut command)
.output()
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
if !status.status.success() {
let stdout = String::from_utf8_lossy(&status.stdout);
let stderr = String::from_utf8_lossy(&status.stderr);
// Maven reports reactor/dependency failures on stdout, not only stderr.
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
@@ -415,14 +325,39 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
})?;
let separator = if cfg!(windows) { ';' } else { ':' };
entries.extend(content.split([separator, '\n', '\r']).map(str::trim).filter(|e| !e.is_empty()).map(str::to_owned));
Ok(join_classpath(entries))
entries.dedup();
Ok(entries.join(&separator.to_string()))
}
/// The `javac` step compiling `file` into `target`'s output directory.
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
fs::create_dir_all(&target.out_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", target.out_dir.display())))?;
let mut step = BuildStep::new(javac, &[], &target.module, Format::Gradle);
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
step.args.push("-encoding".into());
step.args.push("UTF-8".into());
step.args.push("-d".into());
step.args.push(target.out_dir.to_string_lossy().into_owned());
step.args.push("-cp".into());
step.args.push(classpath.to_owned());
// Classes of the module that were never built (or are older than their source) are read
// from its sources; only `file` is written, so a test compile never puts main classes
// into test-classes.
let sources = source_roots(target);
let release = release_args(target.java_version, java_home_major(&target.top.env));
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
if !sources.is_empty() {
let separator = if cfg!(windows) { ";" } else { ":" };
step.args.push("-sourcepath".into());
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
step.args.push("-implicit:none".into());
}
if let Some(version) = target.java_version {
step.args.push("--release".into());
step.args.push(version.to_string());
}
step.args.push(file.to_string_lossy().into_owned());
step.env = target.top.env.clone();
Ok(step)
}
/// The module's Java source folders that exist, generated ones included; test sources see
@@ -448,18 +383,8 @@ fn source_roots(target: &SingleFileTarget) -> Vec<PathBuf> {
/// Resolves the classpath and plans the `javac` invocation for one Java source.
pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<BuildPlan> {
compile_file_plan_cancellable(root, model, file, &CancellationToken::new())
}
/// Cancellable [`compile_file_plan`].
pub fn compile_file_plan_cancellable(
root: &Path,
model: &BuildModel,
file: &Path,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let target = single_file_target(root, model, file)?;
let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?;
let classpath = single_file_classpath(root, model, &target)?;
let javac = find_javac(&target.top.env);
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Ok(BuildPlan {
@@ -469,140 +394,6 @@ pub fn compile_file_plan_cancellable(
})
}
fn gradle_for_file<'a>(
root: &Path,
model: &'a BuildModel,
file: &Path,
) -> Option<(&'a crate::GradleModel, &'a crate::GradleProject, PathBuf)> {
let file = normalize(file);
let file_ref = &file;
model
.gradle
.iter()
.flat_map(|g| {
let g_dir = normalize(&subdir(root, &g.dir));
let g_depth = g_dir.components().count();
g.projects.iter().filter_map(move |p| {
let p_dir = normalize(&subdir(root, &p.dir));
file_ref.starts_with(&p_dir).then_some((g, p, p_dir, g_depth))
})
})
.max_by_key(|(_, _, p_dir, g_depth)| (p_dir.components().count(), *g_depth))
.map(|(g, p, p_dir, _)| (g, p, p_dir))
}
/// Whether `file` lies inside a linked Gradle project of `model`.
pub fn has_gradle_file_target(root: &Path, model: &BuildModel, file: &Path) -> bool {
gradle_for_file(root, model, file).is_some()
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GradleCompileCp {
out_dir: Option<String>,
#[serde(default)]
classpath: Vec<String>,
#[serde(default)]
src_dirs: Vec<String>,
release: Option<u32>,
}
/// Resolves the compile classpath from Gradle and plans a single-file `javac` step.
pub fn gradle_compile_file_plan(
root: &Path,
model: &BuildModel,
file: &Path,
cache: &Path,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let name = is_java_file(file)?;
let (gradle, project, module_dir) = gradle_for_file(root, model, file)
.ok_or_else(|| IdeError::not_found("no linked Gradle project found for file"))?;
let rel = rel_str(&module_dir, file);
let test = is_test_source(&rel);
let scope = if test { "test" } else { "main" };
fs::create_dir_all(cache)?;
let init_script = cache.join("gradle-compile-cp.init.gradle");
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
let args = vec![
"--console=plain".into(),
"-q".into(),
"-Dorg.gradle.configuration-cache=false".into(),
"--init-script".into(),
init_script.to_string_lossy().into_owned(),
format!("-Popenidea.target={}", project.path),
format!("-Popenidea.scope={scope}"),
"help".into(),
];
let gradle_dir = subdir(root, &gradle.dir);
let mut reported: Option<String> = None;
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
reported = Some(json.to_owned());
}
})
.map_err(|e| {
if e.kind == ide_core::error::ErrorKind::Cancelled {
e
} else {
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
}
})?;
if !out.success {
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
}
let json = reported.ok_or_else(|| {
IdeError::internal(format!(
"cannot resolve the compile classpath: Gradle did not report source set '{scope}' for {}",
project.path
))
})?;
let cp: GradleCompileCp = serde_json::from_str(&json)
.map_err(|e| IdeError::internal(format!("cannot parse Gradle compile classpath: {e}")))?;
let out_dir = cp
.out_dir
.filter(|d| !d.trim().is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| module_dir.join("build/classes/java").join(scope));
let mut cp_entries: Vec<String> = Vec::new();
if out_dir.is_dir() {
cp_entries.push(out_dir.to_string_lossy().into_owned());
}
if test {
let main_out = module_dir.join("build/classes/java/main");
if main_out.is_dir() {
cp_entries.push(main_out.to_string_lossy().into_owned());
}
}
for sibling in &gradle.projects {
let sibling_dir = subdir(root, &sibling.dir);
if sibling_dir == module_dir {
continue;
}
let classes = sibling_dir.join("build/classes/java/main");
if classes.is_dir() {
cp_entries.push(classes.to_string_lossy().into_owned());
}
}
cp_entries.extend(cp.classpath);
let classpath = join_classpath(cp_entries);
let mut sources: Vec<PathBuf> = cp.src_dirs.into_iter().map(PathBuf::from).filter(|p| p.is_dir()).collect();
if sources.is_empty() {
let fallback: &[&str] = if test { &["src/test/java", "src/main/java"] } else { &["src/main/java"] };
sources.extend(fallback.iter().map(|s| module_dir.join(s)).filter(|p| p.is_dir()));
}
let javac = find_javac(&gradle.env);
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
let step =
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
}
#[cfg(test)]
mod tests {
use super::*;
@@ -648,8 +439,7 @@ mod tests {
#[test]
fn target_finds_the_owning_module_and_the_test_scope() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
let model = fixture(root);
let main = single_file_target(root, &model, &root.join("app/src/main/java/demo/Main.java")).unwrap();
assert_eq!(main.module, root.join("app"));
@@ -663,8 +453,7 @@ mod tests {
#[test]
fn target_rejects_non_java_missing_and_unlinked_files() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
let model = fixture(root);
write(root, "app/pom.xml", "<project/>");
assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err());
@@ -676,8 +465,7 @@ mod tests {
#[test]
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
let model = fixture(root);
let file = root.join("app/src/test/java/demo/MainTest.java");
let target = single_file_target(root, &model, &file).unwrap();
@@ -713,8 +501,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -745,7 +532,6 @@ mod tests {
assert!(cp.split(separator).count() >= 3, "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(!args.lines().any(|a| a == "compile" || a == "package"), "{args}");
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=compile"), "{args}");
fs::create_dir_all(root.join("app/target/test-classes")).unwrap();
let target = single_file_target(root, &model, &root.join("app/src/test/java/demo/MainTest.java")).unwrap();
let cp = single_file_classpath(root, &model, &target).unwrap();
@@ -753,8 +539,6 @@ mod tests {
assert_eq!(paths[0], root.join("app/target/test-classes"));
assert!(paths.contains(&root.join("app/target/classes")), "{cp}");
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
/// Launches request Maven's matching scope without adding reactor test outputs.
@@ -764,8 +548,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
fixture(root);
let script = root.join("mvnw");
fs::write(
@@ -822,8 +605,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
fixture(root);
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
let script = root.join("mvnw");
@@ -864,8 +646,7 @@ mod tests {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let root = dir.path();
fixture(root);
let script = root.join("mvnw");
// `dependency:build-classpath` reports reactor outputs as absolute paths. Keep
@@ -931,79 +712,4 @@ mod tests {
calls.push('x');
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
}
#[test]
fn javac_step_omits_empty_classpath_and_uses_source_target_on_jdk_8() {
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
let mut model = fixture(root);
let file = root.join("app/src/main/java/demo/Main.java");
let jdk8 = root.join("jdk8");
fs::create_dir_all(jdk8.join("bin")).unwrap();
fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"\n").unwrap();
let project = model.maven.as_mut().unwrap().projects.iter_mut().find(|p| p.dir == "app").unwrap();
project.java_version = Some(8);
let mut target = single_file_target(root, &model, &file).unwrap();
target.top.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
let step = javac_step(&target, &file, "", "javac").unwrap();
assert!(!step.args.iter().any(|a| a == "-cp"), "{:?}", step.args);
assert!(step.args.iter().any(|a| a == "-g"), "{:?}", step.args);
assert!(step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{:?}", step.args);
assert!(!step.args.iter().any(|a| a == "--release"), "{:?}", step.args);
}
#[cfg(unix)]
#[test]
fn gradle_single_file_compiles_with_source_set_classpath_and_siblings() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root_buf = dunce::canonicalize(dir.path()).unwrap();
let root = root_buf.as_path();
write(root, "settings.gradle", "include ':lib', ':app'");
write(root, "lib/build.gradle", "plugins { id 'java' }");
write(root, "app/build.gradle", "plugins { id 'java' }");
write(root, "app/src/main/java/demo/App.java", "package demo; class App {}");
write(root, "app/src/test/java/demo/AppTest.java", "package demo; class AppTest {}");
fs::create_dir_all(root.join("lib/build/classes/java/main")).unwrap();
fs::create_dir_all(root.join("app/build/classes/java/main")).unwrap();
let wrapper = root.join("gradlew");
fs::write(
&wrapper,
"#!/bin/sh\nprintf '%s\\n' \"$@\" > gradle_args.txt\nscope='main'\nfor a in \"$@\"; do\ncase \"$a\" in -Popenidea.scope=*) scope=\"${a#-Popenidea.scope=}\" ;; esac\ndone\nprintf '@openidea-compile-cp\\t{\"outDir\":\"%s/app/build/classes/java/%s\",\"classpath\":[\"%s/deps/guava.jar\"],\"srcDirs\":[\"%s/app/src/%s/java\"],\"release\":17}\\n' \"$PWD\" \"$scope\" \"$PWD\" \"$PWD\" \"$scope\"\n",
)
.unwrap();
fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(root, &root.join("cache"), None);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let main_file = root.join("app/src/main/java/demo/App.java");
let main_plan = gradle_compile_file_plan(root, &model, &main_file, &cache, &cancel).unwrap();
assert_eq!(main_plan.system, BuildSystem::Gradle);
assert_eq!(main_plan.title, "Compile App.java");
let step = &main_plan.steps[0];
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Popenidea.target=:app"), "{args}");
assert!(args.lines().any(|a| a == "-Popenidea.scope=main"), "{args}");
let cp = &step.args[step.args.iter().position(|a| a == "-cp").unwrap() + 1];
let paths: Vec<_> = std::env::split_paths(cp).collect();
assert!(paths.contains(&root.join("app/build/classes/java/main")), "{cp}");
assert!(paths.contains(&root.join("lib/build/classes/java/main")), "{cp}");
assert!(paths.contains(&root.join("deps/guava.jar")), "{cp}");
assert!(step.args.windows(2).any(|w| w == ["--release", "17"]), "{:?}", step.args);
assert!(step.args.iter().any(|a| a == "-implicit:none"), "{:?}", step.args);
let test_file = root.join("app/src/test/java/demo/AppTest.java");
let test_plan = gradle_compile_file_plan(root, &model, &test_file, &cache, &cancel).unwrap();
assert_eq!(test_plan.title, "Compile AppTest.java");
let test_step = &test_plan.steps[0];
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Popenidea.scope=test"), "{args}");
assert!(
test_step.args.windows(2).any(|w| w == ["-d", &root.join("app/build/classes/java/test").to_string_lossy()])
);
}
}
+21 -157
View File
@@ -162,6 +162,16 @@ fn classpath(entries: &[String]) -> String {
entries.join(if cfg!(windows) { ";" } else { ":" })
}
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
fn release_args(level: Option<u32>, jdk: Option<&StructureJdk>) -> Vec<String> {
let Some(level) = level else { return Vec::new() };
if jdk.is_none_or(|j| j.major >= 9) {
vec!["--release".into(), level.to_string()]
} else {
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
}
}
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
pub fn language_release(level: &str) -> Option<u32> {
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
@@ -169,25 +179,6 @@ pub fn language_release(level: &str) -> Option<u32> {
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
}
fn structure_compiler(
root: &Path,
ps: &ProjectStructureSettings,
jdk: Option<&StructureJdk>,
language_level: &str,
) -> (Option<u32>, BTreeMap<String, String>, String) {
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
(level, env, javac)
}
/// The Build / Rebuild plan of a project without a build tool, or `None` when it has no
/// Java sources under its source roots. `language_level`: the project's, unless the module
/// overrides it. Writes the javac argument files below `cache`.
@@ -212,7 +203,16 @@ pub fn structure_plan(
return Ok(None);
}
let (main_out, test_out) = structure_outputs(root, ps);
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let module = root_module(root, ps);
let level = module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release);
let env: BTreeMap<String, String> = jdk
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
.unwrap_or_default();
let javac = find_javac(&env);
let args_dir = cache.join("javac");
fs::create_dir_all(&args_dir)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?;
@@ -241,7 +241,7 @@ pub fn structure_plan(
if !cp.is_empty() {
step.args.extend(["-cp".into(), classpath(cp)]);
}
step.args.extend(single::release_args(level, jdk.map(|j| j.major)));
step.args.extend(release_args(level, jdk));
step.args.push(format!("@{}", args_file.to_string_lossy()));
step.env = env.clone();
step.mkdirs = vec![out.to_path_buf()];
@@ -281,47 +281,6 @@ pub fn structure_plan(
Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps }))
}
/// Single-file `javac` plan for a Java project without a build tool (Project Structure).
pub fn structure_compile_file_plan(
root: &Path,
ps: &ProjectStructureSettings,
roots: &StructureRoots,
jdk: Option<&StructureJdk>,
language_level: &str,
file: &Path,
) -> IdeResult<BuildPlan> {
let name = single::is_java_file(file)?;
let rel = rel_str(root, file);
let test = if roots.tests.is_empty() {
single::is_test_source(&rel)
} else {
let file_norm = normalize(file);
roots.tests.iter().any(|t| file_norm.starts_with(normalize(t)))
};
let (main_out, test_out) = structure_outputs(root, ps);
let out_dir = if test { &test_out } else { &main_out };
let mut cp: Vec<String> = Vec::new();
if test && test_out.is_dir() {
cp.push(test_out.to_string_lossy().into_owned());
}
if main_out.is_dir() {
cp.push(main_out.to_string_lossy().into_owned());
}
cp.extend(library_entries(root, ps, test));
let cp = single::join_classpath(cp);
let mut src_roots: Vec<PathBuf> = Vec::new();
if test {
src_roots.extend(roots.tests.iter().filter(|p| p.is_dir()).cloned());
}
src_roots.extend(roots.sources.iter().filter(|p| p.is_dir()).cloned());
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
let release = single::release_args(level, jdk.map(|j| j.major));
let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
}
/// Where an artifact goes: its output folder, else `out/artifacts/<name>`.
pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
resolve_dir(root, &artifact.output_directory)
@@ -1049,99 +1008,4 @@ mod tests {
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("c.jar").is_file());
}
#[test]
fn plans_single_file_javac_for_main_test_and_jdk8() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("shop");
write(&root.join("src/com/a/Main.java"), "package com.a; class Main {}");
write(&root.join("test/com/a/MainTest.java"), "package com.a; class MainTest {}");
write(&root.join("out/production/shop/com/a/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary { name: "core".into(), classes: vec!["lib/core.jar".into()], ..Default::default() },
ProjectLibrary {
name: "junit".into(),
classes: vec!["lib/junit.jar".into()],
scope: DependencyScope::Test,
..Default::default()
},
],
..Default::default()
};
let roots =
StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
let jdk21 = StructureJdk { home: PathBuf::from("/jdk21"), major: 21 };
let main_plan =
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk21), "17", &root.join("src/com/a/Main.java"))
.unwrap();
assert_eq!(main_plan.system, BuildSystem::Javac);
assert_eq!(main_plan.title, "Compile Main.java");
let main_step = &main_plan.steps[0];
let cp = &main_step.args[main_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
assert!(cp.contains("core.jar") && !cp.contains("junit.jar"), "{cp}");
assert!(main_step.args.windows(2).any(|w| w == ["--release", "17"]));
assert!(main_step.args.iter().any(|a| a == "-implicit:none"));
let jdk8 = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 };
let test_plan =
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk8), "8", &root.join("test/com/a/MainTest.java"))
.unwrap();
let test_step = &test_plan.steps[0];
let test_cp = &test_step.args[test_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
assert!(test_cp.contains("out/production/shop") || test_cp.contains("out\\production\\shop"), "{test_cp}");
assert!(test_cp.contains("junit.jar"), "{test_cp}");
assert!(test_step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]));
assert!(test_step.args.windows(2).any(|w| w[0] == "-d" && Path::new(&w[1]).ends_with("out/test/shop")));
}
#[test]
fn compiles_only_the_target_java_file_and_reports_errors() {
let exe = if cfg!(windows) { "javac.exe" } else { "javac" };
if !std::process::Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success()) {
return;
}
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("demo");
let good = root.join("src/p/Good.java");
let broken_sibling = root.join("src/p/BrokenSibling.java");
let bad_target = root.join("src/p/BadTarget.java");
write(&good, "package p;\npublic class Good { public static int ok() { return 1; } }\n");
write(&broken_sibling, "package p;\npublic class BrokenSibling { MissingType field; }\n");
write(&bad_target, "package p;\npublic class BadTarget {\n UnknownSymbol field;\n}\n");
let ps = ProjectStructureSettings::default();
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let cancel = CancellationToken::new();
// 1. Valid file compiles cleanly without touching or failing on BrokenSibling.java.
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &good).unwrap();
let events = std::sync::Mutex::new(Vec::new());
let result = run(&root, &plan, &cancel, &|e| events.lock().unwrap().push(e)).unwrap();
assert!(result.success, "expected single-file compile to succeed: {:?}", result.messages);
assert_eq!(result.errors, 0);
assert!(root.join("out/production/demo/p/Good.class").is_file());
assert!(!root.join("out/production/demo/p/BrokenSibling.class").exists());
// 2. Broken target fails, streams raw compiler output, and produces structured diagnostics.
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &bad_target).unwrap();
let bad_events = std::sync::Mutex::new(Vec::new());
let bad_result = run(&root, &plan, &cancel, &|e| bad_events.lock().unwrap().push(e)).unwrap();
assert!(!bad_result.success);
assert!(bad_result.errors >= 1, "{bad_result:?}");
assert!(
bad_events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Output { .. })),
"expected streamed output"
);
assert!(
bad_result.messages.iter().any(|m| {
m.severity == Severity::Error
&& m.path.as_ref().is_some_and(|p| <ide_core::IpcPath as AsRef<Path>>::as_ref(p) == bad_target)
&& m.range.is_some_and(|r| r.start.line == 2)
}),
"messages={:?}",
bad_result.messages
);
}
}
@@ -1,58 +0,0 @@
// OpenIDEA single-file javac classpath probe for Gradle projects.
// Prints the target source set's output directory, compile classpath, source dirs and release version.
import groovy.json.JsonOutput
def identity = { Project p -> try { p.identityPath.toString() } catch (ignored) { p.path } }
gradle.projectsEvaluated { g ->
def wantedTarget = g.rootProject.findProperty('openidea.target')?.toString() ?: ':'
def scope = g.rootProject.findProperty('openidea.scope')?.toString() ?: 'main'
def project = g.rootProject.allprojects.find { identity(it) == wantedTarget }
if (project == null && g.parent == null) {
project = g.rootProject.allprojects.find { it.path == wantedTarget }
}
if (project == null) return
def sets = project.extensions.findByName('sourceSets') ?: project.findProperty('sourceSets')
def ss = sets?.findByName(scope)
if (ss == null) return
def outDir = null
try { outDir = ss.java.destinationDirectory.get().asFile.canonicalPath } catch (ignored) {}
if (outDir == null) {
try { outDir = ss.output.classesDirs.files.iterator().next().canonicalPath } catch (ignored) {}
}
def cp = []
if (scope == 'test') {
def mainSet = sets.findByName('main')
try { mainSet?.output?.classesDirs?.files?.each { cp << it.canonicalPath } } catch (ignored) {}
}
try { ss.compileClasspath.files.each { cp << it.canonicalPath } } catch (ignored) {}
cp = cp.unique()
def srcDirs = []
try { ss.java.srcDirs.each { srcDirs << it.canonicalPath } } catch (ignored) {}
if (scope == 'test') {
def mainSet = sets.findByName('main')
try { mainSet?.java?.srcDirs?.each { srcDirs << it.canonicalPath } } catch (ignored) {}
}
srcDirs = srcDirs.unique()
def release = null
try {
def compileTask = project.tasks.findByName(ss.compileJavaTaskName)
release = compileTask?.options?.release?.getOrNull()
} catch (ignored) {}
if (release == null) {
try {
def java = project.extensions.findByName('java')
def lv = null
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
def target = java != null ? java.targetCompatibility : project.findProperty('targetCompatibility')
release = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
} catch (ignored) {}
}
println '@openidea-compile-cp\t' + JsonOutput.toJson([outDir: outDir, classpath: cp, srcDirs: srcDirs, release: release])
}
-25
View File
@@ -336,7 +336,6 @@ pub struct CodeEditingSettings {
/// Next / previous error goes to errors only (skips warnings).
pub next_error_errors_only: bool,
pub sticky_lines_max: u32,
pub sticky_lines_disabled_languages: Vec<String>,
}
impl Default for CodeEditingSettings {
@@ -349,7 +348,6 @@ impl Default for CodeEditingSettings {
quick_doc_delay: 500,
next_error_errors_only: true,
sticky_lines_max: 5,
sticky_lines_disabled_languages: Vec::new(),
}
}
}
@@ -475,12 +473,6 @@ pub struct LanguageCodeStyle {
/// PHP: align `=` of consecutive assignment statements after formatting.
#[serde(skip_serializing_if = "Option::is_none")]
pub align_consecutive_assignments: Option<bool>,
/// SQL › Case › Keywords: `upper` | `lower` | `keep` (other languages ignore it).
#[serde(skip_serializing_if = "Option::is_none")]
pub keyword_case: Option<String>,
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -593,20 +585,3 @@ mod folding_tests {
}
}
}
#[cfg(test)]
mod sticky_lines_tests {
use super::CodeEditingSettings;
#[test]
fn sticky_lines_language_exclusions_round_trip_and_default_to_empty() {
let old: CodeEditingSettings = serde_json::from_value(serde_json::json!({"stickyLinesMax": 3})).unwrap();
assert_eq!(old.sticky_lines_max, 3);
assert!(old.sticky_lines_disabled_languages.is_empty());
let json = serde_json::json!(["markdown", "rust"]);
let saved: CodeEditingSettings =
serde_json::from_value(serde_json::json!({"stickyLinesDisabledLanguages": json})).unwrap();
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
}
}
+2 -19
View File
@@ -402,14 +402,12 @@ mod windows_job {
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation, QueryInformationJobObject,
SetInformationJobObject, TerminateJobObject,
};
use windows_sys::Win32::System::Threading::{
IO_COUNTERS, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE,
};
use windows_sys::Win32::System::Threading::{IO_COUNTERS, OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
/// A job object holding one launch's processes. The handle is kept open for the
/// launch's lifetime: `KILL_ON_JOB_CLOSE` ends anything still in the job when the
@@ -512,21 +510,6 @@ mod windows_job {
ok != 0
}
/// Whether the running process belongs to this specific launch's job.
pub fn contains_pid(&self, pid: u32) -> bool {
// SAFETY: a non-null result is a process handle owned by this call.
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
if handle.is_null() {
return false;
}
// SAFETY: the process handle was just opened above and the job handle is owned here.
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
let mut contained = 0;
// SAFETY: both handles remain valid and `contained` is a writable BOOL.
(unsafe { IsProcessInJob(handle.as_raw_handle(), self.0.as_raw_handle(), &mut contained) }) != 0
&& contained != 0
}
/// Terminates every process in the job. `false` when the call failed (the job
/// handle is invalid): callers then fall back to `taskkill /T /F`. Termination is
/// asynchronous; poll [`Job::is_running`] (bounded by [`TREE_EXIT_WAIT`]) until
-2
View File
@@ -941,8 +941,6 @@ pub struct FileIconThemeOptions {
#[serde(default, rename_all = "camelCase")]
pub struct MainToolbarSettings {
pub left: Vec<String>,
/// Centred in the toolbar (between the other two groups when they leave too little room).
pub center: Vec<String>,
pub right: Vec<String>,
/// Widgets the user removed.
pub hidden: Vec<String>,
-28
View File
@@ -460,16 +460,6 @@ impl Default for ConsoleSettings {
}
}
/// Whether compiled classes are reloaded into running Java debug sessions after compilation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum HotSwapPolicy {
#[default]
Ask,
Always,
Never,
}
/// Build, Execution, Deployment › Debugger (+ Data Views, Stepping, Python Debugger).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -497,8 +487,6 @@ pub struct DebuggerSettings {
pub debug_server_page: bool,
/// Flutter: saving a Dart file of a running debug session hot reloads the app.
pub flutter_hot_reload_on_save: bool,
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
}
@@ -520,7 +508,6 @@ impl Default for DebuggerSettings {
skip_library_code: true,
debug_server_page: false,
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
}
}
@@ -731,19 +718,4 @@ mod tests {
let off: GitSettings = serde_json::from_str(r#"{"syncBranchOperations":false}"#).unwrap();
assert!(!off.sync_branch_operations);
}
#[test]
fn debugger_hotswap_after_compile_defaults_to_ask_and_roundtrips() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert_eq!(missing.hot_swap_after_compile, HotSwapPolicy::Ask);
for (raw, expected) in
[("ask", HotSwapPolicy::Ask), ("always", HotSwapPolicy::Always), ("never", HotSwapPolicy::Never)]
{
let parsed: DebuggerSettings =
serde_json::from_str(&format!(r#"{{"hotSwapAfterCompile":"{raw}"}}"#)).unwrap();
assert_eq!(parsed.hot_swap_after_compile, expected);
let serialized = serde_json::to_value(&parsed).unwrap();
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
}
+1 -27
View File
@@ -1,6 +1,5 @@
//! Class-table snapshots of a debugged JVM, read over the HotSpot attach listener or, where
//! that is unavailable, counted by the debugger; the JVM's objects through the debugger; and
//! its thread dumps.
//! that is unavailable, counted by the debugger; and the JVM's objects through the debugger.
mod fallback;
mod heap;
@@ -11,7 +10,6 @@ mod snapshot;
pub(crate) mod test_support;
#[cfg(test)]
mod tests;
mod threads;
use crate::session::Session;
use crate::session::Suspension;
@@ -30,8 +28,6 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
pub(crate) use scan::watch_for_attached_jvm;
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
pub const HISTOGRAM_TIMEOUT: Duration = Duration::from_secs(10);
@@ -194,25 +190,6 @@ fn histogram_pid(session: &Session) -> Result<Option<i32>, JvmMemoryUnavailable>
Ok(None)
}
/// Whether `session` is a JVM session attached to `run` that may hold `pid`: its JVM is `pid` or
/// not located yet.
pub(crate) fn attached_to_run(session: &Session, run: ide_core::RunId, pid: u32) -> bool {
let located = session.jvm_pid.load(Ordering::Acquire);
session.run == Some(run)
&& JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& (located <= 0 || located == i64::from(pid))
}
/// Whether `session` debugs the JVM `pid`: the program it launched or the JVM its attach found.
pub(crate) fn debugs_jvm(session: &Session, pid: u32) -> bool {
let jvm = if session.request == "launch" { launch_pid(session) } else { session.jvm_pid.load(Ordering::Acquire) };
JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& jvm > 0
&& jvm == i64::from(pid)
}
/// The JVM a launch session started: the one the IDE started for an app-launched (Kotlin)
/// session, else the program the adapter reported; 0 when neither is known.
pub(crate) fn launch_pid(session: &Session) -> i64 {
@@ -229,8 +206,6 @@ pub(crate) enum JvmTarget<'a> {
/// The JVM of an attach session. While `pid` is 0 it is looked up by `jdwp_port`, which is
/// `None` for a remote JVM.
Attached { pid: &'a AtomicI64, jdwp_port: Option<u16> },
/// A JVM the session debugs, found from outside it (in a run's process tree).
Known(i32),
/// Known without asking any JVM: no histogram can be taken, for this reason.
Unavailable(JvmMemoryUnavailable),
}
@@ -286,7 +261,6 @@ async fn histogram(
fn lookup(target: JvmTarget<'_>) -> Result<Lookup, JvmMemoryUnavailable> {
match target {
JvmTarget::Launched(pid) => Ok(Lookup::Tree(pid)),
JvmTarget::Known(pid) => Ok(Lookup::Known(pid)),
JvmTarget::Attached { pid, jdwp_port } => match i32::try_from(pid.load(Ordering::Acquire)) {
Ok(p) if p > 0 => Ok(Lookup::Known(p)),
_ => jdwp_port.map(Lookup::Scan).ok_or(JvmMemoryUnavailable::AttachedJvmNotFound),
+1 -19
View File
@@ -15,8 +15,7 @@ use std::time::Duration;
const VERSION_TIMEOUT: Duration = Duration::from_secs(2);
const FLAGS_TIMEOUT: Duration = Duration::from_secs(2);
/// The attach calls a snapshot, a heap dump or a thread dump makes, so tests can stand in for a
/// JVM.
/// The attach calls a snapshot or a heap dump makes, so tests can stand in for a JVM.
pub(crate) trait AttachProbe: Send + Sync {
fn has_listener(&self, pid: u32) -> bool;
/// Asks only the JVMs whose pid `may_query` accepts.
@@ -28,11 +27,6 @@ pub(crate) trait AttachProbe: Send + Sync {
fn heap_dump(&self, pid: u32, path: &Path, timeout: Duration) -> Result<HeapDumpReply, AttachError>;
/// `None` where the free space is not known.
fn free_bytes(&self, dir: &Path) -> Option<u64>;
fn thread_print(&self, pid: u32) -> Result<String, AttachError>;
/// Opens `pid`'s attach listener unless it runs; refuses a process not confirmed HotSpot.
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
fn is_application_jvm(&self, pid: u32) -> bool;
}
pub(super) struct JdkProbe {
@@ -79,18 +73,6 @@ impl AttachProbe for JdkProbe {
fn free_bytes(&self, dir: &Path) -> Option<u64> {
ide_heap::free_bytes(dir)
}
fn thread_print(&self, pid: u32) -> Result<String, AttachError> {
ide_jvm_attach::thread_print(pid, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
ide_jvm_attach::ensure_listener(pid, ide_jvm_attach::LISTENER_START_TIMEOUT)
}
fn is_application_jvm(&self, pid: u32) -> bool {
ide_jvm_attach::is_application_jvm(pid)
}
}
fn alive(pid: u32) -> bool {
-361
View File
@@ -3,7 +3,6 @@ use super::heap::*;
use super::scan::*;
use super::snapshot::*;
use super::test_support::{BareSession, FakeInspector, bare_session, bare_session_of};
use super::threads::*;
use super::*;
use ide_core::CancellationToken;
use ide_jvm_attach::{AttachError, HeapDumpReply, HistogramRow, JavaVersion};
@@ -40,13 +39,6 @@ struct FakeProbe {
free: Option<u64>,
/// Answering this command stops the program: runs the hook.
stops_on: Option<(&'static str, StopHook)>,
thread_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
/// Replies to `ensure_listener`, in order; `Ok` once empty.
listener_starts: parking_lot::Mutex<VecDeque<Result<(), AttachError>>>,
/// Pids `is_application_jvm` confirms.
application_jvms: Vec<u32>,
/// Pids `ensure_listener` was asked for.
ensured: parking_lot::Mutex<Vec<u32>>,
}
type StopHook = Box<dyn Fn() + Send + Sync>;
@@ -105,10 +97,6 @@ impl FakeProbe {
dump_bytes: 64,
free: None,
stops_on: None,
thread_dumps: parking_lot::Mutex::new(VecDeque::new()),
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
application_jvms: Vec::new(),
ensured: parking_lot::Mutex::new(Vec::new()),
}
}
@@ -179,20 +167,6 @@ impl AttachProbe for FakeProbe {
fn free_bytes(&self, _dir: &Path) -> Option<u64> {
self.free
}
fn thread_print(&self, _pid: u32) -> Result<String, AttachError> {
self.enter("thread_print");
std::thread::sleep(self.delay);
self.leave();
self.thread_dumps.lock().pop_front().expect("unexpected thread dump request")
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
self.record("ensure_listener");
self.ensured.lock().push(pid);
self.listener_starts.lock().pop_front().unwrap_or(Ok(()))
}
fn is_application_jvm(&self, pid: u32) -> bool {
self.application_jvms.contains(&pid)
}
}
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
@@ -1186,341 +1160,6 @@ async fn jdk11_is_refused_while_the_link_is_suspended_before_dap_stops() {
assert!(!dir.exists());
}
const THREADS: &str = "Full thread dump OpenJDK 64-Bit Server VM (21.0.5+11-LTS mixed mode, sharing):\n\n\"main\" #1 [259] prio=5 os_prio=31 cpu=31.20ms elapsed=1.70s tid=0x1 nid=259 runnable [0x2]\n java.lang.Thread.State: RUNNABLE\n";
fn dumping_threads(listener: u32, dumps: Vec<Result<String, AttachError>>) -> FakeProbe {
let fake = FakeProbe::new(listener, Vec::new());
*fake.thread_dumps.lock() = dumps.into();
fake
}
fn threads_unavailable(r: JvmThreadsResult) -> JvmThreadsUnavailable {
match r {
JvmThreadsResult::Unavailable { reason } => reason,
other => panic!("{other:?}"),
}
}
fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
JvmThreadsUnavailable::Jvm { reason }
}
#[test]
fn threads_while_running_start_the_listener() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let r = dump_threads(&fake, 12, false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
assert!(!dump.taken_while_suspended);
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_without_listener_do_not_attach() {
let fake = dumping_threads(99, Vec::new());
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
);
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_while_suspended_on_11_are_refused() {
let mut fake = dumping_threads(12, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
);
fake.version = None;
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
);
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_while_suspended_on_17_use_the_running_listener() {
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let r = dump_threads(&fake, 12, true);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.java_version, "17.0.13");
assert_eq!(*fake.commands.lock(), ["thread_print"]);
}
#[test]
fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![12];
let r = dump_tree(&fake, &[10, 11, 12], false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 12);
assert_eq!(*fake.ensured.lock(), [12]);
// No JVM at all: the reported pid is asked, which tells an exited program from a non-JVM.
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
assert_eq!(
threads_unavailable(dump_tree(&fake, &[10, 11], false)),
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
);
assert_eq!(*fake.ensured.lock(), [10]);
}
#[cfg(unix)]
#[tokio::test]
async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reported_pid() {
struct Child(std::process::Child);
impl Drop for Child {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let child = Child(std::process::Command::new("sleep").arg("30").spawn().unwrap());
let jvm = child.0.id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(0, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![jvm];
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(std::process::id() as i32);
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, jvm);
assert_eq!(*fake.ensured.lock(), [jvm]);
}
#[tokio::test]
async fn a_session_debugs_the_jvm_it_launched_or_found() {
let attach = bare_session("attach");
attach.session.jvm_pid.store(4242, Ordering::Release);
assert!(debugs_jvm(&attach.session, 4242));
assert!(!debugs_jvm(&attach.session, 4243));
let launch = bare_session("launch");
launch.session.debuggee_pid.store(77, Ordering::Release);
assert!(debugs_jvm(&launch.session, 77));
let python = bare_session_of("debugpy", "attach");
python.session.jvm_pid.store(4242, Ordering::Release);
assert!(!debugs_jvm(&python.session, 4242));
attach.session.terminated.store(true, Ordering::Release);
assert!(!debugs_jvm(&attach.session, 4242));
// An attach whose JVM is not found yet debugs no pid.
assert!(!debugs_jvm(&bare_session("attach").session, 0));
}
#[tokio::test]
async fn a_session_attached_to_a_run_may_hold_its_jvm_before_it_is_located() {
let run = ide_core::RunId(7);
let mut bare = bare_session("attach");
Arc::get_mut(&mut bare.session).unwrap().run = Some(run);
// Gradle bootRun Debug opens no attach listener, so the attach-time scan finds no pid.
assert!(attached_to_run(&bare.session, run, 555));
assert!(!attached_to_run(&bare.session, ide_core::RunId(8), 555));
bare.session.jvm_pid.store(4242, Ordering::Release);
assert!(attached_to_run(&bare.session, run, 4242));
assert!(!attached_to_run(&bare.session, run, 555), "another JVM of the same run");
bare.session.terminated.store(true, Ordering::Release);
assert!(!attached_to_run(&bare.session, run, 4242));
let mut python = bare_session_of("debugpy", "attach");
Arc::get_mut(&mut python.session).unwrap().run = Some(run);
assert!(!attached_to_run(&python.session, run, 555));
assert!(!attached_to_run(&bare_session("attach").session, run, 555), "not linked to a run");
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
// Stopped at a breakpoint, no listener: refused with the resume reason, no listener start.
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
// Running: the run's JVM is dumped under the session's turn.
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
assert_eq!(*fake.ensured.lock(), [555]);
}
/// A run's JVM held at a breakpoint by a debugger attached to it (Debug of `spring-boot:run`).
fn stopped_attach(pid: u32) -> BareSession {
let bare = bare_session("attach");
bare.session.jvm_pid.store(i64::from(pid), Ordering::Release);
bare.session.suspended.stopped(None, true);
bare
}
#[tokio::test]
async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
let bare = stopped_attach(4242);
let mut fake = dumping_threads(4242, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
assert!(fake.commands.lock().is_empty());
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.pid, 4242);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let bare = bare_session("attach");
bare.session.jvm_pid.store(4242, Ordering::Release);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let histogram = bare.session.jvm_memory.lock().await;
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind the session's histogram.
bare.session.suspended.stopped(None, true);
drop(histogram);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_of_an_exited_program() {
let mut fake = dumping_threads(99, Vec::new());
fake.alive = false;
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
}
#[test]
fn thread_dump_errors_map_to_reasons() {
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
let mut fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
fake.alive = false;
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
panic!("not a failure")
};
assert!(message.contains("no"), "{message}");
}
#[test]
fn thread_results_serialize_with_camel_case_tags() {
let r = JvmThreadsResult::Unavailable { reason: threads_jvm(JvmMemoryUnavailable::ListenerNotRunning) };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "jvm", "reason": {"kind": "listenerNotRunning"}}})
);
let r = JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::ListenerDidNotStart };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "listenerDidNotStart"}})
);
let dump = JvmThreadDump {
text: "t".into(),
pid: 7,
java_version: String::new(),
taken_while_suspended: true,
elapsed_ms: 3,
};
assert_eq!(
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
serde_json::json!({
"status": "ready",
"dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
})
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn threads_take_the_memory_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.histograms.lock() = vec![Ok(HISTOGRAM.into())].into();
fake.delay = Duration::from_millis(100);
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = Suspension::default();
let (classes, threads) = tokio::join!(
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
);
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
let threads = threads.unwrap();
assert!(matches!(threads, JvmThreadsResult::Ready { .. }), "{threads:?}");
assert_eq!(fake.max_in_flight.load(Ordering::SeqCst), 1);
assert_eq!(*fake.commands.lock(), ["histogram", "ensure_listener", "thread_print"]);
}
#[cfg(unix)]
#[tokio::test]
async fn queued_thread_dump_reads_suspension_under_the_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let suspended = Suspension::default();
let fake = Arc::new(dumping_threads(0, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = state.lock().await;
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind a class-table request.
suspended.stopped(None, true);
drop(running);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[tokio::test]
async fn attached_thread_dump_keeps_the_scanned_jvm() {
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let jvm_pid = AtomicI64::new(0);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.jdwp = Some((5005, 4242));
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 4242);
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
}
#[tokio::test]
async fn capability_matches_memory() {
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
-181
View File
@@ -1,181 +0,0 @@
//! A thread dump (`Thread.print -l`) of a debugged or running JVM.
use super::heap::capture_suspended;
use super::snapshot::{AttachProbe, JdkProbe, attach_failure, gone, pick_jvm_pid};
use super::{
JvmMemoryState, JvmMemoryUnavailable, JvmTarget, histogram_pid, keep_found, lookup, resolve_jvm,
safe_while_suspended, session_target, until_located,
};
use crate::session::Session;
use ide_core::{IdeError, IdeResult};
use ide_jvm_attach::AttachError;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JvmThreadDump {
pub text: String,
pub pid: u32,
/// Empty when unknown.
pub java_version: String,
pub taken_while_suspended: bool,
/// Wall time of the `Thread.print` request.
pub elapsed_ms: u32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsUnavailable {
/// The reason a class table could not be read applies to the dump too.
Jvm {
reason: JvmMemoryUnavailable,
},
/// The JVM ignored the request to open its attach listener (`-XX:+DisableAttachMechanism`).
ListenerDidNotStart,
/// A run on a remote host, whose JVM this machine cannot attach to.
RemoteRun,
Failed {
message: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "status", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsResult {
Ready { dump: JvmThreadDump },
Unavailable { reason: JvmThreadsUnavailable },
}
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
/// dump timeouts, so callers run it in `spawn_blocking`.
pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false)
}
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
until_located(&session).await;
let launched = histogram_pid(&session);
// Detached, so a caller that gives up cannot release the lock while the JVM is still
// answering and let a class-table request run next to it.
tokio::spawn(async move {
let target = session_target(&session, launched);
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
/// is: a JVM the debugger holds suspended is never asked to open a listener.
pub(crate) async fn debugged_run_thread_dump(session: Arc<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
// Detached for the same reason as `session_thread_dump`.
tokio::spawn(async move {
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
known_pid_dump(&session, probe, pid).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
pub(super) async fn known_pid_dump(
session: &Session,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
pid: u32,
) -> IdeResult<JvmThreadsResult> {
let target =
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
}
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
/// session; `suspended` and then `probe` are read once it is held.
pub(super) async fn thread_dump(
state: &tokio::sync::Mutex<JvmMemoryState>,
suspended: impl FnOnce() -> bool,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
target: JvmTarget<'_>,
) -> IdeResult<JvmThreadsResult> {
let _turn = state.lock().await;
let suspended = suspended();
let lookup = match lookup(target) {
Ok(lookup) => lookup,
Err(reason) => return Ok(jvm(reason)),
};
let probe = probe(suspended);
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
Err(reason) => (None, jvm(reason)),
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?;
keep_found(target, found);
Ok(outcome)
}
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
/// Gradle client), else the reported pid.
pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
match jvm_pid {
Some(pid) => dump_threads(probe, pid, suspended),
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
}
}
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
if suspended {
if !probe.has_listener(pid) {
return jvm(gone(probe, pid));
}
} else if let Err(e) = probe.ensure_listener(pid) {
return failure(probe, pid, e);
}
let version = probe.version(pid);
if suspended && !safe_while_suspended(version.as_ref()) {
return jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: version.map_or(0, |v| v.major) });
}
let started = std::time::Instant::now();
let text = match probe.thread_print(pid) {
Ok(text) => text,
Err(e) => return failure(probe, pid, e),
};
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
JvmThreadsResult::Ready {
dump: JvmThreadDump {
text,
pid,
java_version: version.map(|v| v.text).unwrap_or_default(),
taken_while_suspended: suspended,
elapsed_ms,
},
}
}
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
let reason = match error {
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
// A program that exited leaves no perf-data file, so it fails the HotSpot check too.
AttachError::NotAJvm if probe.alive(pid) => {
JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::NoJvmProcess }
}
AttachError::NotAJvm => JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ProgramExited },
e => match attach_failure(probe, pid, e, "thread dump") {
Ok(reason) => JvmThreadsUnavailable::Jvm { reason },
Err(e) => JvmThreadsUnavailable::Failed { message: e.message },
},
};
JvmThreadsResult::Unavailable { reason }
}
fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::Jvm { reason } }
}
+2 -40
View File
@@ -27,7 +27,7 @@ use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
@@ -460,15 +460,6 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
serde_json::from_value(run).ok()
}
/// Builds the `launch`/`attach` arguments: our fields first, then `extra_json` merged on top.
pub fn launch_arguments(config: &LaunchConfig) -> IdeResult<Value> {
// VS Code puts `type`, `request` and `name` in the arguments; js-debug picks launch
@@ -1056,7 +1047,7 @@ impl DebugManager {
adapter_name: String,
parent: Option<DebugSessionId>,
request: String,
mut arguments: Value,
arguments: Value,
spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
@@ -1076,7 +1067,6 @@ impl DebugManager {
.flatten();
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
session.exception_classes = exception_classes;
session.run = take_run_link(&mut arguments);
let session = Arc::new(session);
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
let _ = session.launch_type.set(launch_type.to_owned());
@@ -1977,34 +1967,6 @@ impl DebugManager {
jvm_memory::session_heap_dump(session, dir, cancel).await
}
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
/// debugger holds suspended is asked only when it is 17 or later and its listener already
/// runs: otherwise the request would hang until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult<JvmThreadsResult> {
let session = self.session(s)?;
jvm_memory::session_thread_dump(session).await
}
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
/// it, under that session's turn and suspension. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option<IdeResult<JvmThreadsResult>> {
let session = self.jvm_session_of(run, pid)?;
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
}
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
/// found no listener) still holds `pid`.
fn jvm_session_of(&self, run: RunId, pid: u32) -> Option<Arc<Session>> {
let sessions = self.live_sessions();
let linked = || sessions.iter().filter(|s| jvm_memory::attached_to_run(s, run, pid));
linked()
.find(|s| jvm_memory::debugs_jvm(s, pid))
.or_else(|| linked().next())
.or_else(|| sessions.iter().find(|s| jvm_memory::debugs_jvm(s, pid)))
.cloned()
}
/// Gives the session the backend for [`Self::jvm_memory_instances`] and the debugger's class
/// counts; the UI is told to reload the session's capabilities.
pub fn set_jvm_inspector(
+1 -5
View File
@@ -8,7 +8,7 @@ use crate::{Breakpoint, BreakpointState, DataBreakpoint, DebugManager, FunctionB
use ide_core::event::DebugEvent;
#[cfg(unix)]
use ide_core::process::process_tree;
use ide_core::{DebugSessionId, IdeEvent, RunId, TaskId};
use ide_core::{DebugSessionId, IdeEvent, TaskId};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeSet, HashMap};
@@ -117,9 +117,6 @@ pub(crate) struct Session {
pub jvm_located: watch::Sender<bool>,
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
/// The run whose JVM this session attached to (Debug of a build tool's run, Attach to
/// Process on a run): that run's thread dumps go through this session.
pub run: Option<RunId>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
/// Given at start: the class breakpoints must be armed before `configurationDone`.
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
@@ -336,7 +333,6 @@ impl Session {
jvm_located: watch::channel(false).0,
kotlin_mirror: Mutex::new(None),
jvm_memory: tokio::sync::Mutex::default(),
run: None,
stream_tracer: parking_lot::Mutex::new(None),
exception_classes: None,
exception_turn: tokio::sync::Mutex::default(),
-49
View File
@@ -3074,55 +3074,6 @@ async fn local_attach_finds_its_jvm_before_the_debugger_connects() {
assert_eq!(session.jvm_pid.load(Ordering::Acquire), 4242);
}
/// Gradle bootRun Debug: the JVM has no attach listener, so the session never learns its pid. The
/// run's dump still goes through the session and, the program being stopped, signals nothing.
#[cfg(unix)]
#[tokio::test]
async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
let h = harness(Script::default());
let project = tempfile::tempdir().unwrap();
let mut cfg = remote_attach("java-debug", project.path());
let mut extra: Value = serde_json::from_str(cfg.extra_json.as_deref().unwrap()).unwrap();
extra[RUN_LINK] = json!(7);
cfg.extra_json = Some(extra.to_string());
let id = h.start(cfg).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert!(h.request("attach")["arguments"].get(RUN_LINK).is_none(), "IDE-side only");
let session = h.manager.session(id).unwrap();
assert_eq!((session.run, session.jvm_pid.load(Ordering::Acquire)), (Some(RunId(7)), 0));
// `sleep` stands in for the JVM: a SIGQUIT would end it.
let mut jvm = std::process::Command::new("sleep").arg("30").spawn().unwrap();
let pid = jvm.id();
assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap();
let alive = jvm.try_wait().unwrap().is_none();
let _ = jvm.kill();
let _ = jvm.wait();
assert_eq!(
dump,
JvmThreadsResult::Unavailable {
reason: JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ListenerNotRunning }
}
);
assert!(alive, "the stopped JVM was signalled");
}
/// A run's Dump Threads reaches the session attached to the run's JVM, not the plain run path.
#[cfg(unix)]
#[tokio::test]
async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
let h = harness(Script::default());
h.manager.set_jvm_finder(Arc::new(|port, _| (port == 5005).then_some(4242)));
let mut cfg = java_config("attach");
cfg.extra_json = Some(json!({"hostName": "127.0.0.1", "port": 5005}).to_string());
let id = h.start(cfg).await.unwrap();
assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn local_attach_remembers_its_jdwp_port() {
+1 -14
View File
@@ -17,7 +17,7 @@ specta.workspace = true
toml.workspace = true
toml_edit.workspace = true
blake3.workspace = true
tokio = { workspace = true, features = ["net"] }
tokio.workspace = true
tracing.workspace = true
parking_lot.workspace = true
notify.workspace = true
@@ -38,19 +38,6 @@ rsa = { version = "0.10.0-rc.18", features = ["sha2", "pkcs5"] }
zeroize = "1"
open = "5"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Threading",
"Win32_System_JobObjects",
] }
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net"] }
ide-ssh = { workspace = true, features = ["testing"] }
+7 -108
View File
@@ -12,7 +12,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use sqlx::{
Column, ColumnIndex, ConnectOptions, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
Column, ColumnIndex, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode},
pool::PoolConnection,
postgres::{PgConnectOptions, PgConnection, PgSslMode},
@@ -135,7 +135,7 @@ impl Context {
}
macro_rules! sqlx_pool {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr) => {
pub struct $manager {
options: $options,
init: Arc<Vec<String>>,
@@ -170,7 +170,7 @@ macro_rules! sqlx_pool {
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
tokio::time::timeout(self.timeout, async {
let mut conn = self.options.connect().await?;
let mut conn = <$connection>::connect_with(&self.options).await?;
let context_sql = |value: Option<String>| {
value.map(|v| {
if $driver == DbDriver::Postgres {
@@ -183,9 +183,6 @@ macro_rules! sqlx_pool {
for sql in self.init.iter() {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
}
$(if !self.init.is_empty() {
self.options.$after_init(&mut conn).await?;
})?
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
let context = Context::new(context_sql(row.try_get(0)?));
Ok($handle {
@@ -212,88 +209,7 @@ macro_rules! sqlx_pool {
};
}
#[derive(Clone)]
struct PostgresOptions {
connection: PgConnectOptions,
read_only: bool,
}
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
For PgBouncer, check track_extra_parameters.";
impl PostgresOptions {
async fn connect(&self) -> Result<PgConnection, sqlx::Error> {
let mut conn = self.connection.connect().await?;
// A pooler can silently discard startup options. Check before giving the startup script a connection.
self.verify_read_only(&mut conn).await?;
Ok(conn)
}
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
Check the Advanced properties and startup script. {PG_READ_ONLY_HINT}"
)
.into(),
));
}
Ok(())
}
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
self.verify_read_only(conn).await?;
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
));
}
Ok(())
}
}
async fn pg_setting_on(conn: &mut PgConnection, show: &'static str) -> Result<bool, sqlx::Error> {
let row = sqlx::raw_sql(show).fetch_one(conn).await?;
Ok(row.try_get::<&str, _>(0)? == "on")
}
fn postgres_read_only_hint(read_only: bool, code: Option<&str>, message: &str) -> Option<&'static str> {
match (read_only, code, message) {
(
true,
Some("08P01"),
"unsupported startup parameter in options: default_transaction_read_only"
| "unsupported startup parameter: default_transaction_read_only",
) => Some(PG_READ_ONLY_HINT),
(true, Some("08P01"), "unsupported startup parameter: options") => Some(
"This endpoint rejects PostgreSQL startup options. Use an endpoint that supports and tracks \
default_transaction_read_only for each client.",
),
_ => None,
}
}
fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
let hint =
error.as_database_error().and_then(|db| postgres_read_only_hint(read_only, db.code().as_deref(), db.message()));
let mut error = db_err(error);
if let Some(hint) = hint {
error.message.push_str(". ");
error.message.push_str(hint);
}
error
}
sqlx_pool!(
PgManager,
PgHandle,
PostgresOptions,
PgConnection,
DbDriver::Postgres,
"SHOW search_path",
verify_startup_script
);
sqlx_pool!(PgManager, PgHandle, PgConnectOptions, PgConnection, DbDriver::Postgres, "SHOW search_path");
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
pub struct ServerPool<M: ManageConnection> {
@@ -1064,18 +980,17 @@ impl Pool {
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
let options = PostgresOptions { connection: opts, read_only: source.read_only };
let mut manager = PgManager { options, init: init.clone(), timeout };
let mut manager = PgManager { options: opts, init: init.clone(), timeout };
// Open once directly so authentication failures retain their database error.
let first = match manager.connect().await {
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
manager.options = manager.options.clone().ssl_mode(PgSslMode::Disable);
manager.connect().await
}
first => first,
}
.map_err(|e| postgres_connect_error(e, source.read_only))?;
.map_err(db_err)?;
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
let _ = pool.add(first);
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
@@ -1717,22 +1632,6 @@ mod tests {
}
}
#[test]
fn postgres_read_only_guidance_identifies_what_the_pooler_rejected() {
let rejected = "unsupported startup parameter in options: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), rejected), Some(PG_READ_ONLY_HINT));
let direct = "unsupported startup parameter: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), direct), Some(PG_READ_ONLY_HINT));
let options = postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: options").unwrap();
assert!(options.contains("rejects PostgreSQL startup options"));
assert_eq!(postgres_read_only_hint(false, Some("08P01"), rejected), None);
assert_eq!(postgres_read_only_hint(true, Some("28P01"), rejected), None);
assert_eq!(
postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: extra_float_digits"),
None
);
}
#[test]
fn prefer_retries_without_tls_only_after_a_failed_handshake() {
use std::io;
-436
View File
@@ -1,436 +0,0 @@
//! An approved foreground helper behind a loopback relay owned by the IDE.
use crate::DbExternalTunnel;
use ide_core::{IdeError, IdeResult, error::ErrorKind, process};
use parking_lot::Mutex;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::net::{TcpListener, TcpSocket, TcpStream};
use tokio::sync::Semaphore;
use tokio::task::{JoinHandle, JoinSet};
#[cfg(target_os = "linux")]
#[path = "external_tunnel/linux.rs"]
mod platform;
#[cfg(target_os = "macos")]
#[path = "external_tunnel/macos.rs"]
mod platform;
#[cfg(windows)]
#[path = "external_tunnel/windows.rs"]
mod platform;
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
mod platform {
use super::*;
pub(super) async fn owns_socket(_: &Arc<Helper>, _: SocketAddr, _: Option<SocketAddr>) -> io::Result<bool> {
Err(io::Error::new(io::ErrorKind::Unsupported, "socket ownership cannot be verified on this OS"))
}
}
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(100);
const MAX_CONNECTIONS: usize = 128;
static VERIFICATION_SLOTS: Semaphore = Semaphore::const_new(8);
static HELPERS: Mutex<ActiveHelpers> = Mutex::new(ActiveHelpers { stopping: false, children: Vec::new() });
struct ActiveHelpers {
stopping: bool,
children: Vec<Weak<Helper>>,
}
/// Stop the IDE's external TCP tunnel processes before desktop exit or restart.
pub fn stop_external_tunnels_on_exit() {
let children = {
let mut active = HELPERS.lock();
active.stopping = true;
std::mem::take(&mut active.children)
};
for helper in children.into_iter().filter_map(|child| child.upgrade()) {
helper.stop();
}
}
pub(super) struct ExternalTunnel {
port: u16,
// Keep the address reserved even after the helper exits, until the last route reference drops.
_listener: Arc<TcpListener>,
helper: Weak<Helper>,
task: JoinHandle<()>,
}
impl ExternalTunnel {
pub(super) fn validate(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<()> {
helper_target(config, target).map(|_| ())
}
pub(super) async fn open(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<Self> {
if !cfg!(any(target_os = "linux", target_os = "macos", windows)) {
return Err(IdeError::unavailable("External TCP tunnel socket ownership cannot be verified on this OS"));
}
let listener = Arc::new(loopback_socket()?.listen(128)?);
let port = listener.local_addr()?.port();
let reservation = loopback_socket()?;
let endpoint = reservation.local_addr()?;
let arguments = helper_arguments(config, target, endpoint.port())?;
drop(reservation);
let helper = launch_helper(Path::new(&config.executable), &arguments)?;
let ready = tokio::time::timeout(STARTUP_TIMEOUT, async {
loop {
if !helper.is_alive() {
return Err(IdeError::new(
ErrorKind::Io,
"The external TCP tunnel helper exited before opening its loopback listener. \
Check the helper command in a terminal.",
));
}
if verify_socket(&helper, endpoint, None).await.map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not verify the external TCP tunnel listener: {error}"))
})? {
return Ok(());
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await;
ready.map_err(|_| {
IdeError::new(
ErrorKind::Io,
format!(
"The external TCP tunnel helper did not open an owned listener at {endpoint} before the startup timeout. \
Check that the command binds to 127.0.0.1 and uses {{localPort}}."
),
)
})??;
let watched_helper = Arc::downgrade(&helper);
let task = tokio::spawn(relay(Arc::clone(&listener), endpoint, helper));
Ok(Self { port, _listener: listener, helper: watched_helper, task })
}
pub(super) fn port(&self) -> u16 {
self.port
}
pub(super) fn is_closed(&self) -> bool {
self.task.is_finished() || self.helper.upgrade().is_none_or(|helper| !helper.is_alive())
}
}
impl Drop for ExternalTunnel {
fn drop(&mut self) {
self.task.abort();
}
}
fn loopback_socket() -> io::Result<TcpSocket> {
let socket = TcpSocket::new_v4()?;
#[cfg(windows)]
platform::make_exclusive(&socket)?;
socket.bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into())?;
Ok(socket)
}
fn helper_target<'a>(config: &DbExternalTunnel, (host, port): (&'a str, u16)) -> IdeResult<(&'a str, u16)> {
let executable = Path::new(&config.executable);
if !executable.is_absolute() || executable.file_name().is_none() || config.executable.contains('\0') {
return Err(IdeError::invalid("Choose an absolute path to the external TCP tunnel executable"));
}
#[cfg(windows)]
if !executable.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) {
return Err(IdeError::invalid("Choose an .exe file for the external TCP tunnel"));
}
let host = host.trim();
let host = host
.strip_prefix('[')
.and_then(|host| host.strip_suffix(']'))
.filter(|host| host.parse::<std::net::Ipv6Addr>().is_ok())
.unwrap_or(host);
let dns = host.strip_suffix('.').unwrap_or(host);
if host.parse::<IpAddr>().is_err()
&& (dns.len() > 253
|| !dns.split('.').all(|label| {
let bytes = label.as_bytes();
bytes.len() <= 63
&& bytes.first().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.last().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.iter().all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
}))
{
return Err(IdeError::invalid("Enter a DNS name or IP address for the external TCP tunnel"));
}
if port == 0 {
return Err(IdeError::invalid("Enter a valid destination port for the external TCP tunnel"));
}
if !config.arguments.iter().any(|arg| arg.contains("{localPort}")) {
return Err(IdeError::invalid("Include {localPort} in the external TCP tunnel arguments"));
}
if config.arguments.iter().any(|arg| arg.contains('\0')) {
return Err(IdeError::invalid("External TCP tunnel arguments cannot contain NUL characters"));
}
Ok((host, port))
}
fn helper_arguments(config: &DbExternalTunnel, target: (&str, u16), local_port: u16) -> IdeResult<Vec<String>> {
let (host, port) = helper_target(config, target)?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let (local_port, port) = (local_port.to_string(), port.to_string());
let placeholders =
[("{host}:{port}", target.as_str()), ("{localPort}", &local_port), ("{host}", host), ("{port}", &port)];
Ok(config
.arguments
.iter()
.map(|arg| {
let mut remaining = arg.as_str();
let mut expanded = String::with_capacity(arg.len());
while let Some(start) = remaining.find('{') {
expanded.push_str(&remaining[..start]);
remaining = &remaining[start..];
if let Some((value, tail)) = placeholders
.into_iter()
.find_map(|(key, value)| remaining.strip_prefix(key).map(|tail| (value, tail)))
{
expanded.push_str(value);
remaining = tail;
} else {
expanded.push('{');
remaining = &remaining[1..];
}
}
expanded.push_str(remaining);
expanded
})
.collect())
}
fn launch_helper(executable: &Path, arguments: &[String]) -> IdeResult<Arc<Helper>> {
let mut active = HELPERS.lock();
if active.stopping {
return Err(IdeError::cancelled());
}
let helper = Arc::new(Helper::spawn(executable, arguments).map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not start the external TCP tunnel helper: {error}"))
})?);
active.children.retain(|child| child.strong_count() > 0);
active.children.push(Arc::downgrade(&helper));
Ok(helper)
}
struct Helper {
child: Option<Child>,
#[cfg(windows)]
job: process::Job,
}
impl Helper {
fn spawn(executable: &Path, arguments: &[String]) -> io::Result<Self> {
let mut command = Command::new(executable);
command
.args(arguments)
.current_dir(executable.parent().expect("validated absolute executable path"))
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// Keep user config discovery available without inheriting database or project variables.
for key in [
"PATH",
"HOME",
"XDG_CONFIG_HOME",
"XDG_CACHE_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"SYSTEMROOT",
"WINDIR",
"TMPDIR",
"TEMP",
"TMP",
"SSH_AUTH_SOCK",
"NO_PROXY",
"no_proxy",
] {
if let Some(value) = process::host_var_os(key) {
command.env(key, value);
}
}
for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"] {
if let Some(value) = process::host_var_os(key)
&& value.to_str().is_some_and(credential_free_proxy)
{
command.env(key, value);
}
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Membership of this group is an authorization check. A separate session limits
// membership to this child and its descendants; the leader also owns the group.
// SAFETY: setsid is async-signal-safe and does not access Rust state after fork.
unsafe {
command.pre_exec(|| if libc::setsid() == -1 { Err(io::Error::last_os_error()) } else { Ok(()) });
}
}
#[cfg(windows)]
{
platform::spawn_suspended(command)
}
#[cfg(not(windows))]
{
Ok(Self { child: Some(command.spawn()?) })
}
}
fn child(&self) -> &Child {
self.child.as_ref().expect("the live helper owns its child handle")
}
#[cfg(unix)]
fn pid(&self) -> u32 {
self.child().id()
}
fn is_alive(&self) -> bool {
#[cfg(unix)]
{
loop {
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
// Keep the group leader unreaped so its id cannot be reused before group cleanup.
// SAFETY: valid output buffer and the id of the child owned by `self`.
let result = unsafe {
libc::waitid(
libc::P_PID,
self.pid(),
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if result == 0 {
// SAFETY: the buffer was zeroed and waitid returned successfully.
return unsafe { info.assume_init().si_pid() == 0 };
}
if io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
return false;
}
}
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
// SAFETY: the owned child handle stays open through this non-blocking check.
unsafe { WaitForSingleObject(self.child().as_raw_handle(), 0) == WAIT_TIMEOUT }
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
fn stop(&self) {
#[cfg(windows)]
let _ = self.job.terminate();
#[cfg(unix)]
process::kill_tree_of(self.pid());
}
}
fn credential_free_proxy(value: &str) -> bool {
let url = if value.contains("://") {
reqwest::Url::parse(value)
} else {
reqwest::Url::parse(&format!("http://{value}"))
};
url.is_ok_and(|url| {
matches!(url.scheme(), "http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h")
&& url.host().is_some()
&& url.username().is_empty()
&& url.password().is_none()
&& matches!(url.path(), "" | "/")
&& url.query().is_none()
&& url.fragment().is_none()
})
}
impl Drop for Helper {
fn drop(&mut self) {
self.stop();
#[cfg(unix)]
if let Some(mut child) = self.child.take() {
// A helper blocked in the kernel must not hold up the async caller during cleanup.
if !matches!(child.try_wait(), Ok(Some(_))) {
let _ = std::thread::Builder::new().spawn(move || child.wait());
}
}
}
}
async fn relay(listener: Arc<TcpListener>, endpoint: SocketAddr, helper: Arc<Helper>) {
let mut connections = JoinSet::new();
let mut liveness = tokio::time::interval(Duration::from_secs(1));
liveness.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = liveness.tick() => {
if !helper.is_alive() { break; }
}
accepted = listener.accept(), if connections.len() < MAX_CONNECTIONS => {
let Ok((mut client, _)) = accepted else {
// Transient errors such as descriptor exhaustion affect new sockets only.
tokio::time::sleep(POLL_INTERVAL).await;
continue;
};
let helper = Arc::clone(&helper);
connections.spawn(async move {
if let Ok(Ok(mut upstream)) = tokio::time::timeout(CONNECTION_TIMEOUT, connect_verified(&helper, endpoint)).await {
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
true
} else {
false
}
});
}
finished = connections.join_next(), if !connections.is_empty() => {
if matches!(finished, Some(Ok(false)))
// A slow ownership probe must not interrupt already verified connections.
&& matches!(tokio::time::timeout(CONNECTION_TIMEOUT, verify_socket(&helper, endpoint, None)).await, Ok(Ok(false)))
{
break;
}
}
}
}
}
async fn connect_verified(helper: &Arc<Helper>, endpoint: SocketAddr) -> io::Result<TcpStream> {
let upstream = TcpStream::connect(endpoint).await?;
let peer = upstream.local_addr()?;
// TCP connect can complete before the helper accepts. Check the server's half of this
// exact connection, keeping all client bytes in the IDE until that socket has an owner.
loop {
if !helper.is_alive() {
return Err(io::Error::new(io::ErrorKind::BrokenPipe, "external TCP tunnel helper exited"));
}
if verify_socket(helper, endpoint, Some(peer)).await? && helper.is_alive() {
return Ok(upstream);
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
async fn verify_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let _slot = VERIFICATION_SLOTS.acquire().await.map_err(io::Error::other)?;
platform::owns_socket(helper, local, peer).await
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos", windows)))]
mod tests;
@@ -1,92 +0,0 @@
use super::{Helper, io};
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read};
use std::net::{SocketAddr, SocketAddrV4};
use std::sync::Arc;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let (SocketAddr::V4(local), peer) = (local, peer) else { return Ok(false) };
let peer = match peer {
Some(SocketAddr::V4(peer)) => Some(peer),
None => None,
_ => return Ok(false),
};
let state = if peer.is_some() { "01" } else { "0A" };
for (table, ipv6) in [("/proc/net/tcp", false), ("/proc/net/tcp6", true)] {
let file = match File::open(table) {
Ok(file) => file,
Err(error) if ipv6 && error.kind() == io::ErrorKind::NotFound => continue,
Err(error) => return Err(error),
};
let local = address(local, ipv6);
let peer = peer.map(|peer| address(peer, ipv6));
// Kernel rows are small, but bound the time spent scanning a busy host's table.
for line in BufReader::new(file.take(8 * 1024 * 1024)).lines().skip(1) {
let line = line?;
let mut fields = line.split_ascii_whitespace().skip(1);
let (Some(left), Some(right), Some(current_state)) = (fields.next(), fields.next(), fields.next())
else {
continue;
};
if left != local || current_state != state || peer.as_deref().is_some_and(|peer| peer != right) {
continue;
}
let Some(inode) = fields.nth(5).and_then(|inode| inode.parse::<u64>().ok()).filter(|inode| *inode != 0)
else {
continue;
};
if group_holds_socket(helper.pid(), inode)? {
return Ok(true);
}
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn address(address: SocketAddrV4, ipv6: bool) -> String {
let ip = address.ip();
let port = address.port();
if !ipv6 {
return format!("{:08X}:{port:04X}", u32::from_ne_bytes(ip.octets()));
}
let octets = ip.to_ipv6_mapped().octets();
let [a, b, c, d] = octets.as_chunks::<4>().0 else { unreachable!() };
format!(
"{:08X}{:08X}{:08X}{:08X}:{port:04X}",
u32::from_ne_bytes(*a),
u32::from_ne_bytes(*b),
u32::from_ne_bytes(*c),
u32::from_ne_bytes(*d)
)
}
fn group_holds_socket(group: u32, inode: u64) -> io::Result<bool> {
let group = i32::try_from(group).map_err(io::Error::other)?;
let target = format!("socket:[{inode}]");
for process in fs::read_dir("/proc")? {
let Ok(process) = process else { continue };
let name = process.file_name();
let Some(pid) = name.to_str().and_then(|name| name.parse::<libc::pid_t>().ok()).filter(|pid| *pid > 0) else {
continue;
};
// SAFETY: this only queries the process group of the enumerated pid.
if unsafe { libc::getpgid(pid) } != group {
continue;
}
let Ok(descriptors) = fs::read_dir(process.path().join("fd")) else { continue };
for descriptor in descriptors.flatten() {
if fs::read_link(descriptor.path()).is_ok_and(|link| link.as_os_str() == target.as_str()) {
// SAFETY: check membership again after examining the fd directory.
if unsafe { libc::getpgid(pid) } == group {
return Ok(true);
}
}
}
}
Ok(false)
}
@@ -1,61 +0,0 @@
use super::{Helper, io};
use std::net::{IpAddr, SocketAddr};
use std::process::Stdio;
use std::sync::Arc;
use tokio::io::AsyncReadExt;
const MAX_OUTPUT: u64 = 64 * 1024;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let group = helper.pid().to_string();
let sockets = format!("-iTCP:{}", local.port());
let state = if peer.is_some() { "-sTCP:ESTABLISHED" } else { "-sTCP:LISTEN" };
let mut probe = tokio::process::Command::new("/usr/sbin/lsof")
.args(["-nP", "-a", "-g", &group, &sockets, state, "-Fgn"])
.env_clear()
.stdin(Stdio::null())
.stderr(Stdio::null())
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut output = Vec::new();
probe.stdout.take().expect("stdout is piped").take(MAX_OUTPUT + 1).read_to_end(&mut output).await?;
if output.len() as u64 > MAX_OUTPUT {
return Err(io::Error::other("loopback socket ownership output exceeded its limit"));
}
let status = probe.wait().await?;
if !status.success() {
// lsof uses exit 1 for a successful scan with no matching descriptors.
return if status.code() == Some(1) && output.is_empty() {
Ok(false)
} else {
Err(io::Error::other("loopback socket ownership query failed"))
};
}
let mut owned = false;
for line in String::from_utf8_lossy(&output).lines() {
match line.as_bytes().first() {
Some(b'p') => owned = false,
Some(b'g') => owned = line[1..] == group,
Some(b'n') if owned => {
let (left, right) =
line[1..].split_once("->").map_or((&line[1..], None), |(left, right)| (left, Some(right)));
if address(left) == Some(local) && right.and_then(address) == peer && right.is_some() == peer.is_some()
{
return Ok(true);
}
}
_ => {}
}
}
Ok(false)
}
fn address(value: &str) -> Option<SocketAddr> {
let address = value.parse::<SocketAddr>().ok()?;
let ip = match address.ip() {
IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or(IpAddr::V6(ip), IpAddr::V4),
ip => ip,
};
Some(SocketAddr::new(ip, address.port()))
}
-188
View File
@@ -1,188 +0,0 @@
use super::*;
use std::io::{Read, Write};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const EXAMPLE: &[u8; 4] = b"test";
const FIXTURE: &str = "external_tunnel::tests::fixture_entry";
fn config(mode: &str) -> crate::DbExternalTunnel {
crate::DbExternalTunnel {
executable: std::env::current_exe().unwrap().to_str().unwrap().to_owned(),
arguments: vec!["--exact".into(), FIXTURE.into(), "--skip".into(), format!("wire-{mode}-{{localPort}}")],
}
}
const TARGET: (&str, u16) = ("db.example", 5432);
// The test binary doubles as a foreground helper without an external interpreter.
#[test]
fn fixture_entry() {
let Some(fixture) = std::env::args().find(|arg| arg.starts_with("wire-")) else { return };
#[cfg(unix)]
// SAFETY: these calls only inspect the current process's session and group.
assert_eq!(unsafe { libc::getsid(0) }, unsafe { libc::getpgrp() });
let (mode, port) = fixture.strip_prefix("wire-").unwrap().split_once('-').unwrap();
let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port.parse().unwrap());
match mode {
"exit" => (),
"idle" => std::thread::sleep(Duration::from_secs(60)),
"waiting" => {
let observer = std::env::args()
.find_map(|arg| arg.strip_prefix("observer-port-").and_then(|port| port.parse::<u16>().ok()))
.unwrap();
let _observer = std::net::TcpStream::connect((Ipv4Addr::LOCALHOST, observer)).unwrap();
std::thread::sleep(Duration::from_secs(60));
}
"tree" => {
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["--exact", FIXTURE, "--skip", &format!("wire-echo-{port}")])
.spawn()
.unwrap();
assert!(child.wait().unwrap().success());
}
"echo" | "once" => {
let socket = std::net::TcpListener::bind(endpoint).unwrap();
std::thread::sleep(Duration::from_millis(150));
for stream in socket.incoming() {
let mut stream = stream.unwrap();
let mut bytes = [0; EXAMPLE.len()];
if stream.read_exact(&mut bytes).is_ok() {
stream.write_all(&bytes).unwrap();
stream.write_all(&endpoint.port().to_be_bytes()).unwrap();
if mode == "once" {
let _ = stream.read(&mut [0]);
break;
}
}
}
}
_ => unreachable!(),
}
}
#[tokio::test]
async fn forwards_multiple_connections_to_the_helpers_child_and_cleans_up() {
let tunnel = ExternalTunnel::open(&config("tree"), TARGET).await.unwrap();
let mut helper_port = 0;
for _ in 0..2 {
let result = tokio::time::timeout(Duration::from_secs(5), async {
let mut db = TcpStream::connect((Ipv4Addr::LOCALHOST, tunnel.port())).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let mut bytes = [0; EXAMPLE.len()];
db.read_exact(&mut bytes).await.unwrap();
assert_eq!(&bytes, EXAMPLE);
db.read_u16().await.unwrap()
});
helper_port = result.await.unwrap();
}
assert_ne!(helper_port, tunnel.port());
assert!(!tunnel.is_closed());
drop(tunnel);
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if TcpStream::connect((Ipv4Addr::LOCALHOST, helper_port)).await.is_err() {
break;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.unwrap();
}
#[tokio::test]
async fn reports_a_helper_that_exits_without_listening() {
let result = ExternalTunnel::open(&config("exit"), TARGET).await;
assert!(result.err().unwrap().message.contains("exited"));
}
#[tokio::test]
async fn dropping_startup_stops_the_helper_before_it_listens() {
let observer = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let mut settings = config("waiting");
settings.arguments.extend(["--skip".into(), format!("observer-port-{}", observer.local_addr().unwrap().port())]);
let startup = tokio::spawn(async move { ExternalTunnel::open(&settings, TARGET).await });
let (mut helper_socket, _) =
tokio::time::timeout(Duration::from_secs(10), observer.accept()).await.unwrap().unwrap();
assert!(!startup.is_finished());
startup.abort();
assert!(startup.await.err().unwrap().is_cancelled());
let error = tokio::time::timeout(Duration::from_secs(5), helper_socket.read_u8()).await.unwrap().unwrap_err();
// Terminating the helper can reset its observer socket on Windows.
assert!(matches!(error.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::ConnectionReset), "{error}");
}
#[tokio::test]
async fn refuses_an_unrelated_established_loopback_socket() {
let unrelated = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let endpoint = unrelated.local_addr().unwrap();
let settings = config("idle");
let arguments = helper_arguments(&settings, TARGET, endpoint.port()).unwrap();
let helper = Arc::new(Helper::spawn(Path::new(&settings.executable), &arguments).unwrap());
assert!(helper.is_alive());
assert!(!verify_socket(&helper, endpoint, None).await.unwrap());
let listener = loopback_socket().unwrap().listen(128).unwrap();
let relay_endpoint = listener.local_addr().unwrap();
let task = tokio::spawn(relay(Arc::new(listener), endpoint, helper));
tokio::time::timeout(Duration::from_secs(10), async {
let mut db = TcpStream::connect(relay_endpoint).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let (mut accepted, _) = unrelated.accept().await.unwrap();
assert_eq!(accepted.read_u8().await.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
task.await.unwrap();
})
.await
.unwrap();
}
#[tokio::test]
async fn a_dead_helper_keeps_its_relay_port_reserved_until_the_route_drops() {
let tunnel = ExternalTunnel::open(&config("once"), TARGET).await.unwrap();
let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, tunnel.port());
tokio::time::timeout(Duration::from_secs(5), async {
let mut db = TcpStream::connect(endpoint).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let mut bytes = [0; EXAMPLE.len()];
db.read_exact(&mut bytes).await.unwrap();
assert_eq!(&bytes, EXAMPLE);
db.read_u16().await.unwrap();
drop(db);
while !tunnel.is_closed() {
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.unwrap();
assert!(std::net::TcpListener::bind(endpoint).is_err());
}
#[test]
fn only_credential_free_proxy_addresses_reach_the_helper() {
assert!(credential_free_proxy("proxy.example:3128"));
assert!(credential_free_proxy("socks5h://proxy.example:1080"));
assert!(!credential_free_proxy("https://user:[email protected]:3128"));
assert!(!credential_free_proxy("https://proxy.example:3128/?secret=value"));
}
#[test]
fn expands_only_literal_arguments_and_validates_the_target() {
let settings = crate::DbExternalTunnel {
executable: config("echo").executable,
arguments: vec!["--port={localPort}".into(), "{host}:{port}".into(), "a b \"quotes\"".into()],
};
let arguments = helper_arguments(&settings, TARGET, 12345).unwrap();
assert_eq!(arguments, ["--port=12345", "db.example:5432", "a b \"quotes\""]);
assert!(helper_arguments(&settings, ("--some-option", 5432), 12345).is_err());
}
#[test]
fn brackets_an_ipv6_host_port_pair_but_preserves_the_raw_host_argument() {
let settings = crate::DbExternalTunnel {
executable: config("echo").executable,
arguments: vec!["{localPort}".into(), "{host}:{port}".into(), "{host}".into(), "[{host}]:{port}".into()],
};
let arguments = helper_arguments(&settings, ("[2001:db8::a]", 6432), 12345).unwrap();
assert_eq!(arguments, ["12345", "[2001:db8::a]:6432", "2001:db8::a", "[2001:db8::a]:6432"]);
}
@@ -1,161 +0,0 @@
use super::{Helper, io, process};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4};
use std::os::windows::io::{AsRawHandle, AsRawSocket, FromRawHandle, OwnedHandle};
use std::os::windows::process::CommandExt;
use std::process::Command;
use std::sync::Arc;
use tokio::net::TcpSocket;
use windows_sys::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, INVALID_HANDLE_VALUE, NO_ERROR};
use windows_sys::Win32::NetworkManagement::IpHelper::{
GetExtendedTcpTable, MIB_TCP_STATE_ESTAB, MIB_TCP_STATE_LISTEN, MIB_TCP6ROW_OWNER_PID, MIB_TCPROW_OWNER_PID,
TCP_TABLE_OWNER_PID_ALL,
};
use windows_sys::Win32::Networking::WinSock::{
AF_INET, AF_INET6, SO_EXCLUSIVEADDRUSE, SOCKET_ERROR, SOL_SOCKET, WSAGetLastError, setsockopt,
};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
pub(super) fn make_exclusive(socket: &TcpSocket) -> io::Result<()> {
let enabled = 1i32;
// SAFETY: the socket is open and the option value remains valid for this call.
let result = unsafe {
setsockopt(
socket.as_raw_socket() as usize,
SOL_SOCKET,
SO_EXCLUSIVEADDRUSE,
(&raw const enabled).cast(),
size_of::<i32>() as i32,
)
};
if result == SOCKET_ERROR {
// SAFETY: reads the last Winsock error on the calling thread.
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
}
Ok(())
}
pub(super) fn spawn_suspended(mut command: Command) -> io::Result<Helper> {
let mut child = command.creation_flags(CREATE_SUSPENDED | process::CREATE_NO_WINDOW).spawn()?;
let Some(job) = process::Job::for_child(&child) else {
// The child has never executed, so there are no descendants to terminate.
let _ = child.kill();
return Err(io::Error::other("could not contain the external tunnel helper in a Windows job"));
};
let helper = Helper { child: Some(child), job };
resume_initial_thread(helper.child().id())?;
Ok(helper)
}
fn resume_initial_thread(pid: u32) -> io::Result<()> {
// SAFETY: the snapshot handle is owned here, and each enumeration call writes a sized entry.
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snapshot == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let snapshot = OwnedHandle::from_raw_handle(snapshot);
let mut entry = THREADENTRY32 { dwSize: size_of::<THREADENTRY32>() as u32, ..Default::default() };
let mut has_entry = Thread32First(snapshot.as_raw_handle(), &mut entry);
while has_entry != 0 {
if entry.th32OwnerProcessID == pid {
let thread = OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID);
if thread.is_null() {
return Err(io::Error::last_os_error());
}
let thread = OwnedHandle::from_raw_handle(thread);
return match ResumeThread(thread.as_raw_handle()) {
1 => Ok(()),
u32::MAX => Err(io::Error::last_os_error()),
_ => Err(io::Error::other("external tunnel helper was not in its initial suspended state")),
};
}
entry.dwSize = size_of::<THREADENTRY32>() as u32;
has_entry = Thread32Next(snapshot.as_raw_handle(), &mut entry);
}
}
Err(io::Error::other("could not find the external tunnel helper's suspended thread"))
}
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let state = if peer.is_some() { MIB_TCP_STATE_ESTAB as u32 } else { MIB_TCP_STATE_LISTEN as u32 };
let table = tcp_table(u32::from(AF_INET))?;
// SAFETY: this is the AF_INET owner-PID table, whose rows contain only integers.
for row in unsafe { rows::<MIB_TCPROW_OWNER_PID>(&table)? } {
if row.dwState == state
&& v4_address(row.dwLocalAddr, row.dwLocalPort) == local
&& peer.is_none_or(|peer| v4_address(row.dwRemoteAddr, row.dwRemotePort) == peer)
&& helper.job.contains_pid(row.dwOwningPid)
{
return Ok(true);
}
}
let table = tcp_table(u32::from(AF_INET6))?;
// SAFETY: this is the AF_INET6 owner-PID table, whose rows contain only integers.
for row in unsafe { rows::<MIB_TCP6ROW_OWNER_PID>(&table)? } {
if row.dwState == state
&& mapped_address(row.ucLocalAddr, row.dwLocalPort) == Some(local)
&& peer.is_none_or(|peer| mapped_address(row.ucRemoteAddr, row.dwRemotePort) == Some(peer))
&& helper.job.contains_pid(row.dwOwningPid)
{
return Ok(true);
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn v4_address(address: u32, port: u32) -> SocketAddr {
SocketAddrV4::new(Ipv4Addr::from(address.to_ne_bytes()), u16::from_be(port as u16)).into()
}
fn mapped_address(address: [u8; 16], port: u32) -> Option<SocketAddr> {
let address = Ipv6Addr::from(address).to_ipv4_mapped()?;
Some(SocketAddrV4::new(address, u16::from_be(port as u16)).into())
}
fn tcp_table(family: u32) -> io::Result<Vec<u32>> {
const MAX_TABLE: u32 = 8 * 1024 * 1024;
let mut size = 0;
let mut buffer = Vec::<u32>::new();
for _ in 0..3 {
// SAFETY: the buffer has the supplied capacity and u32 alignment for the owner-PID table.
let result = unsafe {
GetExtendedTcpTable(
if buffer.is_empty() { std::ptr::null_mut() } else { buffer.as_mut_ptr().cast() },
&mut size,
0,
family,
TCP_TABLE_OWNER_PID_ALL,
0,
)
};
match result {
NO_ERROR => return Ok(buffer),
ERROR_INSUFFICIENT_BUFFER if size <= MAX_TABLE => {
buffer.resize(size.div_ceil(size_of::<u32>() as u32) as usize, 0);
size = (buffer.len() * size_of::<u32>()) as u32;
}
_ => return Err(io::Error::from_raw_os_error(result as i32)),
}
}
Err(io::Error::other("the TCP socket ownership table did not stabilize"))
}
// `T` must be the matching Windows owner-PID row for this table, with no invalid bit patterns.
unsafe fn rows<T>(table: &[u32]) -> io::Result<&[T]> {
let Some((&count, data)) = table.split_first() else {
return Err(io::Error::other("missing TCP socket ownership table header"));
};
if align_of::<T>() > align_of::<u32>() || count as usize > std::mem::size_of_val(data) / size_of::<T>() {
return Err(io::Error::other("invalid TCP socket ownership table size"));
}
// SAFETY: the caller supplies the matching row layout; alignment and length are checked above.
Ok(unsafe { std::slice::from_raw_parts(data.as_ptr().cast(), count as usize) })
}
+9 -1
View File
@@ -1,7 +1,6 @@
//! A trusted local driver profile is shared by data sources. JDBC URLs and properties
//! can run driver-specific initialization. A project source may connect only with the
//! settings its user last accepted in the dialog; the approval lives outside the project.
use crate::local_settings::persist_local;
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
@@ -31,6 +30,15 @@ pub struct DbJdbcDriver {
pub url_template: String,
}
fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
fn local_jar(jar: &str) -> IdeResult<&Path> {
if jar.contains(if cfg!(windows) { ';' } else { ':' }) {
return Err(IdeError::invalid("A JDBC JAR path contains the system classpath separator"));
+150 -129
View File
@@ -4,12 +4,7 @@
pub mod catalog;
mod clickhouse;
mod external_tunnel;
pub use external_tunnel::stop_external_tunnels_on_exit;
mod jdbc;
mod local_settings;
mod route;
mod tunnel_approval;
pub use jdbc::{DbJdbcDriver, jdbc_driver_classes};
pub mod conn;
pub mod history;
@@ -30,8 +25,8 @@ pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection, DbSnowflake,
DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -257,14 +252,17 @@ pub struct Databases {
/// Connections of one project's data sources, keyed by connection target (see [`split_target`]).
pub struct DbManager {
root: PathBuf,
pools: Mutex<HashMap<String, Arc<route::ConnectionSlot>>>,
routes: route::Routes,
local_external_tunnels: bool,
pools: Mutex<HashMap<String, Arc<Pool>>>,
/// SSH tunnels by data source id, shared by the pools of its databases
/// (closed with the last of them).
tunnels: Mutex<HashMap<String, Arc<Tunnel>>>,
/// Serialises opening tunnels so concurrent connects share one.
tunnel_open: tokio::sync::Mutex<()>,
/// App-wide SSH connections and host-key trust.
ssh: Arc<SshManager>,
saved_passwords: Arc<SecretStore>,
saved_passwords: SecretStore,
/// Directory of the global data sources and their saved passwords ([`DbManager::with_global_sources`]).
global: Option<(PathBuf, Arc<SecretStore>)>,
global: Option<(PathBuf, SecretStore)>,
history: Arc<HistoryStore>,
/// What introspection read of each data source, kept between runs.
catalogs: catalog::CatalogStore,
@@ -423,15 +421,15 @@ impl DbManager {
}
}
Self {
saved_passwords: Arc::new(SecretStore::new(passwords, &root)),
saved_passwords: SecretStore::new(passwords, &root),
global: None,
history,
catalogs,
recorder,
root,
pools: Mutex::default(),
routes: Mutex::default(),
local_external_tunnels: false,
tunnels: Mutex::default(),
tunnel_open: tokio::sync::Mutex::new(()),
ssh,
session_passwords: Mutex::default(),
on_disk: Mutex::default(),
@@ -443,7 +441,7 @@ impl DbManager {
/// Also lists the global data sources stored in `dir` (the app data directory).
pub fn with_global_sources(mut self, dir: PathBuf) -> Self {
let passwords = self.saved_passwords.scoped(&dir);
self.global = Some((dir, Arc::new(passwords)));
self.global = Some((dir, passwords));
self
}
@@ -473,7 +471,7 @@ impl DbManager {
}
}
fn store_of(&self, source: &DataSource) -> &Arc<SecretStore> {
fn store_of(&self, source: &DataSource) -> &SecretStore {
match &self.global {
Some((_, store)) if source.global => store,
_ => &self.saved_passwords,
@@ -513,7 +511,13 @@ impl DbManager {
.find(|s| s.id == id)
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?
.resolved()?;
source.select_database(database);
if let Some(db) = database {
// The configured schema belongs to the configured database.
if source.driver == DbDriver::Snowflake && !source.database.eq_ignore_ascii_case(db) {
source.options.default_schema.clear();
}
source.database = db.to_owned();
}
Ok(source)
}
@@ -694,10 +698,7 @@ impl DbManager {
if !saved {
return None;
}
// The OS may wait for the user to unlock the credential store. A cancelled connection
// must be able to stop waiting without starting its helper when the prompt is answered.
let store = Arc::clone(self.store_of(source));
tokio::task::spawn_blocking(move || store.get(&key)).await.ok().flatten()
self.store_of(source).get(&key)
}
async fn password(&self, source: &DataSource) -> Option<String> {
@@ -735,6 +736,36 @@ impl DbManager {
}
}
/// Opens the SSH tunnel of `source` when it has one, returning the settings to
/// connect with (the tunnel's local end instead of the database host).
/// `shared` reuses (or registers) the data source's tunnel for its pools; Test
/// Connection opens a private one.
async fn endpoint(
&self,
source: &DataSource,
ssh_secret: Option<String>,
shared: bool,
) -> IdeResult<(DataSource, Option<Arc<Tunnel>>)> {
let Some(ssh) = source.ssh.as_ref().filter(|s| s.enabled && tunneled(source.driver)) else {
return Ok((source.clone(), None));
};
let local = |t: &Tunnel| DataSource { host: "127.0.0.1".into(), port: Some(t.port()), ..source.clone() };
let _opening = if shared { Some(self.tunnel_open.lock().await) } else { None };
if shared {
let existing = self.tunnels.lock().get(&source.id).filter(|t| !t.is_closed()).cloned();
if let Some(t) = existing {
return Ok((local(&t), Some(t)));
}
}
let session = self.ssh_session(source, ssh, ssh_secret).await?;
let (target_host, target_port) = tunnel_target(source);
let t = Arc::new(Tunnel::open(session, target_host, target_port).await?);
if shared {
self.tunnels.lock().insert(source.id.clone(), t.clone());
}
Ok((local(&t), Some(t)))
}
/// The SSH session the tunnel of `source` goes through: its shared SSH configuration's, or one
/// opened with the settings typed in the data source.
async fn ssh_session(
@@ -787,35 +818,23 @@ impl DbManager {
source: &DataSource,
password: Option<String>,
ssh_secret: Option<String>,
) -> IdeResult<String> {
if source.external_tunnel.is_some() {
return Err(IdeError::invalid("Review the external tunnel in the local Test Connection dialog"));
}
self.test_connection(source, password, ssh_secret, route::RouteUse::Test).await
}
pub async fn test_external_tunnel(&self, source: &DataSource, password: Option<String>) -> IdeResult<String> {
self.external_config(source)?;
self.test_connection(source, password, None, route::RouteUse::ReviewedExternalTest).await
}
async fn test_connection(
&self,
source: &DataSource,
password: Option<String>,
ssh_secret: Option<String>,
purpose: route::RouteUse,
) -> IdeResult<String> {
let source = &source.resolved()?;
let password = match password {
Some(p) => Some(p),
None => self.password(source).await,
};
let (target, _tunnel) = self.endpoint(source, ssh_secret, purpose).await?;
let (target, tunnel) = self.endpoint(source, ssh_secret, false).await?;
self.restore_sso(source).await;
let connected = self.open_pool(&target, password.as_deref(), true).await;
self.keep_sso(source).await;
let pool = connected.map_err(|e| self.connection_error(e, source))?;
let pool = connected.map_err(|e| {
through_tunnel(
e,
source,
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
)
})?;
if let Pool::Jdbc(p) = &pool {
let version = p.version.clone();
pool.close().await;
@@ -836,8 +855,7 @@ impl DbManager {
_ => pool.rows(version, 1).await,
};
pool.close().await;
let strict =
source.external_tunnel.is_some() || matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let strict = matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let rows = if strict { result? } else { result.unwrap_or_default() };
let v = rows.into_iter().next().and_then(|r| r.into_iter().next().flatten());
Ok(v.unwrap_or_else(|| "Connected".into()))
@@ -863,15 +881,11 @@ impl DbManager {
if source.driver != tool.driver() {
return Err(IdeError::invalid(format!("{} cannot connect to {}", tool.program(), source.name)));
}
// Keep the same route as the connected pool for the entire tool invocation.
let connection = self.connection(id).await?;
let target = connection.target(&source);
self.pool(id).await?;
let password = self.password(&source).await;
let mut prepared = tools::prepare(job, executable, &target, password.as_deref())?;
if source.external_tunnel.is_some() {
// libpq gives PGHOSTADDR precedence over --host when choosing the TCP peer.
prepared.env.push(("PGHOSTADDR".into(), target.host.clone()));
}
// Holding the tunnel keeps it open while the tool runs, even if the tree disconnects.
let (target, _tunnel) = self.endpoint(&source, None, true).await?;
let prepared = tools::prepare(job, executable, &target, password.as_deref())?;
tools::run(executable, &prepared.args, &prepared.env, prepared.input.as_deref(), cancel, on_output).await
}
@@ -897,6 +911,90 @@ impl DbManager {
.ok_or_else(|| IdeError::internal("no server version"))
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
}
/// The pool of target `id`, connecting first if needed.
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
let (source_id, _) = split_target(id);
// A dropped SSH session leaves every pool through it unusable: start over.
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
}
let source = self.source(id)?;
let password = self.password(&source).await;
let (target, tunnel) = self.endpoint(&source, None, true).await?;
self.restore_sso(&source).await;
let connected = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = match connected {
Ok(p) => Arc::new(p),
Err(e) => {
self.drop_unused_tunnel(source_id);
return Err(through_tunnel(
e,
&source,
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
));
}
};
// Another caller may have connected meanwhile; keep theirs.
let kept = self.pools.lock().entry(id.to_owned()).or_insert_with(|| pool.clone()).clone();
if !Arc::ptr_eq(&kept, &pool) {
// Ours lost the race: close it rather than leave its session open on the server.
pool.close().await;
} else if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(kept)
}
/// Closes the tunnel of `source_id` once none of its targets is connected.
fn drop_unused_tunnel(&self, source_id: &str) {
let in_use = self.pools.lock().keys().any(|k| split_target(k).0 == source_id);
if !in_use {
self.tunnels.lock().remove(source_id);
}
}
/// Disconnects target `id` (one database of a data source).
pub async fn disconnect(&self, id: &str) {
// A held connection would keep the pool from closing; manual mode stays on.
let session = self.sessions.lock().get(id).cloned();
if let Some(s) = session {
end_session(&s).await;
}
self.cursors.release_target(id);
let pool = self.pools.lock().remove(id);
if let Some(p) = pool {
p.close().await;
}
self.drop_unused_tunnel(split_target(id).0);
}
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
for t in targets {
self.disconnect(&t).await;
}
self.tunnels.lock().remove(id);
}
/// Creates a database on the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `template`, the database
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
@@ -1767,83 +1865,6 @@ mod tests {
DbManager::new(dir.join("project"), data.join("db-passwords.json"), data.join("db-history.json"), ssh)
}
#[tokio::test]
async fn external_tunnel_approval_binds_the_command_destination_and_local_scope() {
let tmp = tempfile::tempdir().unwrap();
#[cfg(windows)]
let name = "forward.exe";
#[cfg(not(windows))]
let name = "forward";
let program = tmp.path().join(name);
std::fs::write(&program, b"fixture version 1").unwrap();
let app = tmp.path().join("app");
let desktop = |root: &Path| manager(root).with_global_sources(app.clone()).with_local_external_tunnels(true);
let db = desktop(tmp.path());
let other = desktop(&tmp.path().join("other"));
let mut source = DataSource {
id: "pg".into(),
name: "Example PostgreSQL".into(),
driver: DbDriver::Postgres,
host: "db.example".into(),
external_tunnel: Some(DbExternalTunnel {
executable: program.to_str().unwrap().into(),
arguments: vec!["--listen={localPort}".into(), "{host}:{port}".into()],
}),
..Default::default()
};
assert!(db.check_external_approval(&source).await.is_err());
db.approve_external_tunnel(&source).await.unwrap();
db.save_sources(vec![source.clone()]).await.unwrap();
db.check_external_approval(&db.source("pg").unwrap()).await.unwrap();
db.check_external_approval(&source).await.unwrap();
assert!(other.check_external_approval(&source).await.is_err());
for changed in [
DataSource { host: "other.example".into(), ..source.clone() },
DataSource { user: "other".into(), ..source.clone() },
DataSource { ssl: DbSslMode::Require, ..source.clone() },
] {
assert!(db.check_external_approval(&changed).await.is_err());
}
let mut changed = source.clone();
changed.external_tunnel.as_mut().unwrap().arguments.push("--changed".into());
assert!(db.check_external_approval(&changed).await.is_err());
source.global = true;
assert!(db.check_external_approval(&source).await.is_err());
db.approve_external_tunnel(&source).await.unwrap();
db.save_sources(vec![source.clone()]).await.unwrap();
db.check_external_approval(&db.source("pg").unwrap()).await.unwrap();
other.check_external_approval(&source).await.unwrap();
std::fs::write(&program, b"fixture version 2").unwrap();
assert!(db.check_external_approval(&source).await.is_err());
}
#[tokio::test]
async fn external_tunnel_rejects_incompatible_modes_and_implicit_test() {
let tmp = tempfile::tempdir().unwrap();
let source = DataSource {
id: "pg".into(),
driver: DbDriver::Postgres,
external_tunnel: Some(DbExternalTunnel {
executable: std::env::current_exe().unwrap().to_str().unwrap().into(),
arguments: vec!["{localPort}".into()],
}),
..Default::default()
};
let remote = manager(tmp.path()).with_global_sources(tmp.path().join("app"));
assert!(remote.test_external_tunnel(&source, None).await.is_err());
let db = remote.with_local_external_tunnels(true);
assert!(db.test(&source, None, None).await.is_err());
for bad in [
DataSource { ssl: DbSslMode::VerifyFull, ..source.clone() },
DataSource { url_only: true, ..source.clone() },
DataSource { plugin_owner: Some("sample".into()), ..source.clone() },
DataSource { driver: DbDriver::Jdbc, ..source.clone() },
DataSource { ssh: Some(DbSsh { enabled: true, ..Default::default() }), ..source.clone() },
] {
assert!(db.approve_external_tunnel(&bad).await.is_err());
}
}
#[tokio::test]
async fn saved_passwords_stay_off_disk() {
let tmp = tempfile::tempdir().unwrap();
-11
View File
@@ -1,11 +0,0 @@
use ide_core::{IdeError, IdeResult};
use std::path::Path;
pub(super) fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
-251
View File
@@ -1,251 +0,0 @@
//! A connection target owns its pool and keeps its data source's forwarding route alive.
//! Concurrent opens of sibling databases share a helper, but unrelated sources never wait on it.
use super::*;
use external_tunnel::ExternalTunnel;
use std::sync::Weak;
use tokio::sync::OnceCell;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RouteUse {
Connect,
Test,
ReviewedExternalTest,
}
pub(super) enum Route {
Ssh(Tunnel),
External(ExternalTunnel),
}
impl Route {
fn port(&self) -> u16 {
match self {
Self::Ssh(t) => t.port(),
Self::External(t) => t.port(),
}
}
fn is_closed(&self) -> bool {
match self {
Self::Ssh(t) => t.is_closed(),
Self::External(t) => t.is_closed(),
}
}
}
type RouteSlot = Arc<OnceCell<Route>>;
// The file watcher may observe a source edit after a new caller already read it.
pub(super) struct CachedRoute {
host: String,
port: u16,
ssh: Option<DbSsh>,
helper: Option<DbExternalTunnel>,
slot: Weak<OnceCell<Route>>,
}
impl CachedRoute {
fn matches(&self, source: &DataSource) -> bool {
let (host, port) = tunnel_target(source);
self.host == host && self.port == port && self.ssh == source.ssh && self.helper == source.external_tunnel
}
}
pub(super) type Routes = Mutex<HashMap<String, CachedRoute>>;
#[derive(Clone)]
pub(super) struct Connection {
pub(super) pool: Arc<Pool>,
route: Option<RouteSlot>,
}
impl Connection {
pub(super) fn target(&self, source: &DataSource) -> DataSource {
routed_target(source, self.route.as_ref())
}
fn is_closed(&self) -> bool {
self.pool.is_closed() || self.route.as_ref().and_then(|s| s.get()).is_some_and(Route::is_closed)
}
}
#[derive(Default)]
pub(super) struct ConnectionSlot {
pub(super) value: OnceCell<Connection>,
pub(super) cancel: CancellationToken,
}
fn routed_target(source: &DataSource, slot: Option<&RouteSlot>) -> DataSource {
match slot.and_then(|s| s.get()) {
Some(route) => DataSource { host: "127.0.0.1".into(), port: Some(route.port()), ..source.clone() },
None => source.clone(),
}
}
impl DbManager {
pub(super) async fn endpoint(
&self,
source: &DataSource,
ssh_secret: Option<String>,
purpose: RouteUse,
) -> IdeResult<(DataSource, Option<RouteSlot>)> {
let external = source.external_tunnel.as_ref();
let ssh = source.ssh.as_ref().filter(|ssh| ssh.enabled && tunneled(source.driver));
if external.is_none() && ssh.is_none() {
return Ok((source.clone(), None));
}
if external.is_some() {
match purpose {
RouteUse::Connect => self.check_external_approval(source).await?,
RouteUse::ReviewedExternalTest => {
self.external_config(source)?;
}
RouteUse::Test => {
return Err(IdeError::invalid("Review the external tunnel in the local Test Connection dialog"));
}
}
}
let slot = if purpose == RouteUse::Connect {
let mut routes = self.routes.lock();
if let Some(slot) = routes.get(&source.id).filter(|r| r.matches(source)).and_then(|r| r.slot.upgrade())
&& !slot.get().is_some_and(Route::is_closed)
{
slot
} else {
routes.retain(|_, r| r.slot.strong_count() > 0);
let slot = Arc::new(OnceCell::new());
let (host, port) = tunnel_target(source);
routes.insert(
source.id.clone(),
CachedRoute {
host: host.to_owned(),
port,
ssh: source.ssh.clone(),
helper: source.external_tunnel.clone(),
slot: Arc::downgrade(&slot),
},
);
slot
}
} else {
Arc::new(OnceCell::new())
};
slot.get_or_try_init(|| async {
if let Some(config) = external {
ExternalTunnel::open(config, tunnel_target(source)).await.map(Route::External)
} else {
let ssh = ssh.expect("enabled SSH transport");
let session = self.ssh_session(source, ssh, ssh_secret).await?;
let (host, port) = tunnel_target(source);
Tunnel::open(session, host, port).await.map(Route::Ssh)
}
})
.await?;
Ok((routed_target(source, Some(&slot)), Some(slot)))
}
pub(super) fn connection_error(&self, error: IdeError, source: &DataSource) -> IdeError {
if source.external_tunnel.is_some() && error.kind == ErrorKind::Io {
return IdeError::new(error.kind, format!("{} through the external database tunnel", error.message));
}
let via = source.ssh.as_ref().filter(|s| s.enabled && tunneled(source.driver)).map(|ssh| self.ssh_label(ssh));
through_tunnel(error, source, via.as_deref())
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).and_then(|slot| slot.value.get()).is_some_and(|c| !c.is_closed())
}
pub fn connected(&self) -> Vec<String> {
self.pools
.lock()
.iter()
.filter(|(_, s)| s.value.get().is_some_and(|c| !c.is_closed()))
.map(|(id, _)| id.clone())
.collect()
}
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
Ok(self.connection(id).await?.pool)
}
pub(super) async fn connection(&self, id: &str) -> IdeResult<Connection> {
let (slot, stale) = {
let mut pools = self.pools.lock();
let stale = if pools.get(id).and_then(|s| s.value.get()).is_some_and(Connection::is_closed) {
pools.remove(id)
} else {
None
};
(pools.entry(id.into()).or_default().clone(), stale)
};
if let Some(stale) = stale {
self.close_target(id, stale).await;
}
let result = tokio::select! {
biased;
_ = slot.cancel.cancelled() => Err(IdeError::cancelled()),
result = slot.value.get_or_try_init(|| self.open_connection(id)) => result.cloned(),
};
if result.is_err() {
let mut pools = self.pools.lock();
if Arc::strong_count(&slot) == 2 && pools.get(id).is_some_and(|s| Arc::ptr_eq(s, &slot)) {
pools.remove(id);
}
}
result
}
async fn open_connection(&self, id: &str) -> IdeResult<Connection> {
let (source_id, database) = split_target(id);
let mut source = self.source(source_id)?;
let password = self.password(&source).await;
// The approval belongs to the configured source, including its login database.
// Sibling database selection changes only the driver's target after routing.
let (mut target, route) = self.endpoint(&source, None, RouteUse::Connect).await?;
target.select_database(database);
source.select_database(database);
self.restore_sso(&source).await;
let result = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = Arc::new(result.map_err(|e| self.connection_error(e, &source))?);
if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(Connection { pool, route })
}
async fn close_target(&self, id: &str, slot: Arc<ConnectionSlot>) {
slot.cancel.cancel();
// A held transaction or result cursor keeps the pool from closing.
let session = self.sessions.lock().get(id).cloned();
if let Some(s) = session {
end_session(&s).await;
}
self.cursors.release_target(id);
if let Some(c) = slot.value.get() {
c.pool.close().await;
}
}
pub async fn disconnect(&self, id: &str) {
let slot = self.pools.lock().remove(id);
if let Some(slot) = slot {
self.close_target(id, slot).await;
}
}
pub async fn disconnect_source(&self, id: &str) {
let closing: Vec<_> = {
let mut pools = self.pools.lock();
let mut routes = self.routes.lock();
routes.remove(id);
pools.extract_if(|key, _| split_target(key).0 == id).collect()
};
for (_, slot) in &closing {
slot.cancel.cancel();
}
for (target, slot) in closing {
self.close_target(&target, slot).await;
}
}
}
-21
View File
@@ -296,14 +296,6 @@ pub struct DbSsh {
pub save_secret: bool,
}
/// A foreground program that forwards an IDE-assigned loopback port to the database.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbExternalTunnel {
pub executable: String,
pub arguments: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DataSource {
@@ -326,8 +318,6 @@ pub struct DataSource {
pub read_only: bool,
/// SSH tunnel settings (`None`: never configured; kept but unused when not `enabled`).
pub ssh: Option<DbSsh>,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_tunnel: Option<DbExternalTunnel>,
/// Wire-compatible product preset (`cockroachdb`, `tidb`…; empty: the driver itself).
pub vendor: String,
pub color: Option<DbColor>,
@@ -371,7 +361,6 @@ impl Default for DataSource {
save_password: false,
read_only: false,
ssh: None,
external_tunnel: None,
vendor: String::new(),
color: None,
comment: String::new(),
@@ -512,16 +501,6 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
}
impl DataSource {
pub(crate) fn select_database(&mut self, database: Option<&str>) {
if let Some(db) = database {
// The configured schema belongs to the configured database.
if self.driver == DbDriver::Snowflake && !self.database.eq_ignore_ascii_case(db) {
self.options.default_schema.clear();
}
self.database = db.to_owned();
}
}
pub(crate) fn same_except_visibility(&self, other: &Self) -> bool {
if self == other {
return true;
-103
View File
@@ -1,103 +0,0 @@
//! Only an explicit desktop action can trust a helper. The project file is portable;
//! the authorization belongs to this machine and to the reviewed destination.
use crate::{DataSource, DbDriver, DbExternalTunnel, DbManager, DbSslMode, local_settings::persist_local};
use ide_core::{IdeError, IdeResult};
use std::path::{Path, PathBuf};
impl DbManager {
pub fn with_local_external_tunnels(mut self, enabled: bool) -> Self {
self.local_external_tunnels = enabled;
self
}
pub(super) fn external_config<'a>(&self, source: &'a DataSource) -> IdeResult<&'a DbExternalTunnel> {
if !self.local_external_tunnels {
return Err(IdeError::invalid("External database tunnels require a local desktop project"));
}
if source.driver != DbDriver::Postgres || source.plugin_owner.is_some() || source.url_only {
return Err(IdeError::invalid(
"Use a user-managed PostgreSQL source with host and port for an external tunnel",
));
}
if source.ssh.as_ref().is_some_and(|ssh| ssh.enabled) {
return Err(IdeError::invalid("Choose either SSH or an external tunnel"));
}
if source.ssl == DbSslMode::VerifyFull {
return Err(IdeError::invalid(
"Verify Full needs the remote TLS hostname, which this tunnel transport cannot supply",
));
}
let config =
source.external_tunnel.as_ref().ok_or_else(|| IdeError::invalid("Choose an external tunnel helper"))?;
crate::external_tunnel::ExternalTunnel::validate(config, crate::tunnel_target(source))?;
Ok(config)
}
fn external_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
let config = self.external_config(source)?;
let dir = &self.global.as_ref().ok_or_else(|| IdeError::invalid("Local database settings unavailable"))?.0;
let key = serde_json::to_vec(&((!source.global).then_some(&self.root), &source.id))
.map_err(|e| IdeError::internal(e.to_string()))?;
let settings = serde_json::to_vec(&(
config,
crate::tunnel_target(source),
&source.user,
&source.database,
&source.ssl,
&source.ssl_ca_file,
&source.ssl_cert_file,
&source.ssl_key_file,
source.read_only,
&source.properties,
&source.options,
))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok((
dir.join("database-tunnel-approvals").join(blake3::hash(&key).to_hex().as_str()),
blake3::hash(&settings).to_string(),
))
}
/// Called only after the local connection dialog shows the executable, arguments and destination.
pub async fn approve_external_tunnel(&self, source: &DataSource) -> IdeResult<()> {
let (path, settings) = self.external_approval(source)?;
let program = self.external_config(source)?.executable.clone();
tokio::task::spawn_blocking(move || {
let identity = executable_identity(Path::new(&program))?;
persist_local(&path, format!("{settings}\n{identity}").as_bytes())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
pub(super) async fn check_external_approval(&self, source: &DataSource) -> IdeResult<()> {
let (path, settings) = self.external_approval(source)?;
let program = self.external_config(source)?.executable.clone();
tokio::task::spawn_blocking(move || {
let review = || {
IdeError::invalid("Review the external tunnel in SSH/SSL and save the data source before connecting")
};
let approval = std::fs::read_to_string(path).map_err(|_| review())?;
let (saved, identity) = approval.split_once('\n').ok_or_else(review)?;
// Avoid touching a program named by an unapproved project file.
if saved != settings || identity != executable_identity(Path::new(&program))? {
return Err(review());
}
Ok(())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
}
fn executable_identity(program: &Path) -> IdeResult<String> {
let path = std::fs::canonicalize(program)?;
if !path.is_file() {
return Err(IdeError::invalid("The external tunnel helper must be an executable file"));
}
let mut hash = blake3::Hasher::new();
hash.update(path.as_os_str().as_encoded_bytes());
hash.update(&[0]);
hash.update_reader(std::fs::File::open(path)?)?;
Ok(hash.finalize().to_string())
}
-174
View File
@@ -44,33 +44,6 @@ async fn create_schemas(db: &DbManager) {
}
}
#[tokio::test]
async fn postgres_read_only_is_checked_before_and_after_startup_sql() -> IdeResult<()> {
use ide_db::{DbProperty, Pool};
let Some((host, port, user, password)) = server() else { return Ok(()) };
let mut source =
DataSource { driver: DbDriver::Postgres, host, port: Some(port), user, read_only: true, ..Default::default() };
let pool = Pool::connect(&source, Some(&password), None).await?;
assert_eq!(pool.rows("SHOW transaction_read_only", 1).await?, [[Some("on".into())]]);
pool.close().await;
// Exercise the same server response as a pooler that ignored the startup option.
source.properties.push(DbProperty { name: "default_transaction_read_only".into(), value: "off".into() });
source.options.startup_script = "SELECT 1/0".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("writable connection");
assert!(err.message.contains("did not enable the requested default_transaction_read_only"), "{}", err.message);
source.properties.clear();
source.options.startup_script = "SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("startup script disabled read-only");
assert!(err.message.contains("did not enable the requested default_transaction_read_only"), "{}", err.message);
source.options.startup_script = "BEGIN READ WRITE".into();
let err = Pool::connect(&source, Some(&password), None).await.err().expect("writable startup transaction");
assert!(err.message.contains("writable transaction"), "{}", err.message);
source.options.startup_script = "BEGIN READ ONLY".into();
Pool::connect(&source, Some(&password), None).await?.close().await;
Ok(())
}
#[tokio::test]
async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
@@ -425,150 +398,3 @@ async fn cancelling_a_later_page_stops_its_statement_on_the_server() -> IdeResul
assert_eq!(running, 0, "the cancelled statement still runs on the server");
Ok(())
}
// The same test executable serves as a foreground TCP forwarder for the managed-route test.
#[test]
fn postgres_tunnel_fixture() {
use std::io::{Write, copy};
use std::net::{Ipv4Addr, Shutdown, TcpListener, TcpStream};
let flag = |prefix: &str| std::env::args().find_map(|s| s.strip_prefix(prefix).map(String::from));
let Some(port) = flag("listen=") else { return };
if let Some(file) = flag("waiting=") {
std::fs::write(file, port.as_bytes()).unwrap();
std::thread::sleep(std::time::Duration::from_secs(60));
return;
}
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port.parse::<u16>().unwrap())).unwrap();
let log = flag("start-log=").unwrap();
let mut file = std::fs::OpenOptions::new().append(true).create(true).open(log).unwrap();
writeln!(file, "{port}").unwrap();
let destination = flag("forward=").unwrap();
for stream in listener.incoming() {
let mut client = stream.unwrap();
let dest = destination.clone();
std::thread::spawn(move || {
let mut remote = TcpStream::connect(dest).unwrap();
let mut input = client.try_clone().unwrap();
let mut output = remote.try_clone().unwrap();
std::thread::spawn(move || {
let _ = copy(&mut input, &mut output);
let _ = output.shutdown(Shutdown::Write);
});
let _ = copy(&mut remote, &mut client);
let _ = client.shutdown(Shutdown::Write);
});
}
}
#[tokio::test]
async fn managed_tunnel_shares_the_forwarder_and_closes_it_after_the_last_target() -> IdeResult<()> {
let Some((host, port, user, password)) = server() else { return Ok(()) };
let tmp = tempfile::tempdir()?;
let root = tmp.path();
let log = root.join("starts");
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-secrets")));
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh)
.with_global_sources(root.join("app"))
.with_local_external_tunnels(true);
let source = DataSource {
id: "tunnel".into(),
name: "Tunnel fixture".into(),
driver: DbDriver::Postgres,
host,
port: Some(port),
user,
database: "postgres".into(),
read_only: true,
external_tunnel: Some(ide_db::DbExternalTunnel {
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
arguments: vec![
"--exact".into(),
"postgres_tunnel_fixture".into(),
"--skip".into(),
"listen={localPort}".into(),
"--skip".into(),
"forward={host}:{port}".into(),
"--skip".into(),
format!("start-log={}", log.display()),
],
}),
..Default::default()
};
db.save_sources(vec![source.clone()]).await?;
db.set_password("tunnel", Some(password), false).await?;
assert!(db.pool("tunnel").await.is_err());
assert!(!log.exists());
assert!(db.test_external_tunnel(&source, None).await?.contains("PostgreSQL"));
assert!(db.pool("tunnel").await.is_err(), "Test must not persist launch approval");
db.approve_external_tunnel(&source).await?;
let (a, b) = tokio::try_join!(db.pool("tunnel"), db.pool("tunnel:postgres"))?;
assert_eq!(std::fs::read_to_string(&log)?.lines().count(), 2, "one test helper and one pooled helper");
assert!(db.is_connected("tunnel") && db.is_connected("tunnel:postgres"));
drop((a, b));
db.disconnect("tunnel").await;
let result = db.execute("tunnel:postgres", "SELECT 1", 1, &CancellationToken::new()).await?;
assert_eq!(result.rows, vec![vec![Some("1".to_owned())]]);
db.disconnect_source("tunnel").await;
let ports: Vec<u16> = std::fs::read_to_string(log)?.lines().map(|p| p.parse().unwrap()).collect();
tokio::time::timeout(std::time::Duration::from_secs(5), async {
for port in ports {
while tokio::net::TcpStream::connect(("127.0.0.1", port)).await.is_ok() {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
}
})
.await
.expect("both helpers must stop");
Ok(())
}
#[tokio::test]
async fn external_startup_does_not_block_another_source_and_disconnect_cancels_it() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let dir = tmp.path();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(dir.join("ssh-secrets")));
let db = DbManager::new(dir.into(), dir.join("passwords.json"), dir.join("history.json"), ssh)
.with_global_sources(dir.join("app"))
.with_local_external_tunnels(true);
let waiting = dir.join("starting");
let pending = DataSource {
id: "pending".into(),
name: "Starting helper".into(),
driver: DbDriver::Postgres,
host: "db.example".into(),
external_tunnel: Some(ide_db::DbExternalTunnel {
executable: std::env::current_exe()?.to_string_lossy().into_owned(),
arguments: vec![
"--exact".into(),
"postgres_tunnel_fixture".into(),
"--skip".into(),
"listen={localPort}".into(),
"--skip".into(),
format!("waiting={}", waiting.display()),
],
}),
..Default::default()
};
let file = dir.join("local.db");
std::fs::File::create(&file)?;
let sqlite =
DataSource { id: "local".into(), name: "SQLite fixture".into(), file: Some(file.into()), ..Default::default() };
db.approve_external_tunnel(&pending).await?;
db.save_sources(vec![pending, sqlite]).await?;
let connect = db.pool("pending");
let edit = async {
while !waiting.exists() {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
db.pool("local").await?;
assert!(db.is_connected("local"));
db.disconnect_source("pending").await;
Ok::<_, ide_core::IdeError>(())
};
let (result, edit) = tokio::time::timeout(std::time::Duration::from_secs(8), async { tokio::join!(connect, edit) })
.await
.expect("the pending PostgreSQL helper must not block SQLite or disconnect");
edit?;
assert!(matches!(result, Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled));
Ok(())
}
-1
View File
@@ -68,7 +68,6 @@ specta.workspace = true
specta-typescript.workspace = true
tokio = { workspace = true, features = ["io-std"] }
tracing.workspace = true
url = "2"
tracing-subscriber.workspace = true
parking_lot.workspace = true
dunce.workspace = true
-10
View File
@@ -82,7 +82,6 @@ impl HostConfig {
}
pub struct Host {
local_database_tunnels: bool,
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
@@ -107,7 +106,6 @@ pub struct Host {
syntax: Arc<OnceLock<Arc<Syntax>>>,
pub global_settings: SettingsStore,
pub dependency_versions: Arc<ide_workspace::dependencies::VersionCache>,
pub pypi_names: Arc<ide_workspace::dependencies::pypi::NameCache>,
pub terminals: TerminalManager,
pub processes: ProcessManager,
/// Debug sessions (adapters run on this machine, next to the project).
@@ -167,12 +165,6 @@ impl Host {
windows
}
/// Enables user-approved database helper processes on the local desktop.
pub fn with_local_database_tunnels(mut self) -> Self {
self.local_database_tunnels = true;
self
}
pub fn new(config: HostConfig) -> Self {
let HostConfig {
config_dir,
@@ -193,7 +185,6 @@ impl Host {
ssh.set_configs(global_settings.effective().ssh.configs);
let host = Self {
plugin_host: RwLock::default(),
local_database_tunnels: false,
mcp_executable: Arc::default(),
mcp: Default::default(),
diagnostics,
@@ -216,7 +207,6 @@ impl Host {
dependency_versions: Arc::new(ide_workspace::dependencies::VersionCache::new(
data_dir.join("cache/dependency-versions"),
)),
pypi_names: Arc::new(ide_workspace::dependencies::pypi::NameCache::new(data_dir.join("cache"))),
// Sessions, runs and terminals report to the window that started them (`window_sink`).
terminals: TerminalManager::new(),
processes: ProcessManager::new(),
-1
View File
@@ -870,7 +870,6 @@ async fn occurrences(
max_matches: 0,
context,
include_excluded: false,
skip_large_files: false,
};
let host = call.host();
let request = crate::mcp::tool::request_id();
-1
View File
@@ -650,7 +650,6 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
max_matches,
context: Default::default(),
include_excluded: call.flag("includeExcluded", false)?,
skip_large_files: false,
};
if is_regex && let Err(e) = ide_search::match_ranges("", &query) {
return Err(IdeError::invalid(format!("Invalid regex pattern: {pattern} ({})", e.message)));
+43 -25
View File
@@ -1,6 +1,6 @@
//! Agents tool window: coding agent tasks of the project (over ACP). In a remote
//! window they run on the host, next to the project they work on.
use super::{Channel, blocking, blocking_value};
use super::Channel;
use crate::Host;
use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
@@ -63,7 +63,9 @@ pub async fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentPr
pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<ide_agent::hermes::HermesProfile>> {
host.require_trust(window)?;
let root = ide_agent::hermes::root(dirs::home_dir().as_deref());
blocking_value(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default()).await
tokio::task::spawn_blocking(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default())
.await
.map_err(join_err)
}
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
@@ -124,15 +126,20 @@ pub(crate) fn registry_paths(host: &Host) -> RegistryPaths {
RegistryPaths::new(&host.config_dir, &host.local_data_dir)
}
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
/// Agents of the ACP Registry this machine can run, with what is installed; the list
/// saved earlier when the registry is unreachable. Cancel with `cancel_request(request)`.
#[command(trust = always)]
pub async fn agent_registry_list(host: &Host, request: RequestId) -> IdeResult<AgentRegistry> {
let paths = registry_paths(host);
let cancel = host.begin_request(request);
let result = blocking(move || ide_agent::registry::list(&paths, &cancel)).await;
let result =
tokio::task::spawn_blocking(move || ide_agent::registry::list(&paths, &cancel)).await.map_err(join_err);
host.end_request(request);
let mut registry = result?;
let mut registry = result??;
let installing = installing();
for agent in &mut registry.agents {
agent.installing = installing.contains(&agent.id);
@@ -197,7 +204,7 @@ pub async fn agent_registry_install(
});
}
};
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
let _installing = installing;
let _cancel = ide_core::task::on_cancel(task, {
let cancel = cancel.clone();
@@ -216,9 +223,10 @@ pub async fn agent_registry_install(
report(None, Some(1.0), true);
result
})
.await;
.await
.map_err(join_err);
host.end_request(request);
result?;
result??;
for project in host.projects() {
project.agents.reload_providers();
}
@@ -229,7 +237,7 @@ pub async fn agent_registry_install(
#[command(trust = always)]
pub async fn agent_registry_remove(host: &Host, id: String) -> IdeResult<()> {
let paths = registry_paths(host);
blocking(move || ide_agent::registry::remove(&paths, &id)).await?;
tokio::task::spawn_blocking(move || ide_agent::registry::remove(&paths, &id)).await.map_err(join_err)??;
for project in host.projects() {
project.agents.reload_providers();
}
@@ -265,7 +273,7 @@ pub async fn agent_entries(
pub async fn agent_external_sessions(host: &Host, window: &str) -> IdeResult<Vec<ExternalSession>> {
// Reads transcripts from disk on the blocking pool.
let agents = host.project(window)?.agents.clone();
blocking_value(move || agents.external_sessions()).await
tokio::task::spawn_blocking(move || agents.external_sessions()).await.map_err(join_err)
}
/// Imports an external session as a task: its first turn loads and replays it.
@@ -278,7 +286,7 @@ pub async fn agent_import_session(
) -> IdeResult<AgentTask> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
blocking(move || agents.import_session(&provider, &session_id)).await
tokio::task::spawn_blocking(move || agents.import_session(&provider, &session_id)).await.map_err(join_err)?
}
#[command(trust = trusted)]
@@ -400,13 +408,14 @@ async fn cli_update(
let project = host.project(window)?;
let installing = offer.as_ref().map(|_| Installing::begin(&provider)).transpose()?;
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
let _installing = installing;
project.agents.cli_update(&provider, offer.as_ref(), &cancel)
})
.await;
.await
.map_err(join_err);
host.end_request(request);
result
result?
}
/// What the agent reports about itself when it starts (no session: no MCP servers, hooks
@@ -809,7 +818,11 @@ pub fn agent_mcp_import(host: &Host, window: &str) -> IdeResult<Vec<McpServer>>
pub async fn agent_mcp_discover_sources(host: &Host, window: &str) -> IdeResult<Vec<McpExternalSource>> {
let project_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = dirs::home_dir();
blocking_value(move || ide_agent::mcp::discover_external_sources(home.as_deref(), project_root.as_deref())).await
tokio::task::spawn_blocking(move || {
ide_agent::mcp::discover_external_sources(home.as_deref(), project_root.as_deref())
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
}
/// Imports selected servers from discovered external MCP configuration files into User or Workspace scope.
@@ -1048,7 +1061,7 @@ pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<Agent
let project = host.project(window).ok().filter(|p| !p.light);
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
blocking(move || {
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
@@ -1062,6 +1075,7 @@ pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<Agent
))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
@@ -1125,13 +1139,14 @@ pub async fn agent_skills_browse(
) -> IdeResult<RemoteSkillBrowseResult> {
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::browse_skills(&fetcher, &source, &cancel)
})
.await;
.await
.map_err(join_err);
host.end_request(request);
res
res?
}
/// Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation.
@@ -1149,7 +1164,7 @@ pub async fn agent_skills_preview(
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = dirs::home_dir();
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::preview_skill(
&fetcher,
@@ -1160,9 +1175,10 @@ pub async fn agent_skills_preview(
&cancel,
)
})
.await;
.await
.map_err(join_err);
host.end_request(request);
res
res?
}
/// Installs the selected skill subtree into `~/.agents/skills` (User) or `<workspace>/.agents/skills` (Workspace).
@@ -1183,7 +1199,7 @@ pub async fn agent_skills_install(
let search_path = ide_core::tool_path::search_path();
let install_home = home.clone();
let install_ws = ws_root.clone();
let res = blocking(move || {
let res = tokio::task::spawn_blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::skill_installer::install_skill(
&fetcher,
@@ -1193,9 +1209,10 @@ pub async fn agent_skills_install(
&cancel,
)
})
.await;
.await
.map_err(join_err);
host.end_request(request);
res?;
res??;
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
for p in host.projects() {
@@ -1204,7 +1221,7 @@ pub async fn agent_skills_install(
}
let policy = host_skills_policy(host, project.as_deref());
blocking(move || {
tokio::task::spawn_blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
@@ -1218,6 +1235,7 @@ pub async fn agent_skills_install(
))
})
.await
.map_err(join_err)?
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
+1 -1
View File
@@ -8,7 +8,7 @@ use crate::Project;
use crate::ops::Channel;
use ide_command::command;
use super::blocking;
use super::doc::blocking;
use ide_analysis::{
DuplicateOptions, DuplicatesReport, SourceFile, StructuralFile, StructuralQuery, StructuralSummary,
};
+49 -129
View File
@@ -3,7 +3,6 @@
pub(super) mod workspace;
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
use super::{blocking, blocking_value};
use crate::ops::Channel;
use crate::{Host, Project};
use ide_command::command;
@@ -23,6 +22,10 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
fn join_err(e: tokio::task::JoinError) -> IdeError {
IdeError::internal(e.to_string())
}
/// POM gutters in several editors refresh together. A very short cache lets those
/// requests share one reactor scan without serving a stale module list after edits settle.
const MAVEN_MODULE_CACHE_TTL: Duration = Duration::from_millis(250);
@@ -197,7 +200,7 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
host.require_trust(window)?;
let project = host.project(window)?;
let config = host.config_dir.clone();
blocking(move || workspace::load_project(&project, &config)).await
tokio::task::spawn_blocking(move || workspace::load_project(&project, &config)).await.map_err(join_err)?
}
fn linked_gradle_paths(
@@ -250,7 +253,7 @@ fn linked_gradle_paths(
async fn set_gradle_projects(host: &Host, window: &str, paths: Vec<String>, link: bool) -> IdeResult<BuildModel> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || {
tokio::task::spawn_blocking(move || {
if ide_workspace::workspace::Workspace::load(&project.root)?.is_some() {
return Err(IdeError::invalid("Open a workspace member as a project to link Gradle builds"));
}
@@ -266,6 +269,7 @@ async fn set_gradle_projects(host: &Host, window: &str, paths: Vec<String>, link
Ok::<BuildModel, IdeError>(load(&project.root, &project.build_cache_dir(), &settings))
})
.await
.map_err(join_err)?
}
#[command(trust = trusted)]
@@ -331,7 +335,7 @@ pub async fn build_sync(
let bridge_profiles = profiles.clone();
let p = project.clone();
let config = host.config_dir.clone();
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
let scopes = workspace::scopes(&p, &config)?;
let selected: Vec<_> =
scopes.iter().filter(|scope| workspace::selected(scope, &p.root, tool, build_dir.as_deref())).collect();
@@ -412,9 +416,10 @@ pub async fn build_sync(
};
Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots))
})
.await;
.await
.map_err(join_err);
let result = async {
let (mut model, reconfigure, updates, snapshots) = result?;
let (mut model, reconfigure, updates, snapshots) = result??;
if completion_token.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -440,7 +445,7 @@ pub async fn build_sync(
// JDT LS resolves the binary jars while importing Maven projects.
update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await;
let cancel = completion_token.clone();
let (updated, refreshed) = blocking_value(move || {
let (updated, refreshed) = tokio::task::spawn_blocking(move || {
let mut refreshed = Vec::new();
if let Some(maven) = &model.maven {
for batch in snapshots {
@@ -459,7 +464,8 @@ pub async fn build_sync(
}
(model, refreshed)
})
.await?;
.await
.map_err(join_err)?;
model = updated;
tokio::spawn(async move {
refresh_library_archives(&lsp, &documents, &updates, refreshed).await;
@@ -578,11 +584,12 @@ pub async fn gradle_published_catalog(
coordinates: String,
) -> IdeResult<Option<ide_core::IpcPath>> {
let project = host.project(window)?;
blocking_value(move || {
tokio::task::spawn_blocking(move || {
ide_sdk::libraries::published_version_catalog(&project.root, &project.settings.effective(), &coordinates)
.map(Into::into)
})
.await
.map_err(join_err)
}
/// The resolved dependency tree of a Gradle project for one configuration (Dependency Analyzer).
@@ -601,7 +608,7 @@ pub async fn gradle_dependencies(
let project = host.project(window)?;
let config = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
let scopes = workspace::scopes(&project, &config)?;
let scope = scopes
.iter()
@@ -629,9 +636,10 @@ pub async fn gradle_dependencies(
}
Ok(report.dependencies)
})
.await;
.await
.map_err(join_err);
host.end_request(request);
result
result?
}
/// What the Dependency Analyzer has of the builds of `project` at `root` (the project, or one
@@ -678,11 +686,12 @@ pub async fn maven_dependency_declaration(
) -> IdeResult<Location> {
let project = host.project(window)?;
let config = host.config_dir.clone();
blocking(move || {
tokio::task::spawn_blocking(move || {
let (path, _, range) = declaring_pom(&project, &config, &pom, &dependency)?;
Ok(Location::file(path, range))
})
.await
.map_err(join_err)?
}
/// The go-to-declaration target at `pos` of a Maven POM: the definition of the
@@ -696,7 +705,7 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
// without a managed version the target is the artifact's own POM (a project module's, or the
// local repository's). `None` when nothing resolvable is under the caret.
let project = host.project(window)?;
blocking(move || {
tokio::task::spawn_blocking(move || {
let given = Path::new(&pom);
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
let text = project.text_of(&path)?;
@@ -707,6 +716,7 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
Ok(ide_build::maven::goto_declaration_with(&text, &path, pos, options, modules))
})
.await
.map_err(join_err)?
}
/// Gutter targets of the unversioned dependencies and plugins in a Maven POM:
@@ -721,7 +731,7 @@ pub async fn maven_managed_declarations(
) -> IdeResult<Vec<PomManagedDeclaration>> {
let project = host.project(window)?;
let cancel = host.begin_project_read_request(window, request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -743,7 +753,10 @@ pub async fn maven_managed_declarations(
})
.await;
host.end_request(request);
result
match result {
Ok(result) => result,
Err(error) => Err(join_err(error)),
}
}
/// How long completion waits for Maven Central before answering from the local repository.
@@ -842,7 +855,7 @@ pub async fn maven_exclude_dependency(
) -> IdeResult<Location> {
let project = host.project(window)?;
let config = host.config_dir.clone();
blocking(move || {
tokio::task::spawn_blocking(move || {
let (path, text, range) = declaring_pom(&project, &config, &pom, &dependency)?;
match ide_build::pom_edit::add_exclusion(&text, &dependency, &exclusion) {
Some(Exclusion::Edit(edit)) => {
@@ -858,6 +871,7 @@ pub async fn maven_exclude_dependency(
Ok(Location::file(path, range))
})
.await
.map_err(join_err)?
}
/// Build / Rebuild / Build Artifacts of a Java project without a build tool, from its
@@ -975,7 +989,7 @@ pub async fn build_run(
let config_dir = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let launch_project = project.clone();
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
// Fast path (#2476): an unchanged single-project Maven build skips
// Maven entirely. Previous diagnostics stay: nothing changed, so they
// are still accurate.
@@ -1097,9 +1111,10 @@ pub async fn build_run(
}
Ok::<_, IdeError>(result)
})
.await;
.await
.map_err(join_err);
host.end_request(request);
let outcome = result?;
let outcome = result??;
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
// folders the build wrote are attached. An up-to-date build skips Maven and
// still needs this: the classes can already be on disk.
@@ -1109,39 +1124,11 @@ pub async fn build_run(
Ok(outcome)
}
fn plan_compile_file(
root: &Path,
cache: &Path,
settings: &Settings,
detected: &[ide_workspace::roots::SourceFolder],
file: &Path,
cancel: &CancellationToken,
on_progress: &dyn Fn(String),
) -> IdeResult<compile::BuildPlan> {
if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) {
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
}
if !file.is_file() {
return Err(IdeError::not_found("no Java source found for single-file compilation"));
}
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let model = with_profiles(load(root, cache, settings), cache);
if compile::single_file_target(root, &model, file).is_ok() {
on_progress(format!("Resolving classpath for {name}…"));
return compile::compile_file_plan_cancellable(root, &model, file, cancel);
}
if compile::has_gradle_file_target(root, &model, file) {
on_progress(format!("Resolving classpath for {name}…"));
return compile::gradle_compile_file_plan(root, &model, file, cache, cancel);
}
let (ps, roots, jdk) = structure_inputs(root, settings, detected);
compile::structure_compile_file_plan(root, &ps, &roots, jdk.as_ref(), &settings.languages.java.language_level, file)
}
/// Build › Recompile: compiles one Java source file with `javac`, streaming the
/// console and messages on `on_event`; cancellable with `cancel_request(request)`.
/// Diagnostics of `clear` (the files of the previous build) are cleared first;
/// the new messages are published as `build` diagnostics.
/// Build › Compile File: compiles one Java source of a linked Maven module with
/// `javac`, streaming the console and messages on `on_event`; cancellable with
/// `cancel_request(request)`. Diagnostics of `clear` (the files of the previous
/// build) are cleared first; the new messages are published as `build`
/// diagnostics.
#[command(trust = trusted)]
pub async fn build_compile_file(
host: &Host,
@@ -1153,21 +1140,10 @@ pub async fn build_compile_file(
) -> IdeResult<BuildResult> {
host.require_trust(window)?;
let project = host.project(window)?;
let file = ide_core::project_roots::resolve(&project.root, &file);
let scope = {
let (project, file) = (project.clone(), file.clone());
blocking(move || workspace::scope_for(&project, &file)).await?
};
let scope_root = scope.root.clone();
let detected = if scope.root == project.root {
project.detected_roots.read().clone()
} else {
let root = scope.root.clone();
blocking_value(move || ide_workspace::roots::detect(&root)).await?
};
let sink = project.sink.clone();
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
let settings = project.settings.effective();
let token = host.begin_project_request(window, request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.into(),
@@ -1175,11 +1151,8 @@ pub async fn build_compile_file(
items: Vec::new(),
});
}
let plan =
plan_compile_file(&scope.root, &scope.cache, &scope.settings, &detected, &file, &token, &|message| {
let _ = on_event.send(BuildEvent::Progress { message, fraction: None });
})?;
let result = compile::run(&scope.root, &plan, &token, &|e| {
let plan = compile::compile_file_plan(&root, &with_profiles(load(&root, &cache, &settings), &cache), &file)?;
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
})?;
for (path, items) in compile::diagnostics(&result.messages) {
@@ -1187,11 +1160,12 @@ pub async fn build_compile_file(
}
Ok::<_, IdeError>(result)
})
.await;
.await
.map_err(join_err);
host.end_request(request);
let outcome = result?;
let outcome = result??;
if outcome.system == ide_build::compile::BuildSystem::Maven {
project.lsp.sync_maven_generated_sources(&scope_root).await;
project.lsp.sync_maven_generated_sources(&project.root).await;
}
Ok(outcome)
}
@@ -1416,60 +1390,6 @@ mod build_tool_settings_tests {
assert_eq!(model.env["JAVA_HOME"], root.join("jdk21").to_string_lossy());
assert_eq!(model.env["GRADLE_USER_HOME"], root.join("user-home").to_string_lossy());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn single_file_plan_falls_back_to_project_structure_and_resolves_workspace_scope() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let plain = base.join("plain");
let java_file = plain.join("src/Main.java");
std::fs::create_dir_all(java_file.parent().unwrap()).unwrap();
std::fs::write(&java_file, "class Main {}").unwrap();
let detected = ide_workspace::roots::detect(&plain);
let plan = plan_compile_file(
&plain,
&base.join("cache"),
&Settings::default(),
&detected,
&java_file,
&ide_core::CancellationToken::new(),
&|_| {},
)
.unwrap();
assert_eq!(plan.system, compile::BuildSystem::Javac);
assert_eq!(plan.title, "Compile Main.java");
let txt = plain.join("notes.txt");
std::fs::write(&txt, "hi").unwrap();
assert!(
plan_compile_file(
&plain,
&base.join("cache"),
&Settings::default(),
&detected,
&txt,
&ide_core::CancellationToken::new(),
&|_| {},
)
.is_err()
);
let host =
Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) });
let member_a = base.join("member-a");
let member_b = base.join("member-b");
for m in [&member_a, &member_b] {
std::fs::create_dir_all(m.join("src")).unwrap();
std::fs::write(m.join("src/App.java"), "class App {}").unwrap();
}
let ws = base.join("ws");
std::fs::create_dir_all(&ws).unwrap();
ide_workspace::workspace::Workspace::save(&ws, "WS", vec![member_a.clone(), member_b.clone()], true).unwrap();
let project = host.open_project("win", &ws).unwrap();
let scope = workspace::scope_for(&project, &member_b.join("src/App.java")).unwrap();
assert_eq!(scope.root, member_b);
host.close_project("win");
}
}
#[cfg(test)]
+1 -1
View File
@@ -2,7 +2,7 @@
use crate::Host;
use ide_command::command;
use crate::ops::blocking;
use crate::ops::doc::blocking;
use ide_core::IdeResult;
use ide_vfs::{ByteRange, FileProbe};
use std::path::PathBuf;
+5 -2
View File
@@ -2,14 +2,17 @@
use crate::Host;
use ide_command::command;
use super::blocking;
use ide_core::{IdeResult, IpcPath};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
use ide_run::RunConfig;
/// Output directories kept per kind (older runs' data is deleted).
pub const KEEP_RUNS: usize = 10;
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// How to run `config` with coverage: the command to launch and where its report will be,
/// or which tool is missing.
#[command(trust = trusted)]
+3 -8
View File
@@ -188,15 +188,10 @@ pub async fn db_finish_transaction(host: &Host, window: &str, id: String, commit
}
#[command(trust = trusted)]
pub async fn db_disconnect(host: &Host, window: &str, id: String, whole_source: Option<bool>) -> IdeResult<()> {
// A source-level Deactivate includes databases still opening in the background.
pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<()> {
// Closes the connection of data source `id`.
let db = host.project(window)?.db.clone();
let (source, database) = ide_db::split_target(&id);
if whole_source == Some(true) && database.is_none() {
db.disconnect_source(source).await;
} else {
db.disconnect(&id).await;
}
db.disconnect(&id).await;
Ok(())
}
-82
View File
@@ -114,12 +114,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
extra["__adapterJavaHome"] = serde_json::json!(runtime.home);
config.extra_json = Some(extra.to_string());
}
if finds_java_sources(&config)
&& let Ok(project) = host.project(window)
{
let roots = host.blocking(move || Ok(java_source_roots(&project))).await?;
config = add_java_source_paths(config, &roots);
}
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
let mut ruby_tools = Vec::new();
if config.adapter == "rdbg" && config.request == "launch" {
@@ -314,46 +308,6 @@ fn start_java_attach_listener(mut config: LaunchConfig, windows: bool) -> Launch
config
}
/// The project's source and test roots, as the IDE detects them (no Maven / Gradle import needed).
fn java_source_roots(project: &crate::project::Project) -> Vec<PathBuf> {
use ide_workspace::roots::RootKind;
project
.roots()
.roots
.iter()
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
.map(|r| project.root.join(&r.path))
.filter(|p| p.is_dir())
.collect()
}
/// Debuggers that look a frame's source up in `sourcePaths` when their own model has no file:
/// java-debug after jdtls (which has not imported a project whose Maven sync failed), and
/// java-analyzer after the module it debugs (whose sibling modules it does not load).
fn finds_java_sources(config: &LaunchConfig) -> bool {
matches!(config.adapter.as_str(), "java-debug" | ide_dap::adapter::JAVA_ANALYZER)
}
/// Without a file for the stopped frame the editor cannot follow the execution point, so Java
/// sessions get every source root of the project. The user's own list wins.
fn add_java_source_paths(mut config: LaunchConfig, roots: &[PathBuf]) -> LaunchConfig {
if !finds_java_sources(&config) || roots.is_empty() {
return config;
}
let mut extra = match config.extra_json.as_deref().map(serde_json::from_str) {
None => serde_json::Map::new(),
Some(Ok(serde_json::Value::Object(extra))) => extra,
Some(_) => return config,
};
if extra.get("sourcePaths").is_some_and(|v| !v.is_null()) {
return config;
}
let paths: Vec<String> = roots.iter().map(|r| r.to_string_lossy().into_owned()).collect();
extra.insert("sourcePaths".into(), paths.into());
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
config
}
/// A JVM launched by java-debug writes what java-debug decodes its output as
/// (see [`ide_core::output_encoding::java_debug_vm_args`]).
fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchConfig {
@@ -717,13 +671,6 @@ pub async fn debug_jvm_memory_classes(
host.debugger.jvm_memory_classes(session).await
}
/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken.
#[command(trust = trusted)]
pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult<JvmThreadsResult> {
host.require_trust(window)?;
host.debugger.jvm_thread_dump(session).await
}
/// Up to `limit` live instances of the class in the stopped JVM.
#[command(trust = trusted)]
pub async fn debug_jvm_memory_instances(
@@ -783,34 +730,6 @@ mod tests {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["vmArgs"].clone()
}
#[test]
fn java_debug_sessions_look_up_sources_in_project_roots() {
let roots = [PathBuf::from("/p/src/main/java"), PathBuf::from("/p/src/test/java")];
let source_paths = |config: &LaunchConfig| {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()["sourcePaths"]
.clone()
};
for adapter in ["java-debug", ide_dap::adapter::JAVA_ANALYZER] {
for request in ["launch", "attach"] {
let config = add_java_source_paths(launch(adapter, request, serde_json::json!({"port": 5005})), &roots);
assert_eq!(source_paths(&config), serde_json::json!(["/p/src/main/java", "/p/src/test/java"]));
}
}
let mut bare = launch("java-debug", "attach", serde_json::json!({}));
bare.extra_json = None;
assert_eq!(
source_paths(&add_java_source_paths(bare, &roots)),
serde_json::json!(["/p/src/main/java", "/p/src/test/java"])
);
let own = launch("java-debug", "launch", serde_json::json!({"sourcePaths": ["/elsewhere"]}));
assert_eq!(source_paths(&add_java_source_paths(own, &roots)), serde_json::json!(["/elsewhere"]));
let other = launch("debugpy", "launch", serde_json::json!({}));
assert_eq!(add_java_source_paths(other.clone(), &roots).extra_json, other.extra_json);
let none = launch("java-debug", "launch", serde_json::json!({}));
assert_eq!(add_java_source_paths(none.clone(), &[]).extra_json, none.extra_json);
}
#[test]
fn java_debug_launches_on_windows_write_utf8() {
let extra =
@@ -948,7 +867,6 @@ ide_command::domain!(
debug_jvm_memory_fields,
debug_jvm_memory_instances,
debug_jvm_memory_referrers,
debug_jvm_thread_dump,
debug_listen_for_jvm,
debug_pause,
debug_redefine_classes,
+1 -26
View File
@@ -330,31 +330,6 @@ pub async fn pypi_package(
result
}
/// PyPI project names containing `query`, best match first, 51 at most (50 are shown). Answers from a cached copy of
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
#[command(trust = outside_restricted)]
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
let names = host.pypi_names.clone();
let cancel = host.begin_project_read_request(window, request);
let result = host
.blocking(move || {
let fetch: pypi::Fetch = std::sync::Arc::new(|cancel: &CancellationToken| {
let search_path = std::env::var_os("PATH").unwrap_or_default();
ide_tools::Http::new(&search_path)?
.https_only()
.accept(pypi::SIMPLE_INDEX_ACCEPT)
.compressed()
.get_text_limited(pypi::SIMPLE_INDEX_URL, Some(256 * 1024 * 1024), cancel)
});
let index = names.index(&cancel, fetch)?;
// One more than shown, so the UI can tell the list was cut.
index.search(&query, 51, &cancel)
})
.await;
host.end_request(request);
result
}
#[cfg(test)]
mod tests {
use super::*;
@@ -481,4 +456,4 @@ mod tests {
}
}
ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package, pypi_search);
ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package);
-20
View File
@@ -214,25 +214,6 @@ pub async fn deploy_test_connection(
host.remote.test_connection_with(&connection, &path, password).await
}
#[command(trust = trusted)]
pub async fn remote_upload_into(
window: &str,
host: &Host,
connection: FsConnection,
paths: Vec<IpcPath>,
target: String,
replace: bool,
request: RequestId,
) -> IdeResult<TransferReport> {
let project = host.project(window)?;
let token = host.begin_request(request);
let (mut report, done) = progress(project.sink.clone(), "Uploading", token.clone());
let result = host.remote.upload_into(&connection, &local(paths), &target, replace, &token, &mut report).await;
done();
host.end_request(request);
result
}
ide_command::domain!(
deploy:
deploy_compare,
@@ -246,7 +227,6 @@ ide_command::domain!(
deploy_upload,
remote_delete,
remote_download_into,
remote_upload_into,
remote_list,
remote_mkdir,
remote_of,
-1
View File
@@ -1,4 +1,3 @@
use super::blocking;
use crate::Host;
use ide_command::command;
use ide_core::{ChangeSet, DocId, IdeResult};
+7 -2
View File
@@ -1,12 +1,17 @@
use crate::Host;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range, TextEdit};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
use std::path::PathBuf;
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool,
/// keeping it off the main thread and the async runtime's workers.
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
#[command(trust = always)]
+1 -1
View File
@@ -6,7 +6,7 @@ use ide_core::IdeResult;
use ide_workspace::DirectoryHistory;
use std::path::PathBuf;
use super::blocking;
use super::doc::blocking;
/// Show History on a folder: snapshots of the files under it (deleted ones included) and labels.
#[command(trust = always)]
+1 -21
View File
@@ -1,4 +1,4 @@
use super::blocking;
use super::doc::blocking;
use crate::Host;
use crate::plugins::{ProviderKind, editor_providers_for as editor_providers};
use ide_command::command;
@@ -595,25 +595,6 @@ pub async fn plugin_line_markers(
.collect())
}
/// Where other files import the document's file (Find Usages on a file, a Vue component's
/// usages). Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_file_references(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
) -> IdeResult<Vec<Location>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.file_references(doc, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
result
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
@@ -3216,7 +3197,6 @@ ide_command::domain!(
lsp_hierarchy_refactor,
lsp_hover,
lsp_implementation_locations,
lsp_file_references,
lsp_implementations,
lsp_inlay_hints,
lsp_inline_completion,
+1 -1
View File
@@ -4,7 +4,7 @@
//! poms the nearest pom declares itself are followed from there; a parent outside
//! that walk that no pom declares is not.
use super::blocking;
use super::doc::blocking;
use crate::Host;
use ide_build::maven;
use ide_core::{DocId, Location, Pos};
+2 -103
View File
@@ -39,7 +39,6 @@ pub mod ssh;
pub mod stream_trace;
pub mod syntax;
pub mod term;
pub mod thread_dump;
pub mod tools;
pub mod vcs;
pub mod web;
@@ -119,115 +118,15 @@ ide_command::domains!(
stream_trace: crate::ops::stream_trace,
syntax: crate::ops::syntax,
term: crate::ops::term,
thread_dump: crate::ops::thread_dump,
tools: crate::ops::tools,
vcs: crate::ops::vcs,
vcs_commands: crate::ops::vcs::commands,
web: crate::ops::web,
);
/// A blocking task that panicked or was cancelled, as the error a command returns.
pub(crate) fn join_error(e: tokio::task::JoinError) -> IdeError {
IdeError::internal(e.to_string())
}
/// Runs blocking work (disk I/O, parsing, large copies) on the ambient runtime's blocking
/// pool, keeping it off the main thread and the async runtime's workers.
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(join_error)?
}
/// [`blocking`] for work that cannot fail: only a panic or cancellation is an error.
pub(crate) async fn blocking_value<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(join_error)
}
impl Host {
/// [`blocking`] on this host's runtime instead of the ambient one.
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool.
pub async fn blocking<T: Send + 'static>(&self, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
self.runtime.spawn_blocking(f).await.map_err(join_error)?
}
}
#[cfg(test)]
mod blocking_tests {
use super::{blocking, blocking_value};
use crate::{Host, HostConfig};
use ide_core::error::ErrorKind;
use ide_core::{IdeError, IdeResult};
use std::sync::Arc;
fn runtime(name: &str) -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread().worker_threads(1).thread_name(name).enable_all().build().unwrap()
}
fn thread_name() -> String {
std::thread::current().name().unwrap_or_default().to_owned()
}
fn assert_panic(error: &IdeError) {
assert_eq!(error.kind, ErrorKind::Internal);
assert!(error.data.is_none());
// tokio's JoinError text: `task <id> panicked with message "boom"` (the id varies).
assert!(error.message.starts_with("task "), "{}", error.message);
assert!(error.message.ends_with(" panicked with message \"boom\""), "{}", error.message);
}
fn host_on(handle: tokio::runtime::Handle, base: &std::path::Path) -> Host {
Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
owner: |w| w,
runtime: handle,
project_environment: false,
})
}
#[test]
fn blocking_returns_the_value_and_passes_the_closure_error_through() {
runtime("ambient").block_on(async {
assert_eq!(blocking(|| Ok(7)).await.unwrap(), 7);
let error = blocking::<()>(|| Err(IdeError::invalid("nope"))).await.unwrap_err();
assert_eq!((error.kind, error.message.as_str()), (ErrorKind::InvalidInput, "nope"));
});
}
#[test]
fn blocking_maps_a_panic_to_an_internal_error() {
runtime("ambient").block_on(async {
assert_panic(&blocking::<()>(|| panic!("boom")).await.unwrap_err());
});
}
#[test]
fn blocking_runs_on_the_ambient_runtime() {
let name = runtime("ambient").block_on(async { blocking(|| Ok(thread_name())).await.unwrap() });
assert_eq!(name, "ambient");
}
#[test]
fn blocking_value_returns_the_value_and_maps_a_panic() {
runtime("ambient").block_on(async {
assert_eq!(blocking_value(thread_name).await.unwrap(), "ambient");
assert_panic(&blocking_value::<()>(|| panic!("boom")).await.unwrap_err());
});
}
#[test]
fn host_blocking_runs_on_the_hosts_runtime_not_the_ambient_one() {
let (ambient, hosts) = (runtime("ambient"), runtime("hosts"));
let temp = tempfile::tempdir().unwrap();
let host = host_on(hosts.handle().clone(), temp.path());
ambient.block_on(async {
assert_eq!(host.blocking(|| Ok(thread_name())).await.unwrap(), "hosts");
assert_eq!(host.blocking(|| IdeResult::Ok(7)).await.unwrap(), 7);
let error = host.blocking::<()>(|| Err(IdeError::invalid("nope"))).await.unwrap_err();
assert_eq!((error.kind, error.message.as_str()), (ErrorKind::InvalidInput, "nope"));
assert_panic(&host.blocking::<()>(|| panic!("boom")).await.unwrap_err());
});
self.runtime.spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use super::blocking;
use super::doc::blocking;
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
};
+1 -1
View File
@@ -12,7 +12,7 @@ use ide_workspace::{FileMove, UndoOutcome};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use super::blocking;
use super::doc::blocking;
fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
+4 -4
View File
@@ -13,7 +13,7 @@ use std::time::Duration;
pub async fn run_configs(host: &Arc<Host>, window: &str) -> IdeResult<Vec<RunConfig>> {
// Detection reads build files (and Spring Boot sources): off the command thread.
let (host, window) = (host.clone(), window.to_owned());
super::blocking(move || configs(&host, &window)).await
super::doc::blocking(move || configs(&host, &window)).await
}
#[command(trust = trusted)]
@@ -25,7 +25,7 @@ pub async fn run_save_configs(
) -> IdeResult<()> {
let (host, window) = (host.clone(), window.to_owned());
let removed = removed_detected_ids.unwrap_or_default();
super::blocking(move || save_configs(&host, &window, &configs, &removed)).await
super::doc::blocking(move || save_configs(&host, &window, &configs, &removed)).await
}
/// Detected configs followed by user-defined ones (user ids win on conflict).
@@ -263,7 +263,7 @@ fn settings_only(
#[command(trust = trusted)]
pub async fn run_without_derived(host: &Arc<Host>, window: &str, configs: Vec<RunConfig>) -> IdeResult<Vec<RunConfig>> {
let (host, window) = (host.clone(), window.to_owned());
super::blocking(move || without_derived(&host, &window, configs)).await
super::doc::blocking(move || without_derived(&host, &window, configs)).await
}
/// Without what settings derived (toolchain commands, Maven options, `JAVA_HOME`…), so they
@@ -287,7 +287,7 @@ fn without_derived(host: &Host, window: &str, configs: Vec<RunConfig>) -> IdeRes
#[command(trust = trusted)]
pub async fn run_apply_settings(host: &Arc<Host>, window: &str, configs: Vec<RunConfig>) -> IdeResult<Vec<RunConfig>> {
let (host, window) = (host.clone(), window.to_owned());
super::blocking(move || apply_settings(&host, &window, configs)).await
super::doc::blocking(move || apply_settings(&host, &window, configs)).await
}
/// Today's settings applied, as [`configs`] lists the others.
+7 -17
View File
@@ -100,20 +100,20 @@ pub async fn run_application_publish(
#[command(trust = trusted)]
pub async fn run_templates(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
let root = host.project(window)?.root.clone();
crate::ops::blocking(move || ide_run::load_templates(&root)).await
crate::ops::doc::blocking(move || ide_run::load_templates(&root)).await
}
#[command(trust = trusted)]
pub async fn run_save_templates(host: &Host, window: &str, templates: Vec<RunConfig>) -> IdeResult<()> {
let root = host.project(window)?.root.clone();
crate::ops::blocking(move || ide_run::save_templates(&root, &templates)).await
crate::ops::doc::blocking(move || ide_run::save_templates(&root, &templates)).await
}
/// Project files run configurations can be imported from (`.vscode/launch.json`).
#[command(trust = trusted)]
pub async fn run_import_sources(host: &Host, window: &str) -> IdeResult<Vec<RunImportSource>> {
let root = host.project(window)?.root.clone();
crate::ops::blocking(move || Ok(ide_run::import::available(&root))).await
crate::ops::doc::blocking(move || Ok(ide_run::import::available(&root))).await
}
/// Configurations read from `source`, not saved; names already in `existing` are skipped.
@@ -127,7 +127,7 @@ pub async fn run_import_configs(
// `existing`: the configurations being edited.
host.require_trust(window)?;
let root = host.project(window)?.root.clone();
crate::ops::blocking(move || ide_run::import_configs(&root, source, &existing)).await
crate::ops::doc::blocking(move || ide_run::import_configs(&root, source, &existing)).await
}
/// The environment runs inherit when "Include system environment variables" is on.
@@ -141,7 +141,7 @@ pub fn run_system_env() -> std::collections::BTreeMap<String, String> {
pub async fn run_env_files(files: Vec<std::path::PathBuf>) -> IdeResult<std::collections::BTreeMap<String, String>> {
// In order (later files win): the same files a run loads, over the system environment
// debug adapters inherit.
crate::ops::blocking(move || {
crate::ops::doc::blocking(move || {
ide_run::envfile::load(&files, &ide_run::system_env())
.map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))
})
@@ -317,9 +317,7 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
.filter(|s| !s.is_empty())
.or_else(|| artifacts.first().map(|a| &a.id))
.ok_or_else(|| IdeError::invalid("Choose a WAR artifact"))?;
// One deployment of the config (`ide_run::tomcat::deployment_configs`); its build records go to its own directory.
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
let base = ide_run::tomcat::state_dir(&base, &config);
if let Some(name) = id.strip_prefix(PROJECT_ARTIFACT) {
let settings = project.settings.effective();
let detected = project.detected_roots.read().clone();
@@ -342,10 +340,7 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
let mut plan = ide_build::web::build(&project.root, &model, id, &base)?;
plan.env.extend(config.env.clone());
let mut build = RunConfig {
id: match config.extras.params.get("deploymentIndex") {
Some(i) => format!("tomcat-build:{}:{i}", config.id),
None => format!("tomcat-build:{}", config.id),
},
id: format!("tomcat-build:{}", config.id),
name: format!("Build {}", config.name),
kind: if id.starts_with("maven:") { "maven" } else { "gradle" }.into(),
command: plan.command.clone(),
@@ -410,12 +405,7 @@ pub async fn run_tomcat_sync(
let class_paths: Vec<_> =
class_paths.iter().filter_map(|p| dunce::canonicalize(project.root.join(p)).ok()).collect();
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
ide_run::tomcat::sync_outputs(
&ide_run::tomcat::state_dir(&base, &config),
&module,
&class_paths,
resources_only,
)
ide_run::tomcat::sync_outputs(&base, &module, &class_paths, resources_only)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
+16 -10
View File
@@ -1,14 +1,17 @@
//! File › New Project (`ide-scaffold`). Its commands run in Restricted Mode: New Project writes
//! only where the user chose and runs no code of an open project.
use super::{blocking, blocking_value};
use crate::Host;
use crate::ops::Channel;
use ide_command::command;
use ide_core::{IdeResult, IpcPath, RequestId};
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_scaffold::{CreateRequest, Field, GeneratorInfo, Requirement, ScaffoldEvent, Values};
use std::path::PathBuf;
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
/// The project generators File › New Project offers, in list order.
#[command(trust = always)]
pub fn scaffold_catalog() -> Vec<GeneratorInfo> {
@@ -26,28 +29,30 @@ pub async fn scaffold_options(
) -> IdeResult<Vec<Field>> {
// Spring Initializr's Boot versions and dependencies…; empty for other generators.
let cancel = host.begin_request(request);
let result = blocking(move || ide_scaffold::options(&generator, &values, &cancel)).await;
let result = tokio::task::spawn_blocking(move || ide_scaffold::options(&generator, &values, &cancel))
.await
.map_err(join_err);
host.end_request(request);
result
result?
}
/// The programs a generator needs for `values`, and whether they are installed.
#[command(trust = always)]
pub async fn scaffold_requirements(generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
blocking(move || ide_scaffold::requirements(&generator, &values)).await
tokio::task::spawn_blocking(move || ide_scaffold::requirements(&generator, &values)).await.map_err(join_err)?
}
/// Whether a project named `name` cannot be created in `location`: something other than an
/// empty folder is already there.
#[command(trust = always)]
pub async fn scaffold_target_taken(location: PathBuf, name: String) -> IdeResult<bool> {
blocking_value(move || ide_scaffold::target_taken(&location.join(name.trim()))).await
tokio::task::spawn_blocking(move || ide_scaffold::target_taken(&location.join(name.trim()))).await.map_err(join_err)
}
/// The first of `base`, `base1`, `base2`, … that names nothing in `location` yet.
#[command(trust = always)]
pub async fn scaffold_free_name(location: PathBuf, base: String) -> IdeResult<String> {
blocking_value(move || ide_scaffold::free_name(&location, &base)).await
tokio::task::spawn_blocking(move || ide_scaffold::free_name(&location, &base)).await.map_err(join_err)
}
/// Creates a project, streaming progress through `on_event`, and returns its directory,
@@ -61,14 +66,15 @@ pub async fn scaffold_create(
) -> IdeResult<IpcPath> {
// Trusted because the user just created it; a failed or cancelled run leaves no files behind.
let cancel = host.begin_request(request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
ide_scaffold::create(&req, &cancel, &|e| {
let _ = on_event.send(e);
})
})
.await;
.await
.map_err(join_err);
host.end_request(request);
let dir = result?;
let dir = result??;
host.set_project_trust(&dir, true, false).await?;
Ok(dir.into())
}
+55 -27
View File
@@ -1,5 +1,4 @@
//! Interpreters / toolchains (`ide-sdk`): discovery, Python virtualenvs and packages.
use super::{blocking, blocking_value, join_error};
use crate::Host;
use crate::ops::Channel;
use ide_command::command;
@@ -14,6 +13,10 @@ use std::sync::atomic::{AtomicUsize, Ordering};
pub mod container_python;
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
/// Executables found for "run this file", and where single files are compiled to.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
@@ -45,7 +48,7 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
(Some(p), SdkKind::Python) => ide_sdk::apply::python_interpreter(&p.root, &p.settings.effective()),
_ => None,
};
blocking_value(move || {
tokio::task::spawn_blocking(move || {
let mut sdks = ide_sdk::detect(kind, root.as_deref());
if let Some(path) = current
&& !sdks.iter().any(|s| *s.path == *path)
@@ -56,6 +59,7 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
sdks
})
.await
.map_err(join_err)
}
/// The Python interpreters of the recently opened projects, each with its project.
@@ -74,7 +78,7 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
.filter(|root| current.as_deref() != Some(root.as_path()))
.filter(|root| host.trust.window_trusted(root).unwrap_or(false))
.collect();
blocking_value(move || {
tokio::task::spawn_blocking(move || {
// Each project resolves its configured interpreter, else its own virtualenv. The
// probes run `python`, so keep them off the async runtime and bound how many run at
// once: the recent list can hold ~30 projects, and each probe starts a process.
@@ -103,6 +107,7 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
found.into_iter().map(|(_, interpreter)| interpreter).collect()
})
.await
.map_err(join_err)
}
/// An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run.
@@ -110,7 +115,9 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> IdeResult<Option<Sdk>> {
host.require_trust_if_project(window)?;
let root = host.project(window).ok().map(|p| p.root.clone());
blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref()))).await
tokio::task::spawn_blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref())))
.await
.map_err(join_err)?
}
/// `sys.path` of the interpreter `python`, for All Interpreters › Show Paths.
@@ -123,7 +130,7 @@ pub async fn sdk_python_sys_path(
) -> IdeResult<Vec<ide_core::IpcPath>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
let paths = ide_sdk::libraries::python_sys_path(&python, &cancel);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -136,9 +143,10 @@ pub async fn sdk_python_sys_path(
})?;
Ok(paths.iter().map(|p| p.as_path().into()).collect())
})
.await;
.await
.map_err(join_err);
host.end_request(request);
result
result?
}
/// For each folder added to an interpreter's paths, why it stays off the import path
@@ -150,7 +158,9 @@ pub async fn sdk_python_user_path_problems(
paths: Vec<String>,
) -> IdeResult<Vec<Option<ide_sdk::apply::UserPathProblem>>> {
host.require_trust_if_project(window)?;
blocking_value(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect()).await
tokio::task::spawn_blocking(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect())
.await
.map_err(join_err)
}
/// The interpreter of the workspace member `near` belongs to, else the project's.
@@ -191,7 +201,9 @@ pub async fn sdk_python_effective(
let project = host.project(window)?;
let config_dir = host.config_dir.clone();
// Loading a member's settings needs more stack than a sync command's main thread has left.
blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into))).await
tokio::task::spawn_blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into)))
.await
.map_err(join_err)?
}
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
@@ -214,7 +226,7 @@ pub async fn sdk_php_xdebug(
) -> IdeResult<ide_sdk::php::PhpXdebug> {
host.require_trust(window)?;
let cwd = cwd.or_else(|| host.project(window).ok().map(|p| p.root.clone()));
blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await
tokio::task::spawn_blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await.map_err(join_err)?
}
/// The PHP language level of the project `path` belongs to (a workspace member, by path, as
@@ -237,7 +249,7 @@ pub async fn sdk_php_language_level(host: &Host, window: &str, path: PathBuf) ->
let project = host.project(window)?;
let (project_root, project_settings) = (project.root.clone(), project.settings.effective());
let config_dir = host.config_dir.clone();
blocking_value(move || {
tokio::task::spawn_blocking(move || {
let member = ide_workspace::workspace::Workspace::load(&project_root).ok().flatten().and_then(|w| {
w.projects.into_iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count())
});
@@ -252,6 +264,7 @@ pub async fn sdk_php_language_level(host: &Host, window: &str, path: PathBuf) ->
}
})
.await
.map_err(join_err)
}
/// The Composer project `path` belongs to, when its dependencies need `composer install`.
@@ -275,11 +288,12 @@ pub async fn sdk_php_composer_install(
return Ok(None);
}
let root = project.root.clone();
blocking_value(move || {
tokio::task::spawn_blocking(move || {
ide_sdk::php::composer_install(&path, &root)
.map(|(root, reason)| ComposerInstallState { root: ide_core::IpcPath::from(root), reason })
})
.await
.map_err(join_err)
}
/// SDK / library source folders shown under "External Libraries" in the Project view,
@@ -340,7 +354,7 @@ pub async fn sdk_project_libraries(
return Err(IdeError::cancelled());
}
let groups =
ide_sdk::libraries::merge_groups([libraries.map_err(join_error)?, dependencies.map_err(join_error)?].concat());
ide_sdk::libraries::merge_groups([libraries.map_err(join_err)?, dependencies.map_err(join_err)?].concat());
if host.project(window).is_ok_and(|current| std::sync::Arc::ptr_eq(&current, &project)) {
host.mcp_reports
.set_libraries(window, groups.iter().flat_map(|g| g.roots.iter().map(|r| r.path.0.clone())).collect());
@@ -357,11 +371,12 @@ pub async fn sdk_locate_tools(
near: Option<PathBuf>,
) -> IdeResult<LocatedTools> {
host.require_trust(window)?;
blocking_value(move || LocatedTools {
tokio::task::spawn_blocking(move || LocatedTools {
tools: ide_sdk::locate::locate_tools(&names, near.as_deref()),
compile_dir: ide_sdk::locate::compile_dir().into(),
})
.await
.map_err(join_err)
}
/// The environments the window's project defines for Hatch, `default` first (hatch must be on PATH).
@@ -370,9 +385,10 @@ pub async fn sdk_python_hatch_envs(host: &Host, window: &str, request: RequestId
host.require_trust_if_project(window)?;
let root = host.project(window)?.root.clone();
let cancel = host.begin_project_request(window, request);
let result = blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await;
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await.map_err(join_err);
host.end_request(request);
result
result?
}
/// Creates a Python environment and streams its output through `on_output`.
@@ -391,14 +407,15 @@ pub async fn sdk_python_create_venv(
) -> IdeResult<Sdk> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
let _ = on_output.send(line);
})
})
.await;
.await
.map_err(join_err);
host.end_request(request);
result
result?
}
#[command(trust = outside_restricted)]
@@ -411,9 +428,11 @@ pub async fn sdk_python_packages(
) -> IdeResult<Vec<PythonPackage>> {
host.require_trust_if_project(window)?;
let cancel = host.begin_project_request(window, request);
let result = blocking(move || ide_sdk::python::list_packages(&python, outdated, &cancel)).await;
let result = tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, outdated, &cancel))
.await
.map_err(join_err);
host.end_request(request);
result
result?
}
/// A package index other than PyPI that installing from `python` uses; `None` for PyPI.
@@ -427,9 +446,13 @@ pub async fn sdk_python_package_index(
host.require_trust_if_project(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = blocking(move || ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel)).await;
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel)
})
.await
.map_err(join_err);
host.end_request(request);
result
result?
}
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
@@ -448,7 +471,7 @@ pub async fn sdk_python_pip(
host.require_trust_if_project(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
let send = |line: String| {
let _ = on_output.send(line);
};
@@ -458,16 +481,21 @@ pub async fn sdk_python_pip(
ide_sdk::python::install_package(&python, &requirement, upgrade, project_root.as_deref(), &cancel, &send)
}
})
.await;
.await
.map_err(join_err);
host.end_request(request);
result
result?
}
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home.
#[command(trust = trusted)]
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
// A macOS bundle too (Add JDK from Disk…).
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
tokio::task::spawn_blocking(move || {
ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))
})
.await
.map_err(join_err)
}
#[cfg(all(test, unix))]
+1 -1
View File
@@ -111,7 +111,7 @@ pub(crate) fn search_project(
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned);
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
+1 -1
View File
@@ -3,7 +3,7 @@ use crate::Host;
use crate::Project;
use ide_command::command;
use super::blocking;
use super::doc::blocking;
use ide_core::settings::SpellingSettings;
use ide_core::{DocId, IdeError, IdeResult, RequestId};
use ide_language::SpellingKind;
+1 -1
View File
@@ -10,7 +10,7 @@ use crate::Host;
use crate::Project;
use ide_command::command;
use super::blocking;
use super::doc::blocking;
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, LanguageId, Pos, Range, RequestId};
use ide_syntax::{
ExpressionAt, FileIdentifiers, IdentifierOccurrence, Locals, NodeAt, Snapshot, StructuralRanges, StructureResult,
-109
View File
@@ -1,109 +0,0 @@
use crate::Host;
use ide_command::command;
use ide_core::{IdeResult, RunId};
use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable};
use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm};
use std::sync::Arc;
/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process
/// tree, else the one carrying `token` (the run's marker property).
#[command(trust = trusted)]
pub async fn run_jvm_thread_dump(
host: &Arc<Host>,
window: &str,
id: RunId,
token: Option<String>,
) -> IdeResult<JvmThreadsResult> {
host.require_trust(window)?;
let remote = host.remote.runs.contains(id);
let root = if remote { None } else { host.processes.pid(id) };
let selected = host.blocking(move || Ok(run_jvm(remote, root, token.as_deref(), process_table, is_hotspot)));
let pid = match selected.await? {
Ok(pid) => pid,
Err(refused) => return Ok(refused),
};
// A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process)
// may hold it suspended, which only its session knows.
if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await {
return dump;
}
// The attach handshake blocks for seconds.
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await
}
fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult {
JvmThreadsResult::Unavailable { reason }
}
fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
unavailable(JvmThreadsUnavailable::Jvm { reason })
}
/// The run's JVM, or why none can be dumped. `root` is the run's process while it runs; the
/// process table is read only once the cheaper reasons to refuse are ruled out.
fn run_jvm(
remote: bool,
root: Option<u32>,
token: Option<&str>,
table: impl FnOnce() -> Vec<ProcEntry>,
is_hotspot: impl Fn(u32) -> bool,
) -> Result<u32, JvmThreadsResult> {
if remote {
return Err(unavailable(JvmThreadsUnavailable::RemoteRun));
}
let Some(root) = root else { return Err(jvm(JvmMemoryUnavailable::ProgramExited)) };
if !cfg!(unix) {
return Err(jvm(JvmMemoryUnavailable::UnsupportedPlatform));
}
select_run_jvm(&table(), root, token, is_hotspot).ok_or_else(|| jvm(JvmMemoryUnavailable::NoJvmProcess))
}
ide_command::domain!(thread_dump: run_jvm_thread_dump);
#[cfg(test)]
mod tests {
use super::*;
fn never_called<T>() -> T {
panic!("not reached")
}
#[cfg(unix)]
fn proc(pid: u32, ppid: u32, command: &str) -> ProcEntry {
ProcEntry { pid, ppid, command: command.into() }
}
#[test]
fn remote_run_is_refused() {
let result = run_jvm(true, Some(10), None, never_called, |_| never_called());
assert_eq!(result, Err(unavailable(JvmThreadsUnavailable::RemoteRun)));
}
#[test]
fn exited_run_reports_program_exited() {
let result = run_jvm(false, None, None, never_called, |_| never_called());
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::ProgramExited)));
}
#[cfg(unix)]
#[test]
fn no_jvm_in_tree() {
let table = || vec![proc(10, 1, "sh -c run"), proc(11, 10, "sleep 100")];
let result = run_jvm(false, Some(10), None, table, |_| false);
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::NoJvmProcess)));
}
#[cfg(unix)]
#[test]
fn finds_the_jvm_below_the_run() {
let table = || vec![proc(10, 1, "sh -c run"), proc(11, 10, "java -jar app.jar")];
assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11));
}
#[cfg(not(unix))]
#[test]
fn unsupported_without_reading_the_process_table() {
let result = run_jvm(false, Some(10), None, never_called, |_| never_called());
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::UnsupportedPlatform)));
}
}
+19 -14
View File
@@ -1,5 +1,4 @@
//! Language server / debug adapter installer and JDK downloads (`ide-tools`).
use super::{blocking, blocking_value};
use crate::Host;
use crate::ops::Channel;
use ide_command::command;
@@ -52,6 +51,10 @@ fn languages(host: &Host, window: &str) -> Vec<ide_language::LanguageConfig> {
langs
}
fn join_err(e: impl std::fmt::Display) -> IdeError {
IdeError::internal(e.to_string())
}
fn reconfigure_servers(host: &Host) {
for project in host.projects() {
let lsp = project.lsp.clone();
@@ -64,7 +67,7 @@ fn reconfigure_servers(host: &Host) {
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
let tools = tools(host, window)?;
let langs = languages(host, window);
blocking_value(move || tools.list(&langs)).await
tokio::task::spawn_blocking(move || tools.list(&langs)).await.map_err(join_err)
}
/// Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
@@ -80,14 +83,15 @@ pub async fn tools_install(
let tools = tools(host, window)?;
let langs = languages(host, window);
let cancel = host.begin_request(request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
tools.install(&name, &langs, &cancel, &|e| {
let _ = on_event.send(e);
})
})
.await;
.await
.map_err(join_err);
host.end_request(request);
let info = result?;
let info = result??;
// Language servers whose launch depends on installed tools (jdtls loads the
// java-debug bundle) pick the change up.
reconfigure_servers(host);
@@ -100,9 +104,9 @@ pub async fn tools_install(
pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<ToolUpdate>> {
let tools = tools(host, window)?;
let cancel = host.begin_request(request);
let result = blocking(move || tools.updates(&cancel)).await;
let result = tokio::task::spawn_blocking(move || tools.updates(&cancel)).await.map_err(join_err);
host.end_request(request);
result
result?
}
/// Removes a tool the IDE installed.
@@ -110,7 +114,7 @@ pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> Ide
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
let tools = tools(host, window)?;
let langs = languages(host, window);
let info = blocking(move || tools.uninstall(&name, &langs)).await?;
let info = tokio::task::spawn_blocking(move || tools.uninstall(&name, &langs)).await.map_err(join_err)??;
reconfigure_servers(host);
Ok(info)
}
@@ -126,9 +130,9 @@ pub fn jdk_download_vendors() -> Vec<JdkVendor> {
pub async fn jdk_download_releases(host: &Host, vendor: String, request: RequestId) -> IdeResult<JdkReleases> {
let tools = Tools::new(&host.local_data_dir);
let cancel = host.begin_request(request);
let result = blocking(move || tools.jdk_releases(&vendor, &cancel)).await;
let result = tokio::task::spawn_blocking(move || tools.jdk_releases(&vendor, &cancel)).await.map_err(join_err);
host.end_request(request);
result
result?
}
/// Where Download JDK puts JDKs unless told otherwise.
@@ -153,7 +157,7 @@ pub async fn jdk_download(
let tools = Tools::new(&host.local_data_dir);
let location = location.filter(|p| !p.as_os_str().is_empty());
let cancel = host.begin_request(request);
let result = blocking(move || {
let result = tokio::task::spawn_blocking(move || {
let jdk = tools.download_jdk(&vendor, version, location.as_deref(), &cancel, &|e| {
let _ = on_event.send(e);
})?;
@@ -167,9 +171,10 @@ pub async fn jdk_download(
.ok_or_else(|| IdeError::internal(format!("{} is not a JDK home", home.display())))?;
IdeResult::Ok(ide_sdk::jdk_sdk(&jdk))
})
.await;
.await
.map_err(join_err);
host.end_request(request);
let sdk = result?;
let sdk = result??;
reconfigure_servers(host);
Ok(sdk)
}
@@ -188,7 +193,7 @@ pub async fn jdtls_required_java(host: &Host, window: &str) -> IdeResult<Option<
};
ide_sdk::apply::server_launch_overrides(&mut cfg, &settings);
ide_sdk::apply::server_protocol_overrides(&mut cfg, &settings);
blocking_value(move || ide_sdk::java::jdtls_required_java(&cfg)).await
tokio::task::spawn_blocking(move || ide_sdk::java::jdtls_required_java(&cfg)).await.map_err(join_err)
}
ide_command::domain!(
+4 -1
View File
@@ -3,7 +3,6 @@ use super::*;
use crate::Host;
use crate::Project;
use crate::ops::Channel;
use crate::ops::blocking;
use ide_command::command;
use ide_core::error::PushDivergence;
use ide_core::ipc_path::IpcPath;
@@ -414,6 +413,10 @@ fn per_backend(
per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths))
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
}
fn with_shelf_batch<T>(project: &Project, batch: Option<String>, operation: impl FnOnce() -> T) -> T {
let Some(batch) = batch.and_then(|id| uuid::Uuid::parse_str(&id).ok()) else { return operation() };
let repos = project.repos();
+1 -1
View File
@@ -8,7 +8,7 @@ use ide_core::proxy_settings::{ProxyMode, ProxySettings};
use std::time::Duration;
/// Whether `url` names this machine (`localhost` or a loopback address).
pub fn is_loopback(url: &reqwest::Url) -> bool {
fn is_loopback(url: &reqwest::Url) -> bool {
let host = url.host_str().unwrap_or_default().trim_start_matches('[').trim_end_matches(']');
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
}
+2 -51
View File
@@ -136,10 +136,6 @@ pub trait PluginWorkspace: Send + Sync {
fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit], background: bool) -> Result<u64, HostError>;
/// Code from the project may run (git hooks and config on fetch).
fn trusted(&self, root: &Path) -> bool;
/// Git roots with the same directory mappings as the VCS tool window.
fn repositories(&self, _root: &Path) -> Result<ide_vcs::Repos, HostError> {
Err(HostError::NotFound("no open project repositories".into()))
}
/// The git executable of the project at `root` (see [`crate::Project::git_executable`]).
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
None
@@ -2398,40 +2394,8 @@ impl HostApi for PluginApi {
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError> {
let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { return Ok(Vec::new()) };
plugin_remotes(&repo)
}
fn vcs_roots(&self, root: &Path) -> Result<Vec<String>, HostError> {
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
Ok(workspace
.repositories(root)?
.roots()
.iter()
.filter(|r| r.starts_with(root) || root.starts_with(r))
.map(|r| to_ipc(r))
.collect())
}
fn vcs_repository_at(&self, root: &Path, path: &str) -> Result<Option<ide_plugin::RepositoryInfo>, HostError> {
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
if !workspace.trusted(root) {
return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into()));
}
let path = ide_plugin::resolve_in_root(root, path).map_err(HostError::Invalid)?;
let repos = workspace.repositories(root)?;
// A link to a nested worktree directory denotes that worktree, not its entry in the parent.
let Some(repo) = repos.at_root(&path).or_else(|| repos.for_path(&path)) else { return Ok(None) };
let relative = path.strip_prefix(repo.root()).map_err(failed)?;
let info = repo.branch_info().map_err(failed)?;
Ok(Some(ide_plugin::RepositoryInfo {
root: to_ipc(repo.root()),
relative_path: to_ipc(relative),
branch: info.head,
commit: info.head_commit,
upstream: info.upstream,
ahead: info.ahead,
remotes: plugin_remotes(repo)?,
}))
let remotes = repo.remotes().map_err(failed)?;
Ok(remotes.into_iter().map(|r| (r.name, without_credentials(&r.url))).collect())
}
fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError> {
@@ -3552,7 +3516,6 @@ impl PluginWorkspace for HostWorkspace {
max_matches: limit.min(10_000).saturating_add(1),
context: Default::default(),
include_excluded: false,
skip_large_files: false,
};
query.exclude.extend(project.search_excludes());
let files = Mutex::new(Vec::new());
@@ -3766,13 +3729,6 @@ impl PluginWorkspace for HostWorkspace {
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
}
fn repositories(&self, root: &Path) -> Result<ide_vcs::Repos, HostError> {
Ok(self
.project_covering(root)
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?
.repos())
}
fn git_executable(&self, root: &Path) -> Option<PathBuf> {
HostWorkspace::project_covering(self, root)?.git_executable()
}
@@ -4737,10 +4693,6 @@ fn from_window<'a>(client: Option<&'a str>, what: &str) -> Result<&'a str, HostE
client.ok_or_else(|| HostError::Invalid(format!("can only {what} from a command the user invoked")))
}
fn plugin_remotes(repo: &ide_vcs::Repo) -> Result<Vec<(String, String)>, HostError> {
Ok(repo.remotes().map_err(failed)?.into_iter().map(|r| (r.name, without_credentials(&r.url))).collect())
}
/// `url` without the `user:password@` a remote may carry (`https://user:token@host/…`):
/// `vcs.read` must not hand out credentials. scp-style `git@host:path` has no password.
fn without_credentials(url: &str) -> String {
@@ -5057,7 +5009,6 @@ mod workbench_tests {
style: style.into(),
hover: None,
after: Some("after".into()),
markdown_hover: None,
};
api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap();
assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 1);
+5 -2
View File
@@ -5,15 +5,18 @@ use super::{
PluginInfo, PluginStatusItem, WorkbenchEvent,
};
use crate::Host;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{IdeResult, RequestId};
use ide_core::{IdeError, IdeResult, RequestId};
use ide_plugin::Invocation;
use ide_workspace::settings::SettingsScope;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Runs a plugin command in the context of this window's project and focused editor.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
+4 -1
View File
@@ -1,5 +1,4 @@
use super::PluginHost;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
use ide_plugin::Invocation;
@@ -201,6 +200,10 @@ pub async fn plugin_navigation_markers(
.await
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
ide_command::domain!(
plugins_index_ops:
plugin_endpoints,
+16 -175
View File
@@ -11,7 +11,6 @@ use super::{PackageFile, PluginEvent, PluginHost, PluginSource, PluginStatus, Pl
use ide_core::{IdeError, IdeResult};
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, PluginIcon, SIGNATURE_FILE};
use ide_extension::{MANIFEST_FILE, Manifest};
use ide_tools::mirror;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
@@ -238,11 +237,6 @@ impl PluginHost {
*self.default_market_url.write() = url.filter(|u| !u.trim().is_empty());
}
/// Where plugin packages are fetched from first (Tools › Download sources).
pub fn set_downloads(&self, downloads: ide_core::settings::ToolDownloadSettings) {
*self.downloads.write() = downloads;
}
pub fn set_market_url(&self, url: Option<String>) {
self.state.lock().market_url = url.filter(|u| !u.trim().is_empty());
self.save_state();
@@ -361,111 +355,40 @@ impl PluginHost {
entry.id, entry.version
)));
}
let candidates = mirror::candidates(&download, &self.downloads.read());
let bytes = read_url(&download, MAX_PACKAGE).map_err(IdeError::unavailable)?;
let downloads = self.plugins_dir.join(DOWNLOADS);
std::fs::create_dir_all(&downloads)?;
let archive = downloads.join(format!("{}-{}.{}", entry.id, entry.version, package::PACKAGE_EXTENSION));
let picked = try_sources(&candidates, |index, candidate| {
// Bytes a failed source left behind must not be unpacked as the next one's.
if index > 0 {
let _ = std::fs::remove_file(&archive);
}
// Which source a package comes from is the first thing to look at when an install
// is slow or fails (a mirror is one of several candidates), so it goes in the log.
tracing::info!(
"plugins: {} {} from {} ({}){}",
entry.id,
entry.version,
candidate.url,
candidate.describe(),
if candidates.len() > 1 {
format!(", source {} of {}", index + 1, candidates.len())
} else {
String::new()
}
);
let fetched = self.fetch_market_package(&candidate.url, &entry, &archive);
if let Err(e) = &fetched {
tracing::warn!("plugins: {} from {} failed: {}", entry.id, candidate.url, e.message);
}
fetched
});
match picked {
Ok((dir, index)) => {
tracing::info!(
"plugins: {} {} installed from {}",
entry.id,
entry.version,
candidates[index].describe()
);
Ok(dir)
}
Err(e) => Err(e),
}
}
/// Fetches the package of `entry` from `url`, checks it against the index (its digest, then
/// the publisher's signature) and only then hands it over, unpacked. A failure here is that
/// source's failure.
///
/// The index has no hash of the archive itself, only [`package_digest`] of the unpacked
/// contents, so the bytes have to be unpacked before they can be checked. The unpacked
/// files of a source that does **not** check are therefore kept out of reach until they
/// pass: they go to a staging folder of this attempt, and every exit but the verified one
/// removes it, so nothing a mirror served is ever left where the install page reads from.
fn fetch_market_package(&self, url: &str, entry: &IndexEntry, archive: &Path) -> IdeResult<PathBuf> {
let bytes = read_url(url, MAX_PACKAGE).map_err(IdeError::unavailable)?;
std::fs::write(archive, bytes)?;
let unpacked = self.unpack_package(archive);
// The archive is needed only until it is unpacked; a failed source leaves none behind.
let _ = std::fs::remove_file(archive);
let dir = unpacked?;
self.verify_market_package(&dir, entry).inspect_err(|_| {
let _ = std::fs::remove_dir_all(&dir);
})?;
Ok(dir)
}
/// Whether the unpacked package in `dir` is the one `entry` names: same id, version and
/// digest, and signed by a publisher the index trusts.
fn verify_market_package(&self, dir: &Path, entry: &IndexEntry) -> IdeResult<()> {
let manifest = Manifest::load(dir).map_err(IdeError::invalid)?;
let files = self.package_files_in(dir)?;
let digest = package::package_digest(dir, &files)?;
std::fs::write(&archive, bytes)?;
let dir = self.unpack_package(&archive);
let _ = std::fs::remove_file(&archive);
let dir = dir?;
let manifest = Manifest::load(&dir).map_err(IdeError::invalid)?;
let files = self.package_files_in(&dir)?;
let digest = package::package_digest(&dir, &files)?;
if (manifest.id.as_str(), manifest.version.as_str(), digest.as_str())
!= (&entry.id, &entry.version, &entry.digest)
{
let _ = std::fs::remove_dir_all(&dir);
return Err(IdeError::invalid("the download does not match the marketplace's entry"));
}
if self.verified_publisher(dir).is_none() {
if self.verified_publisher(&dir).is_none() {
let _ = std::fs::remove_dir_all(&dir);
return Err(IdeError::invalid("the marketplace package is not signed by a trusted publisher"));
}
Ok(())
Ok(dir)
}
/// Unpacks a package file (`.oiplugin`, or a `.zip` of a package) next to the downloads; returns the folder.
///
/// A package that fails to unpack leaves nothing: the folder is removed, so a half-written
/// zip is never mistaken for a package (a mirror's bytes reach here before they are checked).
pub fn unpack_package(&self, archive: &Path) -> IdeResult<PathBuf> {
let stem = archive.file_stem().and_then(|s| s.to_str()).unwrap_or("package");
let dir = self.plugins_dir.join(DOWNLOADS).join(format!("{stem}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let unpacked = match package::unpack(archive, &dir) {
Ok(unpacked) => unpacked,
Err(e) => {
let _ = std::fs::remove_dir_all(&dir);
return Err(IdeError::invalid(e));
}
};
let unpacked = package::unpack(archive, &dir).map_err(IdeError::invalid)?;
// Kept with the files: install checks it and keeps it with the installed copy.
if let Some(sig) = unpacked.signature {
let json = serde_json::to_string_pretty(&sig).map_err(|e| IdeError::internal(e.to_string()));
let written = json.and_then(|json| std::fs::write(dir.join(SIGNATURE_FILE), json).map_err(IdeError::from));
if let Err(e) = written {
let _ = std::fs::remove_dir_all(&dir);
return Err(e);
}
let json = serde_json::to_string_pretty(&sig).map_err(|e| IdeError::internal(e.to_string()))?;
std::fs::write(dir.join(SIGNATURE_FILE), json)?;
}
Ok(dir)
}
@@ -617,31 +540,6 @@ pub(super) fn read_signature(dir: &Path) -> Option<PackageSignature> {
serde_json::from_str(&text).ok()
}
/// The first `candidate` whose `attempt` succeeds, with its index.
///
/// A mirror is a third party: when one fails, that failure is its own and the official host
/// below still gets its turn. The official host is the last candidate, so its failure is the
/// download's: returned as it is when nothing came before it, else with the mirrors' reasons.
fn try_sources<T>(
candidates: &[mirror::Candidate],
mut attempt: impl FnMut(usize, &mirror::Candidate) -> IdeResult<T>,
) -> IdeResult<(T, usize)> {
let mut failures: Vec<String> = Vec::new();
for (index, candidate) in candidates.iter().enumerate() {
match attempt(index, candidate) {
Ok(value) => return Ok((value, index)),
// A mirror's failure is its own: the next source still gets a turn.
Err(e) if candidate.mirror.is_some() => failures.push(format!("{}: {}", candidate.describe(), e.message)),
Err(e) if failures.is_empty() => return Err(e),
Err(e) => {
failures.push(format!("{}: {}", candidate.describe(), e.message));
return Err(IdeError::unavailable(format!("could not download ({})", failures.join("; "))));
}
}
}
Err(IdeError::unavailable(format!("could not download ({})", failures.join("; "))))
}
/// Keeps the signature of a package with its installed copy.
pub(super) fn copy_signature(src: &Path, installed: &Path) {
if src.join(SIGNATURE_FILE).is_file() {
@@ -690,60 +588,6 @@ mod tests {
assert!(reachable_from("/srv/market/index.json", "/srv/market/a.oiplugin"));
}
#[test]
fn a_mirror_that_serves_a_bad_package_leaves_the_official_host_its_turn() {
// Two sources: the mirror, then the official host. The mirror answers with bytes that
// do not verify — which is exactly the failure `fetch_market_package` reports for a
// tampered package — and the official host must still be asked.
let candidates = mirror::candidates(
"https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin",
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
);
let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
let picked = try_sources(&candidates, |index, candidate| {
asked.borrow_mut().push(index);
match candidate.mirror.is_some() {
true => Err(IdeError::invalid("the download does not match the marketplace's entry")),
false => Ok("the official copy"),
}
});
let (copy, index) = picked.unwrap();
assert_eq!((copy, index), ("the official copy", 1));
assert_eq!(*asked.borrow(), [0, 1], "the mirror was tried first, then the official host");
// Both failing: the official host's error is the download's, with the mirror's folded in.
let err = try_sources(&candidates, |index, candidate| -> IdeResult<&str> {
match candidate.mirror.is_some() {
true => Err(IdeError::invalid("the download does not match the marketplace's entry")),
false => Err(IdeError::unavailable(format!("nothing at {index}"))),
}
})
.unwrap_err();
assert!(err.message.contains("https://gh-proxy.com/"), "{}", err.message);
assert!(err.message.contains("nothing at 1"), "{}", err.message);
}
#[test]
fn a_download_goes_to_the_mirror_first_and_the_official_host_last() {
let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin";
let through = mirror::candidates(
url,
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
);
assert_eq!(through.len(), 2);
assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}"));
assert!(through[0].mirror.is_some());
assert_eq!((through[1].url.as_str(), through[1].mirror.is_none()), (url, true));
// A local index's own package is not on GitHub: no prefix may carry it.
let local = mirror::candidates(
"/srv/market/a.oiplugin",
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
);
assert_eq!(local.len(), 1);
assert_eq!(local[0].url, "/srv/market/a.oiplugin");
}
#[test]
fn a_failed_read_says_why() {
// A port nothing listens on: refused.
@@ -751,10 +595,7 @@ mod tests {
let url = format!("http://127.0.0.1:{port}/a.oiplugin");
let err = read_url(&url, 1 << 20).unwrap_err();
assert_eq!(err.matches(&url).count(), 1, "{err}");
// The cause follows the URL. Its wording is the OS's, and localised: assert that it is
// there rather than spelling out any one language's phrase for a refused connection.
let cause = err.strip_prefix(&url).unwrap_or_default().trim_start_matches([':', ' ']);
assert!(cause.len() > 1, "the failure says nothing beyond the URL: {err}");
assert!(err.to_lowercase().contains("refused"), "{err}");
}
#[test]
-3
View File
@@ -429,8 +429,6 @@ pub struct PluginHost {
announced_updates: Mutex<Vec<String>>,
/// The marketplace used while the user has set none (the app's official one).
default_market_url: RwLock<Option<String>>,
/// Tools › Download sources: where plugin packages are fetched from first.
downloads: RwLock<ide_core::settings::ToolDownloadSettings>,
/// Updates not confirmed yet (the new version hasn't started once): what
/// to roll back to.
updates: Mutex<HashMap<String, PendingUpdate>>,
@@ -501,7 +499,6 @@ impl PluginHost {
official_keys: RwLock::new(official_keys),
announced_updates: Mutex::default(),
default_market_url: RwLock::new(None),
downloads: RwLock::new(Default::default()),
updates: Mutex::default(),
project_policy: RwLock::new(Arc::new(|_| false)),
engine: PluginEngine::new().map_err(IdeError::internal)?,
+4 -1
View File
@@ -20,7 +20,6 @@
use super::{Consent, HostWorkspace, PluginEvent, PluginHost, PluginSource, SecretStore};
use crate::catalogue::TrustClass;
use crate::ops::blocking;
use crate::rpc::{Dispatcher, PeerHandle};
use base64::Engine as _;
use ide_core::{IdeError, IdeResult};
@@ -452,6 +451,10 @@ impl RemotePlugins {
}
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
fn spawn_supervision(host: Weak<PluginHost>) -> IdeResult<()> {
std::thread::Builder::new().name("remote-plugins".into()).spawn(move || {
for n in 1u32.. {
+3 -188
View File
@@ -36,7 +36,6 @@
//! priority = "default" # or "option": only through Open With
//! layout = "tab" # or "split" / "preview": beside the text editor
//! web = "web/index.html" # a web page from the package instead of rendered content
//! frames = ["https://example.com"] # API 1.16: origins the page may embed; each needs `net:<host>`
//!
//! [[contributes.editorPanels]]
//! id = "minimap"
@@ -642,65 +641,6 @@ struct ViewDecl {
/// A web page of the package (`web/index.html`) instead of content the code renders.
#[serde(default, skip_serializing_if = "Option::is_none")]
web: Option<String>,
/// Origins the web page may embed in `<iframe>`s (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
}
/// Most origins one web page may declare in `frames`.
const MAX_FRAMES: usize = 16;
/// Checks a web page's `frames` and returns them as origins (`https://host[:port]`).
/// Each is HTTPS, or HTTP to a loopback host, and must be covered by a `net:` or
/// `net.http:` capability of the manifest, so the install page lists it; the page
/// gets only the ones the user granted.
fn frame_origins(pkg: &Package, frames: &[String], web: bool, what: &str) -> Result<Vec<String>, String> {
if frames.is_empty() {
return Ok(Vec::new());
}
pkg.manifest.needs_api(&format!("{what}: `frames`"), 16)?;
if !web {
return Err(format!("{what}: `frames` is for a web page (`web`)"));
}
if frames.len() > MAX_FRAMES {
return Err(format!("{what}: at most {MAX_FRAMES} `frames`"));
}
let mut origins = Vec::new();
for frame in frames {
let origin = frame_origin(frame).map_err(|e| format!("{what}: frames: {frame:?}: {e}"))?;
let cap = ide_plugin::net_capability(&origin).map_err(|e| format!("{what}: frames: {frame:?}: {e}"))?;
if !pkg.manifest.capabilities.all().any(|c| c.covers(&cap)) {
return Err(format!("{what}: frames: {frame:?} needs the `{cap}` capability (required or optional)"));
}
if !origins.contains(&origin) {
origins.push(origin);
}
}
Ok(origins)
}
/// `https://host[:port]` (or `http://` to a loopback host) with nothing after it.
fn frame_origin(frame: &str) -> Result<String, String> {
let url = url::Url::parse(frame).map_err(|e| format!("not a URL ({e})"))?;
let loopback = matches!(
url.host(),
Some(url::Host::Domain("localhost")) | Some(url::Host::Ipv4(std::net::Ipv4Addr::LOCALHOST))
) || url.host() == Some(url::Host::Ipv6(std::net::Ipv6Addr::LOCALHOST));
match url.scheme() {
"https" => {}
"http" if loopback => {}
_ => return Err("an origin is https://, or http:// to localhost".into()),
}
if url.host_str().is_none_or(|h| h.contains('*')) {
return Err("name one exact host".into());
}
if !url.username().is_empty() || url.password().is_some() {
return Err("no user name or password".into());
}
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
return Err("an origin only: no path, query or fragment".into());
}
Ok(url.origin().ascii_serialization())
}
/// The files of a `web` entry, or a check that the code renders the view.
@@ -715,7 +655,7 @@ fn web_or_code(pkg: &Package, web: Option<&str>, what: &str) -> Result<Vec<PathB
}
pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let mut d: ViewDecl = decode(VIEWS, decl)?;
let d: ViewDecl = decode(VIEWS, decl)?;
validate_item_id(&d.id, "view id")?;
title(VIEWS, &d.title)?;
if let Some(group) = &d.group {
@@ -728,7 +668,6 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
}
let files = web_or_code(pkg, d.web.as_deref(), &format!("view {:?}", d.id))?;
d.frames = frame_origins(pkg, &d.frames, d.web.is_some(), &format!("view {:?}", d.id))?;
if !["left", "right", "bottom", SERVICES_LOCATION].contains(&d.location.as_str()) {
return Err(format!("view {:?}: `location` is left, right, bottom or services", d.id));
}
@@ -795,11 +734,6 @@ struct CustomEditorDecl {
layout: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
web: Option<String>,
/// Origins the web page may embed (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
binary: Option<bool>,
}
fn default_priority() -> String {
@@ -824,12 +758,11 @@ fn file_patterns(patterns: &[String], what: &str) -> Result<(), String> {
}
pub(super) fn custom_editor(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let mut d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?;
let d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?;
validate_item_id(&d.id, "custom editor id")?;
title(CUSTOM_EDITORS, &d.title)?;
let what = format!("custom editor {:?}", d.id);
let files = web_or_code(pkg, d.web.as_deref(), &what)?;
d.frames = frame_origins(pkg, &d.frames, d.web.is_some(), &what)?;
file_patterns(&d.patterns, &what)?;
if d.priority != "default" && d.priority != "option" {
return Err(format!("{what}: `priority` is default or option"));
@@ -837,12 +770,6 @@ pub(super) fn custom_editor(pkg: &Package, decl: toml::Value) -> Result<UiDecl,
if !["tab", "split", "preview"].contains(&d.layout.as_str()) {
return Err(format!("{what}: `layout` is tab, split or preview"));
}
if let Some(binary) = d.binary {
pkg.manifest.needs_api("contributes.customEditors.binary", 16)?;
if binary && (d.web.is_none() || d.layout != "tab") {
return Err(format!("{what}: `binary` requires a web editor with `layout = \"tab\"`"));
}
}
let mut out = UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?);
out.files = files;
Ok(out)
@@ -856,9 +783,6 @@ struct EditorPanelDecl {
width: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
/// Origins the page may embed (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
}
const EDITOR_PANEL_WIDTH: std::ops::RangeInclusive<u32> = 40..=400;
@@ -867,7 +791,7 @@ const EDITOR_PANEL_WIDTH: std::ops::RangeInclusive<u32> = 40..=400;
/// editor group, beside its text editor. It sees each file the group shows, so it
/// needs `editor.read`.
pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let mut d: EditorPanelDecl = decode(EDITOR_PANELS, decl)?;
let d: EditorPanelDecl = decode(EDITOR_PANELS, decl)?;
pkg.manifest.needs_api(&format!("contributes.{EDITOR_PANELS}"), 9)?;
validate_item_id(&d.id, "editor panel id")?;
let what = format!("editor panel {:?}", d.id);
@@ -881,7 +805,6 @@ pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, S
return Err(format!("{what}: needs the `editor.read` capability (the page sees the files editors show)"));
}
let files = super::web::web_files(pkg, &d.web, &what)?;
d.frames = frame_origins(pkg, &d.frames, true, &what)?;
let mut out = UiDecl::new(d.id.clone(), d.id.clone(), json(&d)?);
out.files = files;
Ok(out)
@@ -1410,114 +1333,6 @@ mod tests {
assert!(check(&optional).is_ok());
}
#[test]
fn binary_custom_editor_requires_api_1_16() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("web")).unwrap();
std::fs::write(dir.path().join("web/view.html"), "").unwrap();
let check = |engine: &str, binary: &str| {
let source = format!(
r#"id = "p"
name = "P"
version = "1.0.0"
engines.openidea = "{engine}"
[[contributes.customEditors]]
id = "data"
title = "Data"
patterns = ["*.bin"]
web = "web/view.html"
{binary}
"#
);
let manifest = ide_extension::Manifest::parse(&source)?;
let decl = manifest.declarations(CUSTOM_EDITORS).into_iter().next().unwrap();
custom_editor(&Package::new(manifest, dir.path().to_path_buf()), decl)
};
for value in [true, false] {
let field = format!("binary = {value}");
assert_eq!(check("^1.16", &field).unwrap().json["binary"], value);
assert_eq!(
check("^1.15", &field).unwrap_err(),
r#"contributes.customEditors.binary is new in plugin API 1.16: set engines.openidea to "^1.16""#
);
}
assert!(check("^1.15", "").unwrap().json.get("binary").is_none());
}
#[test]
fn web_pages_declare_frames_their_net_capabilities_cover() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("web")).unwrap();
std::fs::write(dir.path().join("web/index.html"), "<iframe></iframe>").unwrap();
let header = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.16\"\nwasm = \"p.wasm\"\n\
[capabilities]\nrequired = [\"editor.read\", \"net:example.com\", \"net:*.games.test\", \"net:localhost\"]\n";
let check = |point: &str, body: &str, header: &str| {
let manifest = ide_extension::Manifest::parse(&format!("{header}[[contributes.{point}]]\n{body}"))?;
let decl = manifest.declarations(point).into_iter().next().unwrap();
let pkg = Package::new(manifest, dir.path().to_path_buf());
match point {
VIEWS => view(&pkg, decl),
CUSTOM_EDITORS => custom_editor(&pkg, decl),
_ => editor_panel(&pkg, decl),
}
};
let view_with =
|frames: &str| format!("id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\nframes = {frames}\n");
let ok = check(
VIEWS,
&view_with(r#"["https://EXAMPLE.com/", "https://a.games.test:8443", "http://localhost:5173"]"#),
header,
)
.unwrap();
assert_eq!(
ok.json["frames"],
serde_json::json!(["https://example.com", "https://a.games.test:8443", "http://localhost:5173"])
);
assert!(
check(VIEWS, "id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\n", header)
.unwrap()
.json
.get("frames")
.is_none()
);
let editor = "id = \"e\"\ntitle = \"E\"\npatterns = [\"*.x\"]\nweb = \"web/index.html\"\nframes = [\"https://example.com\"]\n";
assert_eq!(
check(CUSTOM_EDITORS, editor, header).unwrap().json["frames"],
serde_json::json!(["https://example.com"])
);
let panel = "id = \"m\"\nweb = \"web/index.html\"\nwidth = 110\nframes = [\"https://example.com\"]\n";
assert_eq!(
check(EDITOR_PANELS, panel, header).unwrap().json["frames"],
serde_json::json!(["https://example.com"])
);
for (frames, error) in [
(r#"["https://other.com"]"#, "`net:other.com` capability"),
(r#"["https://games.test"]"#, "`net:games.test` capability"),
(r#"["http://example.com"]"#, "https://, or http:// to localhost"),
(r#"["ftp://example.com"]"#, "https://, or http:// to localhost"),
(r#"["https://example.com/room"]"#, "no path"),
(r#"["https://example.com?x"]"#, "no path"),
(r#"["https://example.com/#x"]"#, "no path"),
(r#"["https://*.games.test"]"#, "one exact host"),
(r#"["https://[email protected]"]"#, "user name"),
(r#"["example.com"]"#, "not a URL"),
(r#"["data:text/html,x"]"#, "https://"),
] {
let err = check(VIEWS, &view_with(frames), header).unwrap_err();
assert!(err.contains(error), "{frames} → {err}");
}
let many = format!("[{}]", vec!["\"https://example.com\""; 17].join(", "));
assert!(check(VIEWS, &view_with(&many), header).unwrap_err().contains("at most 16"));
let older = header.replace("^1.16", "^1.15");
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &older).unwrap_err().contains("1.16"));
let code_view = "id = \"v\"\ntitle = \"V\"\nframes = [\"https://example.com\"]\n";
assert!(check(VIEWS, code_view, header).unwrap_err().contains("for a web page"));
// `net:ask` is not a listed host: the install page would not show the origin.
let ask = header.replace("\"net:example.com\"", "\"net:ask\"");
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &ask).unwrap_err().contains("capability"));
}
fn package_with_catalogs(files: &[(&str, &str)]) -> (tempfile::TempDir, Package) {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join(LOCALES_DIR)).unwrap();
+4 -1
View File
@@ -4,7 +4,6 @@
//! the desktop for local projects, `openidea-server` for remote ones.
use super::{PluginEditor, PluginHost, PluginOutputLine};
use crate::ops::blocking;
use ide_command::command;
use ide_core::{DocId, IdeError, IdeResult};
use ide_plugin::{EditorContext, Invocation, ServiceTab, View, ViewEvent, Viewport};
@@ -36,6 +35,10 @@ pub fn view_invocation(
})
}
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Content of a plugin view (`doc`: the document of a custom editor; `editor`: for
/// a tool window, the window's active editor, as commands get it).
#[allow(clippy::too_many_arguments)]
+1 -38
View File
@@ -121,10 +121,6 @@ pub(super) struct WebPtySession {
pub struct WebFile {
pub bytes: Vec<u8>,
pub mime: &'static str,
/// The origins a page may embed: `None` when no web page whose directory holds
/// the file declares `frames` (API 1.16), else the declared origins the user has
/// granted (`net:` / `net.http:`), possibly none.
pub frames: Option<Vec<String>>,
}
impl PluginHost {
@@ -328,32 +324,6 @@ impl PluginHost {
})
}
/// `frames` of the web pages whose directory holds `rel`, kept to those `granted`.
fn web_frames(&self, plugin: &str, rel: &str, granted: &[ide_extension::Capability]) -> Option<Vec<String>> {
let declared: Vec<String> = super::ui_points::WEB_POINTS
.iter()
.flat_map(|point| self.ui.items(point, Some(plugin)))
.filter(|item| {
let dir = item.decl.get("web").and_then(|w| w.as_str()).and_then(|e| e.rsplit_once('/'));
dir.is_some_and(|(dir, _)| rel.starts_with(&format!("{dir}/")))
})
.filter_map(|item| item.decl.get("frames").and_then(|f| f.as_array()).cloned())
.flatten()
.filter_map(|f| f.as_str().map(str::to_owned))
.collect();
if declared.is_empty() {
return None;
}
let mut allowed = Vec::new();
for origin in declared {
let ok = ide_plugin::net_capability(&origin).is_ok_and(|cap| granted.iter().any(|g| g.covers(&cap)));
if ok && !allowed.contains(&origin) {
allowed.push(origin);
}
}
Some(allowed)
}
/// The web roots `plugin` declares (entry directories, package-relative, `/`-terminated).
fn web_dirs(&self, plugin: &str) -> Vec<String> {
super::ui_points::WEB_POINTS
@@ -406,14 +376,7 @@ impl PluginHost {
return Err(IdeError::not_found(format!("{rel}: not part of a web view")));
}
let bytes = plugin.pkg.read_bytes(rel_path).map_err(IdeError::not_found)?;
let mime = mime(rel);
let frames = if mime.starts_with("text/html") {
let granted = plugin.meta.lock().granted.clone();
self.web_frames(plugin_id, rel, &granted)
} else {
None
};
Ok(WebFile { bytes, mime, frames })
Ok(WebFile { bytes, mime: mime(rel) })
}
}
+6 -42
View File
@@ -753,8 +753,7 @@ impl Host {
self.data_dir.join("db-history.json"),
self.ssh.clone(),
)
.with_global_sources(self.data_dir.clone())
.with_local_external_tunnels(self.local_database_tunnels),
.with_global_sources(self.data_dir.clone()),
);
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(project_key)));
let agents = Arc::new(ide_agent::AgentManager::new(
@@ -1499,15 +1498,17 @@ impl Project {
return encoding_rs::Encoding::for_label(info.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown document encoding"));
}
let defaults = self.documents.file_defaults();
let fallback = defaults.fallback_for(path);
// The working file only when it is a regular file: a path that is a directory there
// (a committed symlink to a folder, a file replaced by a folder) has only its blob.
if path.is_file() {
let loaded = self.documents.load_file(path)?;
let loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
}
let bytes = self.with_log_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
Ok(self.documents.detect_encoding(path, &bytes))
Ok(ide_vfs::detect_encoding(&bytes, fallback))
}
/// Current text of `path`: the open buffer when available, else the file on disk.
@@ -2361,11 +2362,8 @@ fn git_metadata_watch(root: &Path, sink: &SharedSink) -> Option<Arc<ide_vcs::Met
.ok()
}
/// Whether a VCS metadata path changed for a reason other than our own status run
/// refreshing an index: the main repository's `.git/index` or a linked worktree's
/// `.git/worktrees/<id>/index`.
fn vcs_path_changed(path: &Path) -> bool {
path.file_name().is_none_or(|n| n != "index") || !ide_vcs::is_own_index_write(path)
!path.ends_with(".git/index") || !ide_vcs::is_own_index_write(path)
}
#[cfg(test)]
@@ -2449,40 +2447,6 @@ mod index_event_tests {
std::fs::remove_file(&index).unwrap();
assert!(vcs_path_changed(&index));
}
#[test]
fn status_write_in_a_linked_worktree_is_suppressed() {
let tmp = tempfile::tempdir().unwrap();
let main = tmp.path().join("main");
std::fs::create_dir(&main).unwrap();
let git = |dir: &std::path::Path, args: &[&str]| {
let output = std::process::Command::new("git")
.current_dir(dir)
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
};
git(&main, &["init", "-q"]);
std::fs::write(main.join("file.txt"), "original\n").unwrap();
git(&main, &["add", "file.txt"]);
git(&main, &["commit", "-qm", "init"]);
let linked = tmp.path().join("linked");
git(&main, &["worktree", "add", "-q", linked.to_str().unwrap()]);
std::fs::File::options()
.write(true)
.open(linked.join("file.txt"))
.unwrap()
.set_modified(std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1))
.unwrap();
let index = main.join(".git/worktrees/linked/index");
let before = std::fs::read(&index).unwrap();
ide_vcs::Repo::discover(&linked).unwrap().unwrap().status().unwrap();
assert_ne!(before, std::fs::read(&index).unwrap(), "status must actually write the index");
assert!(!vcs_path_changed(&index));
assert!(vcs_path_changed(&main.join(".git/worktrees/linked/HEAD")));
}
}
#[cfg(all(test, unix))]
+1 -13
View File
@@ -26,14 +26,13 @@ async fn invoke(peer: &Peer, window: &str, cmd: &str, args: Value) -> Result<Val
const NO_SESSION: i64 = 4242;
fn calls() -> [(&'static str, Value); 5] {
fn calls() -> [(&'static str, Value); 4] {
let object = json!({"generation": 1, "id": 7});
[
("debug_jvm_memory_classes", json!({"session": NO_SESSION})),
("debug_jvm_memory_instances", json!({"session": NO_SESSION, "className": "java.lang.String", "limit": 10})),
("debug_jvm_memory_fields", json!({"session": NO_SESSION, "object": object})),
("debug_jvm_memory_referrers", json!({"session": NO_SESSION, "object": object, "limit": 10})),
("debug_jvm_thread_dump", json!({"session": NO_SESSION})),
]
}
@@ -81,14 +80,3 @@ async fn class_table_is_refused_in_restricted_mode() {
let error = ide_host::ops::debug::debug_jvm_memory_classes(&host, "main", session).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{error:?}");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn thread_dumps_are_refused_in_restricted_mode() {
let (host, _tmp) = host(false);
let session = ide_core::DebugSessionId(NO_SESSION as u32);
let error = ide_host::ops::debug::debug_jvm_thread_dump(&host, "main", session).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{error:?}");
let error =
ide_host::ops::thread_dump::run_jvm_thread_dump(&host, "main", ide_core::RunId(1), None).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{error:?}");
}
-167
View File
@@ -209,11 +209,6 @@ fn write_index(
path.to_string_lossy().into_owned()
}
/// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources).
fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings {
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() }
}
/// Security audit lead 5: an index entry's id and version name the download file,
/// so an entry whose id or version would place it outside the downloads folder
/// is not offered, and nothing is written for it.
@@ -444,168 +439,6 @@ fn serve(body: String) -> String {
})
}
/// A loopback HTTP server that logs every request path it is asked for and answers with
/// `bytes` (a package file); the base URL to put in front of the GitHub one.
fn serve_bytes(bytes: Vec<u8>, paths: Arc<Mutex<Vec<String>>>) -> String {
use std::io::{BufRead, BufReader, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
std::thread::spawn(move || {
for mut stream in listener.incoming().flatten() {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) > 0 {
paths.lock().push(line.trim().to_owned());
}
while reader.read_line(&mut line).unwrap_or(0) > 0 && line != "\r\n" {
line.clear();
}
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
bytes.len()
);
let _ = stream.write_all(&bytes);
}
});
base
}
/// A configured mirror is tried before the official host, and its bytes must still pass the
/// index's digest and the publisher's signature: a mirror only ever carries the download
/// (Tools › Download sources), never the trust root.
#[test]
fn a_mirror_prefix_carries_plugin_packages_and_only_bytes_that_check() {
let f = fixture();
let market = f.work.join("market");
std::fs::create_dir_all(&market).unwrap();
let key = PublisherKey::from_seed([3; 32]);
let (package, mut entry) = signed_hello(&market, "1.0.0", &key, &f.host);
// The download is a GitHub one, which is the only kind a prefix may carry.
entry.download = format!(
"https://github.com/acme/openidea-hello/releases/download/v1.0.0/{}",
package.file_name().unwrap().to_string_lossy()
);
let url = write_index(&market, &key, vec![entry.clone()], vec![], false);
f.host.set_market_url(Some(url));
f.host.refresh_market().unwrap();
// The mirror answers with the real package.
let paths: Arc<Mutex<Vec<String>>> = Arc::default();
let base = serve_bytes(std::fs::read(&package).unwrap(), paths.clone());
f.host.set_downloads(download_sources(&base));
let dir = f.host.download_market_plugin("acme.hello").unwrap();
assert_eq!(f.host.preview_install(&dir).unwrap().version, "1.0.0");
let asked = paths.lock().clone();
assert_eq!(asked.len(), 1, "{asked:?}");
assert!(
asked[0].contains(entry.download.trim_start_matches("https://")),
"the official URL is appended to the prefix unchanged: {asked:?}"
);
// No mirror: the official URL is what is asked for, exactly as before.
f.host.set_downloads(download_sources(""));
assert_eq!(
ide_tools::mirror::candidates(&entry.download, &download_sources("")),
vec![ide_tools::mirror::Candidate { url: entry.download.clone(), mirror: None }]
);
// A download that is not on GitHub is not one a prefix may carry: it stays official.
let mut local = entry.clone();
local.download = package.to_string_lossy().into_owned();
assert_eq!(
ide_tools::mirror::candidates(&local.download, &download_sources(&base)),
vec![ide_tools::mirror::Candidate { url: local.download.clone(), mirror: None }]
);
}
/// A mirror serving a tampered package is a source that fails its checks — and the unpacked
/// bytes it served must not be left behind where the install page reads from.
///
/// The index has no hash of the archive itself (only `package_digest` of the unpacked
/// contents), so the bytes have to be unpacked before they can be checked; the test therefore
/// watches the staging folders, not the archive.
#[test]
fn a_tampered_package_from_a_mirror_is_refused_and_leaves_nothing_behind() {
let f = fixture();
let market = f.work.join("market");
std::fs::create_dir_all(&market).unwrap();
let key = PublisherKey::from_seed([3; 32]);
let (package, mut entry) = signed_hello(&market, "1.0.0", &key, &f.host);
entry.download = format!(
"https://github.com/acme/openidea-hello/releases/download/v1.0.0/{}",
package.file_name().unwrap().to_string_lossy()
);
let url = write_index(&market, &key, vec![entry.clone()], vec![], false);
f.host.set_market_url(Some(url));
f.host.refresh_market().unwrap();
// A package whose manifest was changed after signing: its digest disagrees with the index,
// and it carries no signature at all.
let tampered = {
let dir = f.work.join("tampered-src");
std::fs::create_dir_all(&dir).unwrap();
let unpacked = f.host.unpack_package(&package).unwrap();
copy_dir(&unpacked, &dir.join("pkg"));
let manifest = std::fs::read_to_string(dir.join("pkg/plugin.toml")).unwrap();
std::fs::write(dir.join("pkg/plugin.toml"), manifest.replace("Sample plugin", "Totally safe plugin")).unwrap();
let files = f.host.package_files_of(&dir.join("pkg")).unwrap();
let out = dir.join("tampered.oiplugin");
package::pack(&dir.join("pkg"), &files, &out, None).unwrap();
out
};
let mirror_paths: Arc<Mutex<Vec<String>>> = Arc::default();
let mirror = serve_bytes(std::fs::read(&tampered).unwrap(), mirror_paths.clone());
let downloads = f.plugins_dir.join(".downloads");
// Browsing the package above went through `unpack_package`, which stages a folder of its
// own: clear what that left so the baseline is this attempt's alone.
for dir in staging_dirs(&downloads) {
let _ = std::fs::remove_dir_all(downloads.join(dir));
}
let staging_before = staging_dirs(&downloads);
assert!(staging_before.is_empty(), "{staging_before:?}");
// The mirror answers with the tampered package, and it is the only source configured: the
// download must fail rather than install what the mirror served.
f.host.set_downloads(download_sources(&mirror));
let err = f.host.download_market_plugin("acme.hello").unwrap_err();
assert!(err.message.contains("could not download"), "{}", err.message);
assert!(err.message.contains("does not match the marketplace's entry"), "{}", err.message);
assert_eq!(mirror_paths.lock().len(), 1, "the mirror was asked once");
// Nothing the mirror served stays where the install page reads from, and the staging folder
// of the refused attempt is gone.
assert_eq!(staging_dirs(&downloads), staging_before, "a refused package left its staging folder");
let leftovers: Vec<PathBuf> = std::fs::read_dir(&downloads)
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| p.to_string_lossy().contains("acme.hello"))
.collect();
assert!(leftovers.is_empty(), "a refused package left files behind: {leftovers:?}");
// The official host, serving the real package, still installs.
let official_paths: Arc<Mutex<Vec<String>>> = Arc::default();
let official = serve_bytes(std::fs::read(&package).unwrap(), official_paths.clone());
f.host.set_downloads(download_sources(&official));
let dir = f.host.download_market_plugin("acme.hello").unwrap();
assert_eq!(f.host.preview_install(&dir).unwrap().version, "1.0.0");
assert_eq!(official_paths.lock().len(), 1);
}
/// The staging folders under `<plugins>/.downloads`: one per unpacked package, `<stem>-<pid>`.
fn staging_dirs(downloads: &Path) -> Vec<String> {
let Ok(entries) = std::fs::read_dir(downloads) else { return Vec::new() };
let mut names: Vec<String> = entries
.flatten()
.filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
}
/// An index is read up to the size an index may have, whatever its server says or sends:
/// the marketplace is read again every day, with nobody asking.
#[test]
-216
View File
@@ -81,10 +81,6 @@ impl TestWorkspace {
}
impl PluginWorkspace for TestWorkspace {
fn repositories(&self, root: &Path) -> Result<ide_vcs::Repos, HostError> {
ide_vcs::Repos::discover(root, &|_| false).map_err(|e| HostError::Failed(e.message))
}
fn run_configuration(&self, _client: &str, plugin: &str, id: &str) -> Result<ide_run::RunConfig, HostError> {
if !(plugin == "execution" && matches!(id, "detected" | "dynamic") || plugin == "api14" && id == "tests") {
return Err(HostError::NotFound(id.into()));
@@ -128,7 +124,6 @@ impl PluginWorkspace for TestWorkspace {
max_matches: limit,
context: Default::default(),
include_excluded: false,
skip_large_files: false,
};
let files = Mutex::new(Vec::new());
let summary = ide_search::search(root, &query, &|_| None, cancel, &|file| files.lock().push(file))
@@ -3531,77 +3526,6 @@ fn views_open_project_files_at_a_line() {
assert!(opened.is_none());
}
#[test]
fn views_open_locations_use_invoking_root_and_reject_symlink_escapes() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let other = f._tmp.path().join("project-b");
std::fs::create_dir_all(&other).unwrap();
let other = dunce::canonicalize(other).unwrap();
for root in [&f.project, &other] {
std::fs::write(root.join("jobs.log"), "build\ndeploy\nfailed\n").unwrap();
}
let press = |client: &str, root: Option<&Path>| {
f.take_events();
let inv = Invocation {
client: Some(client.into()),
workspace_root: root.map(Path::to_path_buf),
..Default::default()
};
let result = f.host.view_event("jobs", "jobs", ide_plugin::ViewEvent::Button { id: "log".into() }, inv);
let opened = f
.take_events()
.into_iter()
.filter_map(|(client, event)| match event {
PluginEvent::OpenLocation { plugin_id, path, line, column } => {
Some((client, plugin_id, path.0, line, column))
}
_ => None,
})
.collect::<Vec<_>>();
(result, opened)
};
for (client, root) in [("window-a", &f.project), ("window-b", &other), ("window-a", &f.project)] {
let (result, opened) = press(client, Some(root));
result.unwrap();
assert_eq!(opened, vec![(Some(client.into()), "jobs".into(), root.join("jobs.log"), 2, 4)]);
}
let link = f.project.join("jobs.log");
std::fs::remove_file(&link).unwrap();
let (result, opened) = press("window-a", Some(&f.project));
let error = result.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("no such file"), "{error:?}");
assert!(opened.is_empty());
let (result, opened) = press("window-a", None);
let error = result.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("no project is open"), "{error:?}");
assert!(opened.is_empty());
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
symlink(other.join("jobs.log"), &link).unwrap();
let (result, opened) = press("window-a", Some(&f.project));
let error = result.unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains("outside the project root"), "{error:?}");
assert!(opened.is_empty());
std::fs::remove_file(&link).unwrap();
let target = f.project.join("构建 日志 [ ] # %.log");
std::fs::write(&target, "build\ndeploy\nfailed\n").unwrap();
symlink(target.file_name().unwrap(), &link).unwrap();
let (result, opened) = press("window-a", Some(&f.project));
result.unwrap();
assert_eq!(opened, vec![(Some("window-a".into()), "jobs".into(), target, 2, 4)]);
}
}
#[test]
fn commands_see_the_paths_they_were_run_on() {
let f = fixture(Limits::default());
@@ -3613,36 +3537,6 @@ fn commands_see_the_paths_they_were_run_on() {
assert_eq!(f.run("jobs", "selection", None).unwrap().as_deref(), Some(""));
}
#[test]
fn plugin_reads_the_repository_owning_the_path() {
let f = fixture(Limits::default());
f.install(&sample("jobs"));
let lookup = |path: Option<&str>| f.run("jobs", "repository-at", path);
for name in ["alpha", "beta", "alpha/nested"] {
let dir = f.project.join(name);
std::fs::create_dir_all(&dir).unwrap();
git(&dir, &["init", "-b", "work"]);
git(&dir, &["remote", "add", "origin", &format!("https://user:[email protected]/{name}.git")]);
std::fs::write(dir.join("file.txt"), name).unwrap();
}
assert_eq!(lookup(None).unwrap().unwrap().lines().count(), 3);
for (path, repo, relative) in [
("alpha/file.txt", "alpha", "file.txt"),
("beta/file.txt", "beta", "file.txt"),
("alpha/nested/file.txt", "alpha/nested", "file.txt"),
("alpha/nested", "alpha/nested", ""),
] {
let root = to_ipc(&f.project.join(repo));
let expected = format!("{root}|{relative}|work|[(\"origin\", \"https://example.org/{repo}.git\")]");
assert_eq!(lookup(Some(path)).unwrap().as_deref(), Some(expected.as_str()));
}
assert_eq!(lookup(Some(".")).unwrap(), None);
assert!(lookup(Some("..")).unwrap_err().contains("outside"));
f.host.set_capability("jobs", "vcs.read", false).unwrap();
assert!(lookup(None).unwrap_err().contains("vcs.read"));
assert!(lookup(Some("alpha/file.txt")).unwrap_err().contains("vcs.read"));
}
#[test]
fn vcs_remotes_clipboard_and_open_url() {
let f = fixture(Limits::default());
@@ -4008,68 +3902,6 @@ path = "templates/new.draw"
assert!(f.host.web_page("web-demo", "draw").is_err());
}
#[test]
fn web_pages_embed_only_declared_and_granted_frames() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let pkg = tmp.path().join("frame-demo");
for (path, text) in [
("hall/index.html", "<iframe src=\"https://play.games.test:8443/room\"></iframe>"),
("hall/rules.html", "<p>rules</p>"),
("hall/app.js", "console.log(1)"),
("panel/index.html", "<p>panel</p>"),
] {
std::fs::create_dir_all(pkg.join(path).parent().unwrap()).unwrap();
std::fs::write(pkg.join(path), text).unwrap();
}
std::fs::write(
pkg.join("plugin.toml"),
r#"id = "frame-demo"
name = "Frame Demo"
version = "1.0.0"
engines.openidea = "^1.16"
[capabilities]
optional = ["net:example.com", "net:*.games.test"]
[[contributes.views]]
id = "hall"
title = "Hall"
web = "hall/index.html"
frames = ["https://example.com/", "https://play.games.test:8443", "https://example.com"]
[[contributes.views]]
id = "panel"
title = "Panel"
web = "panel/index.html"
"#,
)
.unwrap();
let info = f.install(&pkg);
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
assert_eq!(
f.host.ui_items("views").iter().find(|v| v.decl["id"] == "hall").unwrap().decl["frames"],
serde_json::json!(["https://example.com", "https://play.games.test:8443"])
);
let page = f.host.web_page("frame-demo", "hall").unwrap();
let rev = page.path.strip_prefix("frame-demo/").unwrap().split_once('/').unwrap().0.to_owned();
let frames = |path: &str| f.host.web_file("frame-demo", &format!("{rev}/{path}")).unwrap().frames;
let both = Some(vec!["https://example.com".to_owned(), "https://play.games.test:8443".to_owned()]);
// Every page in the declaring view's directory, not its other files nor another view's pages.
assert_eq!(frames("hall/index.html"), both);
assert_eq!(frames("hall/rules.html"), both);
assert_eq!(frames("hall/app.js"), None);
assert_eq!(frames("panel/index.html"), None);
// Only what the user granted: declining a host takes it out of the policy.
f.host.set_capability("frame-demo", "net:example.com", false).unwrap();
assert_eq!(frames("hall/index.html"), Some(vec!["https://play.games.test:8443".to_owned()]));
f.host.set_capability("frame-demo", "net:*.games.test", false).unwrap();
assert_eq!(frames("hall/index.html"), Some(Vec::new()));
f.host.set_capability("frame-demo", "net:example.com", true).unwrap();
assert_eq!(frames("hall/index.html"), Some(vec!["https://example.com".to_owned()]));
}
#[test]
fn file_icons_without_patterns_require_api_1_8_and_project_assets() {
let f = fixture(Limits::default());
@@ -5454,34 +5286,6 @@ fn project_notifications_go_to_a_window_of_that_project_only() {
assert_eq!(f.status("jobs"), PluginStatus::Active);
}
#[test]
fn file_prompts_return_the_path_from_the_calling_window_without_a_capability() {
use ide_plugin::{PluginFileFilter, Prompt};
let f = fixture(Limits::default());
f.install(&sample("jobs"));
f.host.set_capability("jobs", "project.read", false).unwrap();
for name in [None, Some("result.parquet")] {
let (result, prompt) = run_and_answer(&f, "pick-file", name, Some(&["C:/data/chosen.parquet"]), Duration::ZERO);
assert_eq!(result.unwrap().as_deref(), Some("C:/data/chosen.parquet"));
assert_eq!(
prompt,
Prompt::PickFile {
title: "Data file".into(),
save: name.is_some(),
name: name.map(str::to_owned),
filters: vec![PluginFileFilter { name: "Parquet".into(), extensions: vec!["parquet".into()] }],
}
);
}
// A suggested name is only a file name, never a directory to start in.
let (_, prompt) =
run_and_answer(&f, "pick-file", Some("/etc/out.parquet"), Some(&["C:/data/x.parquet"]), Duration::ZERO);
assert!(matches!(&prompt, Prompt::PickFile { name: Some(n), .. } if n == "out.parquet"), "{prompt:?}");
assert_eq!(run_and_answer(&f, "pick-file", None, None, Duration::ZERO).0.unwrap(), None);
assert!(run_and_answer(&f, "pick-file", None, Some(&["relative"]), Duration::ZERO).0.is_err());
assert!(f.host.run_command("jobs", "pick-file", None, Invocation::default()).is_err());
}
#[test]
fn directory_prompts_and_project_requests_use_the_calling_window_without_a_capability() {
use ide_plugin::Prompt;
@@ -6990,26 +6794,6 @@ fn api14_stage3_terminal_calls_are_denied_without_process_grants() {
assert!(f.run("execution", "terminal", None).unwrap_err().contains("not granted"));
}
/// API 1.15: a plugin pushes line-end labels whose hover is Markdown, and clears them.
#[test]
fn markdown_decorations_publish_a_hover_card_and_clear() {
let f = fixture(Limits::default());
f.install(&sample("decorations"));
f.run("decorations", "publish", Some("src/notes.txt")).unwrap();
let sets = f.host.decoration_sets();
let set = &sets["decorations"][0];
assert_eq!((set.set_id.as_str(), set.tree), ("example", false));
assert_eq!(set.items.len(), 1);
assert_eq!(set.items[0].style, "highlight");
assert_eq!(set.items[0].after.as_deref(), Some(" + model-x"));
assert_eq!(
set.items[0].markdown_hover.as_deref(),
Some("**model-x** generated this line\n\n- prompt: add a greeting")
);
f.run("decorations", "clear", None).unwrap();
assert!(f.host.decoration_sets()["decorations"].is_empty());
}
// ─── Project window groups ────────────────────────────────────────────────────
// A group's container root holds only `.openidea` metadata; the files live in
// the member projects. The plugin surface reaches them like the editor and the
-2
View File
@@ -40,7 +40,6 @@ async fn find(host: &Host, paths: Vec<PathBuf>, pattern: &str) -> Vec<ide_search
max_matches: 0,
context: Default::default(),
include_excluded: false,
skip_large_files: false,
},
ide_host::ops::Channel::new(move |event| {
if let search::SearchEvent::File { file } = event {
@@ -162,7 +161,6 @@ async fn properties_search_git_and_document_coordinates_agree() {
max_matches: 0,
context: Default::default(),
include_excluded: false,
skip_large_files: false,
};
search::replace_in_files(
&host,
+13 -68
View File
@@ -1,20 +1,16 @@
mod common;
use ide_core::{ChangeSet, TextChange};
use ide_host::{Host, Project, ops::vcs};
use std::{
path::{Path, PathBuf},
process::Command,
sync::Arc,
time::Duration,
};
use ide_host::{Host, ops::vcs};
use std::{path::Path, process::Command, time::Duration};
fn git(root: &Path, args: &[&str]) {
let out = Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
fn repo() -> (tempfile::TempDir, PathBuf, PathBuf) {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
@@ -24,25 +20,6 @@ fn repo() -> (tempfile::TempDir, PathBuf, PathBuf) {
git(&root, &["config", "user.email", "[email protected]"]);
git(&root, &["config", "commit.gpgsign", "false"]);
git(&root, &["config", "core.autocrlf", "false"]);
(temp, base, root)
}
async fn open(base: &Path, root: &Path) -> (Host, Arc<Project>) {
let host = Host::new(common::host_config(base));
host.trust.decide(root, true, false).unwrap();
let project = host.open_project("main", root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
(host, project)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
let (_temp, base, root) = repo();
let path = root.join("Example.java");
let old = "// 中文注释\nclass Example {\n // 保持不变\n int value = 1;\n}\n";
let original = ide_vfs::encode(old, "gbk", false).unwrap();
@@ -50,7 +27,15 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
std::fs::write(root.join("Utf8.java"), old).unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "GBK Java"]);
let (host, project) = open(&base, &root).await;
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
for _ in 0..500 {
if !project.repos().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let mut defaults = project.documents.file_defaults();
defaults.project_fallback = "gbk".into();
project.documents.set_file_defaults(defaults);
@@ -154,43 +139,3 @@ async fn a_directory_symlink_revision_is_its_target() {
assert_eq!(vcs::vcs_file_mode(&host, "main", link, Some("HEAD".into())).await.unwrap().as_deref(), Some("120000"));
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ascii_properties_keep_utf8_for_vcs_by_default() {
let (_temp, base, root) = repo();
let path = root.join("messages.properties");
std::fs::write(&path, b"greeting=Hello\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "properties"]);
let (host, project) = open(&base, &root).await;
assert_eq!(project.vcs_encoding(&path, None).unwrap().charset, encoding_rs::UTF_8, "working file");
std::fs::remove_file(&path).unwrap();
assert_eq!(project.vcs_encoding(&path, Some("HEAD")).unwrap().charset, encoding_rs::UTF_8, "revision");
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn vcs_labels_ascii_files_like_the_editor() {
let (_temp, base, root) = repo();
std::fs::write(root.join(".editorconfig"), "root = true\n[Utf8.java]\ncharset = utf-8\n").unwrap();
let latin = root.join("Latin.java");
let utf8 = root.join("Utf8.java");
std::fs::write(&latin, b"class Latin {}\n").unwrap();
std::fs::write(&utf8, b"class Utf8 {}\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "ascii"]);
let (host, project) = open(&base, &root).await;
let mut defaults = project.documents.file_defaults();
defaults.project_fallback = "iso-8859-15".into();
project.documents.set_file_defaults(defaults);
let charset = |path: &Path, rev| project.vcs_encoding(path, rev).unwrap().charset;
assert_eq!(charset(&latin, None), encoding_rs::ISO_8859_15, "working file, project encoding");
assert_eq!(charset(&utf8, None), encoding_rs::UTF_8, "working file, .editorconfig charset");
std::fs::remove_file(&latin).unwrap();
std::fs::remove_file(&utf8).unwrap();
assert_eq!(charset(&latin, Some("HEAD")), encoding_rs::ISO_8859_15, "revision, project encoding");
assert_eq!(charset(&utf8, Some("HEAD")), encoding_rs::UTF_8, "revision, .editorconfig charset");
host.close_project("main");
}
-7
View File
@@ -112,7 +112,6 @@ mod tests {
#[test]
fn scan_matches_port_not_first_listener() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pid111", Some(5005));
let _b = fake_jvm(dir.path(), ".java_pid222", Some(6006));
@@ -121,7 +120,6 @@ mod tests {
#[test]
fn scan_returns_none_when_no_port_matches() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pid111", Some(5005));
assert_eq!(find_in(dir.path(), 6006, SECOND, 2 * SECOND, ALL), None);
@@ -129,7 +127,6 @@ mod tests {
#[test]
fn scan_skips_silent_listener_within_budget() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _silent = fake_jvm(dir.path(), ".java_pid111", None);
let _b = fake_jvm(dir.path(), ".java_pid222", Some(6006));
@@ -140,7 +137,6 @@ mod tests {
#[test]
fn scan_gives_up_at_the_budget_even_if_a_query_could_run_longer() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _silent = fake_jvm(dir.path(), ".java_pid111", None);
let started = Instant::now();
@@ -150,7 +146,6 @@ mod tests {
#[test]
fn scan_ignores_non_matching_names() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pidabc", Some(6006));
let _b = fake_jvm(dir.path(), ".java_pid", Some(6006));
@@ -161,7 +156,6 @@ mod tests {
#[test]
fn scan_applies_the_socket_trust_checks() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pid111", Some(6006));
fs::set_permissions(dir.path().join(".java_pid111"), fs::Permissions::from_mode(0o666)).unwrap();
@@ -176,7 +170,6 @@ mod tests {
#[test]
fn scan_never_asks_a_jvm_the_caller_rejects() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let _a = fake_jvm(dir.path(), ".java_pid111", Some(6006));
let offered = std::sync::Mutex::new(Vec::new());
+12 -70
View File
@@ -35,7 +35,16 @@ fn version_from(text: &str) -> Option<JavaVersion> {
pub fn java_version_of(pid: u32) -> Option<JavaVersion> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
version_of_exe(&exe_path(pid)?)
let exe = std::fs::canonicalize(exe_path(pid)?).ok()?;
// `<jdk>/bin/java`, or `<jdk>/jre/bin/java` on JDK 8.
let home = exe.parent()?.parent()?;
// Only climb out of `jre/`, so a JDK without its own `release` cannot pick up an
// unrelated file in a shared parent such as `/usr/lib/jvm`.
let outer = if home.file_name().is_some_and(|n| n == "jre") { home.parent() } else { None };
[Some(home), outer].into_iter().flatten().find_map(|dir| {
let contents = std::fs::read_to_string(dir.join("release")).ok()?;
parse_release(&contents)
})
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
@@ -44,41 +53,13 @@ pub fn java_version_of(pid: u32) -> Option<JavaVersion> {
}
}
#[cfg(any(target_os = "linux", target_os = "macos", test))]
fn version_of_exe(exe: &std::path::Path) -> Option<JavaVersion> {
releases_of(exe).iter().find_map(|release| parse_release(release))
}
/// The `release` files of the JDK whose `java` executable is `exe`, nearest first.
#[cfg(any(target_os = "linux", target_os = "macos", test))]
fn releases_of(exe: &std::path::Path) -> Vec<String> {
let Some(exe) = std::fs::canonicalize(exe).ok() else { return Vec::new() };
// `<jdk>/bin/java`, or `<jdk>/jre/bin/java` on JDK 8.
let Some(home) = exe.parent().and_then(std::path::Path::parent) else { return Vec::new() };
// Only climb out of `jre/`, so a JDK without its own `release` cannot pick up an
// unrelated file in a shared parent such as `/usr/lib/jvm`.
let outer = if home.file_name().is_some_and(|n| n == "jre") { home.parent() } else { None };
[Some(home), outer]
.into_iter()
.flatten()
.filter_map(|dir| std::fs::read_to_string(dir.join("release")).ok())
.collect()
}
/// OpenJ9 (IBM Semeru) answers SIGQUIT by writing a `javacore` file into its working directory
/// instead of opening a listener. Its `release` files name it under varying keys.
#[cfg(any(target_os = "linux", target_os = "macos", test))]
pub(crate) fn is_openj9(exe: &std::path::Path) -> bool {
releases_of(exe).iter().any(|release| release.to_ascii_lowercase().contains("openj9"))
}
#[cfg(target_os = "linux")]
pub(crate) fn exe_path(pid: u32) -> Option<PathBuf> {
fn exe_path(pid: u32) -> Option<PathBuf> {
std::fs::read_link(format!("/proc/{pid}/exe")).ok()
}
#[cfg(target_os = "macos")]
pub(crate) fn exe_path(pid: u32) -> Option<PathBuf> {
fn exe_path(pid: u32) -> Option<PathBuf> {
use std::{ffi::c_void, os::unix::ffi::OsStringExt};
let mut buf = vec![0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
@@ -104,7 +85,6 @@ pub fn wants_listener_flag(jvm_args: &str) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use std::path::{Path, PathBuf};
#[test]
fn release_versions() {
@@ -120,44 +100,6 @@ mod tests {
assert_eq!(parse_vm_version("OpenJDK 64-Bit Server VM version 25.512-b09\nJDK 8.0_512\n").unwrap().major, 8);
}
fn fake_jdk(dir: &Path, java: &str, release: Option<&str>) -> PathBuf {
let exe = dir.join(java);
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, "").unwrap();
if let Some(release) = release {
std::fs::write(dir.join("release"), release).unwrap();
}
exe
}
#[test]
fn version_of_a_jre_falls_back_to_the_jdk_release() {
let root = tempfile::tempdir().unwrap();
let jdk = root.path().join("jdk8");
let exe = fake_jdk(&jdk, "jre/bin/java", Some("JAVA_VERSION=\"1.8.0_512\"\n"));
assert_eq!(version_of_exe(&exe).map(|v| v.major), Some(8));
// A `jre/release` without the version, as some JDK 8 builds ship.
std::fs::write(jdk.join("jre/release"), "IMPLEMENTOR=\"Oracle Corporation\"\n").unwrap();
assert_eq!(version_of_exe(&exe).map(|v| v.major), Some(8));
// Outside `jre/` nothing above the JDK is read.
let lone = fake_jdk(&root.path().join("jdk/x"), "bin/java", Some("IMPLEMENTOR=x\n"));
std::fs::write(root.path().join("jdk/release"), "JAVA_VERSION=\"17\"\n").unwrap();
assert_eq!(version_of_exe(&lone), None);
}
#[test]
fn openj9_is_told_by_its_release_file() {
let root = tempfile::tempdir().unwrap();
let semeru = "IMPLEMENTOR=\"IBM Corporation\"\nJAVA_VERSION=\"21.0.5\"\nJVM_VARIANT=\"Openj9\"\n";
let temurin = "IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"21.0.5\"\n";
let only_build = "JAVA_VERSION=\"17\"\nBUILD_INFO=\"OpenJDK 17 with Eclipse OpenJ9 VM\"\n";
assert!(is_openj9(&fake_jdk(&root.path().join("semeru"), "bin/java", Some(semeru))));
assert!(is_openj9(&fake_jdk(&root.path().join("other-key"), "bin/java", Some(only_build))));
assert!(is_openj9(&fake_jdk(&root.path().join("jdk8"), "jre/bin/java", Some(semeru))));
assert!(!is_openj9(&fake_jdk(&root.path().join("temurin"), "bin/java", Some(temurin))));
assert!(!is_openj9(&fake_jdk(&root.path().join("bare"), "bin/java", None)));
}
#[test]
fn suspended_gate() {
assert!(!histogram_safe_while_suspended(11));
-8
View File
@@ -2,12 +2,8 @@ mod discover;
mod heap_dump;
mod histogram;
mod jvm;
mod listener;
mod properties;
mod socket;
#[cfg(all(test, unix))]
mod test_serial;
mod threads;
pub use discover::find_jvm_by_jdwp_port;
pub use heap_dump::{HeapDumpReply, dump_timeout, heap_dump, heap_dump_command, parse_heap_dump_reply, vm_flags};
@@ -16,9 +12,5 @@ pub use jvm::{
JavaVersion, START_LISTENER_FLAG, histogram_safe_while_suspended, java_version_of, parse_release, parse_vm_version,
wants_listener_flag,
};
pub use listener::{LISTENER_START_TIMEOUT, ensure_listener, is_hotspot};
pub use properties::{jdwp_port, parse_properties};
pub use socket::{AttachError, MAX_OUTPUT, agent_properties, has_listener, jcmd, temp_dir};
pub use threads::{
ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm, thread_print,
};
-395
View File
@@ -1,395 +0,0 @@
use std::time::Duration;
use crate::socket::AttachError;
#[cfg(unix)]
use crate::socket::{check_socket, has_listener, has_listener_at, socket_path, temp_dir};
#[cfg(any(target_os = "linux", target_os = "macos", all(unix, test)))]
use std::time::UNIX_EPOCH;
#[cfg(unix)]
use std::{
fs::{Metadata, OpenOptions},
io,
os::unix::fs::{MetadataExt, OpenOptionsExt},
path::{Path, PathBuf},
time::{Instant, SystemTime},
};
/// Default budget for `ensure_listener`.
pub const LISTENER_START_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(unix)]
const POLL_INTERVAL: Duration = Duration::from_millis(50);
/// True when `pid` is confirmed to be a HotSpot JVM: it has an attach listener, a perf-data
/// file of the current user written since it started, or runs an executable named `java`
/// (`-XX:-UsePerfData` JVMs).
pub fn is_hotspot(pid: u32) -> bool {
#[cfg(unix)]
{
signal_target(pid).is_some() && (has_listener(pid) || has_perf_data(pid) || runs_java(pid))
}
#[cfg(not(unix))]
{
let _ = pid;
false
}
}
/// Opens `pid`'s attach listener if it has none, as the JDK's attach API does: a
/// `.attach_pid<pid>` trigger file, then SIGQUIT. Refuses anything `is_hotspot` does not
/// confirm (`NotAJvm`), because SIGQUIT's default action terminates any other process, and a
/// socket that fails the ownership check (`ForeignListener`).
///
/// Blocks for up to `timeout`. A JVM that ignores attach (`-XX:+DisableAttachMechanism`) still
/// handles the SIGQUIT: it prints a thread dump to its own stdout.
pub fn ensure_listener(pid: u32, timeout: Duration) -> Result<(), AttachError> {
#[cfg(unix)]
{
ensure_listener_at(&socket_path(pid), pid, timeout)
}
#[cfg(not(unix))]
{
let _ = (pid, timeout);
Err(AttachError::Unsupported)
}
}
#[cfg(unix)]
fn ensure_listener_at(socket: &Path, pid: u32, timeout: Duration) -> Result<(), AttachError> {
// `has_listener` reads a socket that fails the trust check as absent; signalling past it
// would leave its owner answering in the JVM's place.
match check_socket(socket) {
Ok(()) => return Ok(()),
Err(AttachError::NoListener) => {}
Err(e) => return Err(e),
}
let Some(target) = signal_target(pid).filter(|_| is_hotspot(pid)) else {
return Err(AttachError::NotAJvm);
};
let deadline = Instant::now() + timeout;
let _trigger = Trigger::create(pid)?;
signal(target, libc::SIGQUIT)?;
loop {
if has_listener_at(socket) {
return Ok(());
}
signal(target, 0)?;
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(AttachError::ListenerDidNotStart);
}
std::thread::sleep(remaining.min(POLL_INTERVAL));
}
}
/// `kill` treats 0 and negative pids as process groups, which would signal the IDE itself.
#[cfg(unix)]
fn signal_target(pid: u32) -> Option<libc::pid_t> {
libc::pid_t::try_from(pid).ok().filter(|p| *p > 0)
}
#[cfg(unix)]
fn signal(pid: libc::pid_t, signal: libc::c_int) -> Result<(), AttachError> {
// SAFETY: kill has no memory preconditions; `pid` is positive, so only that process is targeted.
if unsafe { libc::kill(pid, signal) } == 0 {
return Ok(());
}
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) { Err(AttachError::NoListener) } else { Err(err.into()) }
}
/// `.attach_pid<pid>`, removed on every path out of `ensure_listener`.
#[cfg(unix)]
struct Trigger(PathBuf);
#[cfg(unix)]
impl Trigger {
fn create(pid: u32) -> Result<Self, AttachError> {
let name = format!(".attach_pid{pid}");
// HotSpot looks in its working directory before the temp dir; through /proc that also
// reaches a JVM in another mount namespace.
#[cfg(target_os = "linux")]
let candidates = [PathBuf::from(format!("/proc/{pid}/cwd")).join(&name), temp_dir().join(&name)];
#[cfg(not(target_os = "linux"))]
let candidates = [temp_dir().join(&name)];
let mut failure = None;
for path in candidates {
match create_private(&path) {
Ok(()) => return Ok(Self(path)),
Err(e) => failure = Some(e),
}
}
Err(failure.expect("at least one candidate").into())
}
}
#[cfg(unix)]
impl Drop for Trigger {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
/// `create_new` refuses to follow a symlink planted in a shared directory.
#[cfg(unix)]
fn create_private(path: &Path) -> io::Result<()> {
match OpenOptions::new().write(true).create_new(true).mode(0o600).open(path) {
Ok(_) => Ok(()),
// Left by an attempt that died before its cleanup; nobody else's file is adopted.
Err(e) if e.kind() == io::ErrorKind::AlreadyExists && owned_regular_file(path) => Ok(()),
Err(e) => Err(e),
}
}
#[cfg(unix)]
fn owned_regular_file(path: &Path) -> bool {
std::fs::symlink_metadata(path).is_ok_and(|meta| owned_regular(&meta))
}
#[cfg(unix)]
fn owned_regular(meta: &Metadata) -> bool {
// SAFETY: geteuid has no preconditions and cannot fail.
meta.is_file() && meta.uid() == unsafe { libc::geteuid() }
}
/// `<temp>/hsperfdata_<user>/<pid>`, which HotSpot writes unless run with `-XX:-UsePerfData`.
/// Ownership matters outside macOS, where the directory sits in a shared `/tmp`.
#[cfg(unix)]
fn has_perf_data(pid: u32) -> bool {
let Some(user) = effective_user_name() else { return false };
let path = temp_dir().join(format!("hsperfdata_{user}")).join(pid.to_string());
std::fs::symlink_metadata(path).is_ok_and(|meta| {
owned_regular(&meta) && meta.modified().is_ok_and(|modified| written_since_start(modified, process_start(pid)))
})
}
/// Absorbs the coarser clock of the start time: Linux knows the boot time only to the second.
#[cfg(unix)]
const START_SLACK: Duration = Duration::from_secs(2);
/// A perf-data file older than the process was left by a JVM that died without removing it
/// (SIGKILL) and whose pid was reused. An unknown start time proves nothing.
#[cfg(unix)]
fn written_since_start(modified: SystemTime, started: Option<SystemTime>) -> bool {
started.and_then(|start| start.checked_sub(START_SLACK)).is_some_and(|earliest| modified >= earliest)
}
#[cfg(target_os = "macos")]
fn process_start(pid: u32) -> Option<SystemTime> {
let pid = libc::c_int::try_from(pid).ok()?;
// SAFETY: proc_bsdinfo is plain data; all-zero is a valid value.
let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
// SAFETY: `info` is writable for `size` bytes, the most PROC_PIDTBSDINFO writes.
let written = unsafe { libc::proc_pidinfo(pid, libc::PROC_PIDTBSDINFO, 0, (&raw mut info).cast(), size) };
if written != size {
return None;
}
Some(UNIX_EPOCH + Duration::from_secs(info.pbi_start_tvsec) + Duration::from_micros(info.pbi_start_tvusec))
}
#[cfg(target_os = "linux")]
fn process_start(pid: u32) -> Option<SystemTime> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let system = std::fs::read_to_string("/proc/stat").ok()?;
// SAFETY: sysconf has no preconditions.
let ticks_per_sec = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
start_from_proc(&stat, &system, u64::try_from(ticks_per_sec).ok().filter(|t| *t > 0)?)
}
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn process_start(_pid: u32) -> Option<SystemTime> {
None
}
/// `/proc/<pid>/stat` field 22 is the start in clock ticks since boot; `btime` in `/proc/stat`
/// is the boot time in seconds since the epoch.
#[cfg(any(target_os = "linux", all(unix, test)))]
fn start_from_proc(stat: &str, system: &str, ticks_per_sec: u64) -> Option<SystemTime> {
// The command name (field 2) may contain spaces and parentheses; the fields after it start at 3.
let ticks: u64 = stat.rsplit_once(')')?.1.split_whitespace().nth(22 - 3)?.parse().ok()?;
let boot: u64 = system.lines().find_map(|line| line.strip_prefix("btime "))?.trim().parse().ok()?;
let since_boot = Duration::from_millis(ticks.checked_mul(1000)? / ticks_per_sec);
Some(UNIX_EPOCH + Duration::from_secs(boot) + since_boot)
}
/// HotSpot names the perf-data directory after the effective user's passwd entry.
#[cfg(unix)]
fn effective_user_name() -> Option<String> {
let mut buf = vec![0 as libc::c_char; 4096];
// SAFETY: passwd is plain data; all-zero is a valid value.
let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
let mut result: *mut libc::passwd = std::ptr::null_mut();
// SAFETY: every pointer refers to a live local buffer of the stated size.
let rc = unsafe { libc::getpwuid_r(libc::geteuid(), &mut pwd, buf.as_mut_ptr(), buf.len(), &mut result) };
if rc != 0 || result.is_null() || pwd.pw_name.is_null() {
return None;
}
// SAFETY: on success `pw_name` is a NUL-terminated string inside `buf`.
let name = unsafe { std::ffi::CStr::from_ptr(pwd.pw_name) };
Some(name.to_string_lossy().into_owned())
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn runs_java(pid: u32) -> bool {
crate::jvm::exe_path(pid)
.is_some_and(|exe| exe.file_name().is_some_and(|name| name == "java") && !crate::jvm::is_openj9(&exe))
}
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn runs_java(_pid: u32) -> bool {
false
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::process::Command;
/// Kills the child even when an assertion fails.
struct ChildGuard(std::process::Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn spawn_sleep() -> ChildGuard {
ChildGuard(Command::new("sleep").arg("30").spawn().expect("spawn sleep"))
}
#[test]
fn is_hotspot_false_for_sleep() {
let _serial = crate::test_serial::hold();
let sleep = spawn_sleep();
assert!(!is_hotspot(sleep.0.id()));
}
/// `sleep` copied to `<jdk>/bin/java`: confirmed HotSpot by its name alone, unless the
/// JDK's `release` file says OpenJ9.
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn sleep_as_java(release: &str) -> (tempfile::TempDir, ChildGuard) {
let jdk = tempfile::tempdir().unwrap();
let java = jdk.path().join("bin/java");
std::fs::create_dir(java.parent().unwrap()).unwrap();
let sleep = ["/bin/sleep", "/usr/bin/sleep"].into_iter().find(|p| Path::new(p).exists()).expect("sleep");
std::fs::copy(sleep, &java).unwrap();
std::fs::write(jdk.path().join("release"), release).unwrap();
let child = ChildGuard(Command::new(&java).arg("30").spawn().expect("spawn java"));
(jdk, child)
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn an_executable_named_java_is_hotspot_unless_its_jdk_is_openj9() {
let _serial = crate::test_serial::hold();
let (_jdk, hotspot) = sleep_as_java("IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"21.0.5\"\n");
assert!(is_hotspot(hotspot.0.id()));
let (_jdk, openj9) = sleep_as_java("IMPLEMENTOR=\"IBM Corporation\"\nJVM_VARIANT=\"Openj9\"\n");
let pid = openj9.0.id();
assert!(!is_hotspot(pid));
let result = ensure_listener(pid, Duration::from_millis(500));
assert!(matches!(result, Err(AttachError::NotAJvm)), "{result:?}");
}
#[test]
fn ensure_listener_refuses_a_non_jvm() {
let _serial = crate::test_serial::hold();
let sleep = spawn_sleep();
let pid = sleep.0.id();
let result = ensure_listener(pid, Duration::from_millis(500));
assert!(matches!(result, Err(AttachError::NotAJvm)), "{result:?}");
// SAFETY: signal 0 only checks that the pid exists.
assert_eq!(unsafe { libc::kill(pid as libc::pid_t, 0) }, 0, "the process must still be alive");
}
#[test]
fn foreign_socket_is_refused_without_a_signal() {
let _serial = crate::test_serial::hold();
use std::os::unix::{fs::PermissionsExt, net::UnixListener};
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join(".java_pid1");
let _listener = UnixListener::bind(&socket).unwrap();
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o666)).unwrap();
let sleep = spawn_sleep();
let pid = sleep.0.id();
let result = ensure_listener_at(&socket, pid, Duration::from_millis(500));
assert!(matches!(result, Err(AttachError::ForeignListener)), "{result:?}");
assert!(!temp_dir().join(format!(".attach_pid{pid}")).exists());
// SAFETY: signal 0 only checks that the pid exists.
assert_eq!(unsafe { libc::kill(pid as libc::pid_t, 0) }, 0, "the process must still be alive");
}
#[test]
fn perf_data_counts_only_when_written_since_the_process_started() {
let start = UNIX_EPOCH + Duration::from_secs(1_700_000_000);
assert!(!written_since_start(start - Duration::from_secs(60), Some(start)));
assert!(!written_since_start(start - Duration::from_secs(3), Some(start)));
assert!(written_since_start(start - Duration::from_secs(1), Some(start)));
assert!(written_since_start(start + Duration::from_secs(5), Some(start)));
assert!(!written_since_start(start + Duration::from_secs(5), None));
}
#[test]
fn our_own_start_time_is_known_and_recent() {
let start = process_start(std::process::id()).expect("start time of this process");
let age = SystemTime::now().duration_since(start).expect("started in the past");
assert!(age < Duration::from_secs(24 * 3600), "{age:?}");
}
#[test]
fn start_time_from_proc_files() {
let stat = "1234 (my (odd) proc) S 1 1234 1234 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 5000 1000 50";
let system = "cpu 1 2 3
btime 1700000000
processes 9
";
let start = start_from_proc(stat, system, 100).unwrap();
assert_eq!(start, UNIX_EPOCH + Duration::from_secs(1_700_000_050));
assert_eq!(
start_from_proc(
stat,
"cpu 1 2 3
",
100
),
None
);
assert_eq!(start_from_proc("1234 (short) S 1", system, 100), None);
}
#[test]
fn process_group_pids_are_never_signalled() {
for pid in [0, u32::MAX, i32::MAX as u32 + 1] {
assert!(!is_hotspot(pid), "{pid}");
let result = ensure_listener(pid, Duration::from_millis(100));
assert!(matches!(result, Err(AttachError::NotAJvm)), "{pid}: {result:?}");
}
}
#[test]
fn trigger_file_is_private_and_removed_on_drop() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".attach_pid1");
create_private(&path).unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
create_private(&path).expect("our own leftover is reused");
drop(Trigger(path.clone()));
assert!(!path.exists());
}
#[test]
fn trigger_file_refuses_a_planted_symlink() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("elsewhere");
let path = dir.path().join(".attach_pid1");
std::os::unix::fs::symlink(&target, &path).unwrap();
assert!(create_private(&path).is_err());
assert!(!target.exists());
}
}
+2 -17
View File
@@ -28,10 +28,6 @@ pub enum AttachError {
Unsupported,
#[error("the JVM has no attach listener")]
NoListener,
#[error("the process is not a HotSpot JVM")]
NotAJvm,
#[error("the JVM did not open its attach listener; it may run with -XX:+DisableAttachMechanism")]
ListenerDidNotStart,
#[error("the attach socket is not private to the current user")]
ForeignListener,
#[error("the attach listener refused the connection")]
@@ -102,14 +98,14 @@ pub fn jcmd(pid: u32, command_line: &str, timeout: Duration) -> Result<String, A
}
#[cfg(unix)]
pub(crate) fn socket_path(pid: u32) -> PathBuf {
fn socket_path(pid: u32) -> PathBuf {
temp_dir().join(format!(".java_pid{pid}"))
}
/// Same trust rule as the JDK's `VirtualMachineImpl`: only talk to a socket we own and
/// nobody else can reach, otherwise another user could answer in the JVM's place.
#[cfg(unix)]
pub(crate) fn check_socket(path: &Path) -> Result<(), AttachError> {
fn check_socket(path: &Path) -> Result<(), AttachError> {
// No symlink following: in a sticky, world-writable /tmp anyone can plant a symlink to a
// socket we own, pass this check, then re-point it before connect.
let meta = match std::fs::symlink_metadata(path) {
@@ -401,7 +397,6 @@ mod tests {
#[test]
fn sends_v1_jcmd_request_and_returns_body() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let server = serve_once(listener, b"0\nhello\n");
@@ -412,7 +407,6 @@ mod tests {
#[test]
fn sends_v1_agent_properties_request_and_parses_body() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let server = serve_once(listener, b"0\n#Mon\nsun.jdwp.listenerAddress=dt_socket\\:64390\n");
@@ -423,7 +417,6 @@ mod tests {
#[test]
fn nonzero_code_is_command_error() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let _server = serve_once(listener, b"-1\njava.lang.IllegalArgumentException: Unknown diagnostic command");
@@ -438,7 +431,6 @@ mod tests {
#[test]
fn jcmd_times_out_when_listener_never_answers() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let (release, hold) = mpsc::channel::<()>();
@@ -456,7 +448,6 @@ mod tests {
#[test]
fn stale_socket_maps_to_refused() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
drop(listener);
@@ -467,7 +458,6 @@ mod tests {
#[test]
fn rejects_socket_with_group_or_other_permissions() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, _listener) = bind_private(dir.path());
fs::set_permissions(&path, fs::Permissions::from_mode(0o666)).unwrap();
@@ -478,7 +468,6 @@ mod tests {
#[test]
fn output_over_limit_is_too_large() {
let _serial = crate::test_serial::hold();
let (mut reader, mut writer) = UnixStream::pair().unwrap();
writer.write_all(b"0\n").unwrap();
writer.write_all(&[b'x'; 100]).unwrap();
@@ -490,7 +479,6 @@ mod tests {
#[test]
fn symlink_to_our_own_private_socket_is_rejected() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (target, _listener) = bind_private(dir.path());
let link = dir.path().join(".java_pid2");
@@ -503,7 +491,6 @@ mod tests {
#[test]
fn peer_uid_check_passes_for_our_own_listener() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, listener) = bind_private(dir.path());
let stream = connect_before(&path, Instant::now() + Duration::from_secs(1)).unwrap();
@@ -513,7 +500,6 @@ mod tests {
#[test]
fn connect_before_maps_missing_socket_to_no_listener() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let deadline = Instant::now() + Duration::from_secs(1);
let missing = connect_before(&dir.path().join("nope"), deadline);
@@ -524,7 +510,6 @@ mod tests {
/// connect must give up within its deadline instead of hanging.
#[test]
fn connect_before_gives_up_on_a_full_backlog() {
let _serial = crate::test_serial::hold();
let dir = tempfile::tempdir().unwrap();
let (path, _listener) = bind_private(dir.path());
let mut held = Vec::new();
-10
View File
@@ -1,10 +0,0 @@
use std::sync::{Mutex, MutexGuard};
static SERIAL: Mutex<()> = Mutex::new(());
/// Held for a whole test that binds or accepts on a socket or spawns a process. macOS sets
/// close-on-exec on a new socket only after `socket()` returns, so a child spawned meanwhile by
/// another test inherits the listening fd and keeps a dropped listener connectable.
pub fn hold() -> MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
-281
View File
@@ -1,281 +0,0 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::process::Command;
use std::time::Duration;
use crate::listener::is_hotspot;
use crate::socket::{AttachError, jcmd};
/// Default budget for `thread_print`; a dump of a healthy JVM takes milliseconds, so this only
/// bounds a JVM stuck at a safepoint.
pub const THREAD_DUMP_TIMEOUT: Duration = Duration::from_secs(10);
/// System property the IDE adds to a run's JVM so it can be found even when the build tool
/// forks it outside the run's process tree (a Gradle daemon).
pub const RUN_TOKEN_PROPERTY: &str = "-Dopenidea.run.token=";
/// Gradle's own JVMs: the client that waits for the build, the daemon that runs it, and the
/// workers and Kotlin compile daemon it forks (beside the application under `--no-daemon`).
/// None is the application, even when it is the only JVM under the run's root.
const GRADLE_JVM_MARKERS: [&str; 5] = [
"org.gradle.wrapper.GradleWrapperMain",
"org.gradle.launcher.GradleMain",
"org.gradle.launcher.daemon",
"org.gradle.process.internal.worker.GradleWorkerMain",
"org.jetbrains.kotlin.daemon.KotlinCompileDaemon",
];
/// `Thread.print -l` also lists the owned `java.util.concurrent` locks, which deadlock
/// reports need.
pub fn thread_print(pid: u32, timeout: Duration) -> Result<String, AttachError> {
jcmd(pid, "Thread.print -l", timeout)
}
#[derive(Debug, Clone, PartialEq)]
pub struct ProcEntry {
pub pid: u32,
pub ppid: u32,
/// The full argv joined by spaces, as `ps` prints it.
pub command: String,
}
/// Every process of the machine; empty when `ps` is unavailable.
pub fn process_table() -> Vec<ProcEntry> {
let Ok(out) = Command::new("ps").args(["-A", "-o", "pid=,ppid=,command="]).output() else {
return Vec::new();
};
String::from_utf8_lossy(&out.stdout).lines().filter_map(parse_ps_line).collect()
}
fn parse_ps_line(line: &str) -> Option<ProcEntry> {
let (pid, rest) = line.trim_start().split_once(char::is_whitespace)?;
let (ppid, command) = rest.trim_start().split_once(char::is_whitespace)?;
Some(ProcEntry { pid: pid.parse().ok()?, ppid: ppid.parse().ok()?, command: command.trim().to_string() })
}
/// The JVM that runs a run configuration: the deepest HotSpot JVM below `root` that is not
/// Gradle's own (a Maven `spring-boot:run` forks the application under the Maven JVM), else
/// the one carrying `token` (a Gradle daemon forks it outside the run's tree, which then holds
/// only the Gradle client). Ties go to the highest pid.
pub fn select_run_jvm(
table: &[ProcEntry],
root: u32,
token: Option<&str>,
is_hotspot: impl Fn(u32) -> bool,
) -> Option<u32> {
// The tree first: a token is only as unique as the configuration and project it names.
deepest_jvm_in_tree(table, root, &is_hotspot).or_else(|| {
let wanted = format!("{RUN_TOKEN_PROPERTY}{}", token.filter(|token| !token.is_empty())?);
table
.iter()
// The Gradle client carries the token too: a delegated run passes it on its command line.
.filter(|entry| {
entry.command.split_whitespace().any(|arg| arg == wanted)
&& !is_gradle_jvm(&entry.command)
&& is_hotspot(entry.pid)
})
.map(|entry| entry.pid)
.max()
})
}
/// Confirmed HotSpot (`is_hotspot`) and, by its command line, not one of Gradle's own JVMs.
pub fn is_application_jvm(pid: u32) -> bool {
is_hotspot(pid) && !command_line(pid).is_some_and(|command| is_gradle_jvm(&command))
}
fn command_line(pid: u32) -> Option<String> {
let out = Command::new("ps").args(["-o", "command=", "-p", &pid.to_string()]).output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
fn is_gradle_jvm(command: &str) -> bool {
GRADLE_JVM_MARKERS.iter().any(|marker| command.contains(marker))
}
fn deepest_jvm_in_tree(table: &[ProcEntry], root: u32, is_hotspot: &dyn Fn(u32) -> bool) -> Option<u32> {
let mut children: HashMap<u32, Vec<&ProcEntry>> = HashMap::new();
for entry in table {
children.entry(entry.ppid).or_default().push(entry);
}
let by_pid: HashMap<u32, &ProcEntry> = table.iter().map(|entry| (entry.pid, entry)).collect();
let mut seen = HashSet::from([root]);
let mut queue = VecDeque::from([(root, 0usize)]);
let mut best: Option<(usize, u32)> = None;
while let Some((pid, depth)) = queue.pop_front() {
let is_app_jvm = by_pid.get(&pid).is_some_and(|entry| !is_gradle_jvm(&entry.command)) && is_hotspot(pid);
if is_app_jvm && best.is_none_or(|found| (depth, pid) > found) {
best = Some((depth, pid));
}
for child in children.get(&pid).into_iter().flatten() {
if seen.insert(child.pid) {
queue.push_back((child.pid, depth + 1));
}
}
}
best.map(|(_, pid)| pid)
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(pid: u32, ppid: u32, command: &str) -> ProcEntry {
ProcEntry { pid, ppid, command: command.to_string() }
}
fn any_pid(_: u32) -> bool {
true
}
/// The shell at pid 10 is not a JVM, as the real `is_hotspot` would say.
fn not_the_shell(pid: u32) -> bool {
pid != 10
}
fn gradle_run() -> Vec<ProcEntry> {
vec![
entry(10, 1, "/bin/zsh"),
entry(11, 10, "/jdk/bin/java -classpath wrapper.jar org.gradle.wrapper.GradleWrapperMain run"),
entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"),
]
}
#[test]
fn select_falls_back_to_the_token_when_the_tree_holds_only_gradle() {
let table = gradle_run();
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(50));
assert_eq!(select_run_jvm(&table, 10, Some("cfg-2"), not_the_shell), None);
}
#[test]
fn select_skips_the_gradle_client_that_carries_the_token() {
let client = |pid| {
entry(
pid,
10,
"/jdk/bin/java -Dopenidea.run.token=cfg-1 -classpath wrapper.jar org.gradle.wrapper.GradleWrapperMain run",
)
};
let app = entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main");
for client_pid in [11, 99] {
let table = vec![entry(10, 1, "/bin/zsh"), client(client_pid), app.clone()];
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(50), "client {client_pid}");
}
// Only the client carries it: the tree rules apply, which skip the client too.
let table = vec![entry(10, 1, "/bin/zsh"), client(11), entry(12, 11, "/jdk/bin/java -cp app Main")];
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(12));
let alone = vec![entry(10, 1, "/bin/zsh"), client(11)];
assert_eq!(select_run_jvm(&alone, 10, Some("cfg-1"), not_the_shell), None);
let launcher = entry(13, 10, "java -Dopenidea.run.token=cfg-1 org.gradle.launcher.GradleMain run");
assert_eq!(select_run_jvm(&[entry(10, 1, "sh"), launcher], 10, Some("cfg-1"), not_the_shell), None);
}
#[test]
fn select_prefers_the_run_tree_over_a_token_elsewhere() {
// Another worktree's delegated JVM carries the same token as this plain run.
let table = vec![
entry(10, 1, "/bin/zsh"),
entry(11, 10, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"),
entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"),
];
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(11));
}
#[test]
fn select_picks_deepest_jvm_in_tree() {
let table = vec![
entry(10, 1, "/bin/zsh"),
entry(11, 10, "/jdk/bin/java -classpath maven.jar org.codehaus.plexus.classworlds.launcher.Launcher"),
entry(12, 11, "/jdk/bin/java -cp app Main"),
];
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12));
}
#[test]
fn select_ignores_token_substring() {
let table = vec![entry(50, 1, "java -Dopenidea.run.token=cfg-10 -cp app Main")];
assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), any_pid), None);
assert_eq!(select_run_jvm(&table, 10, Some("cfg-10"), any_pid), Some(50));
}
#[test]
fn select_none_when_tree_has_no_jvm() {
let table = vec![entry(10, 1, "/bin/zsh"), entry(11, 10, "/bin/sleep 5"), entry(12, 1, "java -cp app Main")];
assert_eq!(select_run_jvm(&table, 10, None, |pid| pid == 12), None);
}
#[test]
fn select_treats_an_empty_token_as_no_token() {
// "-Dopenidea.run.token=" with nothing after it must not tag every such process.
let table =
vec![entry(50, 1, "java -Dopenidea.run.token= -cp app Main"), entry(10, 1, "sh"), entry(11, 10, "java a")];
assert_eq!(select_run_jvm(&table, 10, Some(""), not_the_shell), Some(11));
}
#[test]
fn select_takes_the_highest_pid_among_equally_deep_jvms() {
let table = vec![entry(10, 1, "sh"), entry(11, 10, "java a"), entry(12, 10, "java b")];
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12));
let tagged = vec![entry(5, 1, "java -Dopenidea.run.token=t"), entry(7, 1, "java -Dopenidea.run.token=t")];
assert_eq!(select_run_jvm(&tagged, 10, Some("t"), any_pid), Some(7));
}
#[test]
fn select_skips_tagged_processes_that_are_not_a_hotspot_jvm() {
let table = vec![entry(50, 1, "native -Dopenidea.run.token=t"), entry(10, 1, "sh"), entry(11, 10, "java a")];
assert_eq!(select_run_jvm(&table, 10, Some("t"), |pid| pid == 11), Some(11));
}
#[test]
fn select_includes_the_root_itself() {
let table = vec![entry(10, 1, "java -cp app Main")];
assert_eq!(select_run_jvm(&table, 10, None, any_pid), Some(10));
}
#[test]
fn select_survives_a_parent_cycle() {
let table = vec![entry(10, 11, "sh"), entry(11, 10, "java a")];
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(11));
}
#[test]
fn select_skips_gradle_workers_and_the_kotlin_daemon() {
// `--no-daemon`: the build's helper JVMs sit beside the application in the run's tree.
let worker = "/jdk/bin/java -cp gradle-worker.jar worker.org.gradle.process.internal.worker.GradleWorkerMain 'Gradle Worker Daemon 1'";
let kotlin = "/jdk/bin/java -cp kotlin-compiler-embeddable.jar org.jetbrains.kotlin.daemon.KotlinCompileDaemon --daemon-runFilesPath x";
let build =
entry(11, 10, "/jdk/bin/java -cp gradle-launcher.jar org.gradle.launcher.GradleMain --no-daemon run");
let table = vec![
entry(10, 1, "/bin/zsh"),
build.clone(),
entry(12, 11, "/jdk/bin/java -cp app Main"),
entry(20, 11, worker),
entry(21, 11, kotlin),
];
assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12));
let helpers = vec![entry(10, 1, "/bin/zsh"), build, entry(20, 11, worker), entry(21, 11, kotlin)];
assert_eq!(select_run_jvm(&helpers, 10, None, not_the_shell), None);
}
#[cfg(unix)]
#[test]
fn command_line_of_a_process_and_a_sleep_is_no_application_jvm() {
let mut sleep = Command::new("sleep").arg("30").spawn().expect("spawn sleep");
let pid = sleep.id();
let (command, application) = (command_line(pid), is_application_jvm(pid));
let _ = sleep.kill();
let _ = sleep.wait();
assert_eq!(command.as_deref(), Some("sleep 30"));
assert!(!application);
assert_eq!(command_line(pid), None, "an ended process has no command line");
}
#[test]
fn parses_ps_lines_with_arguments_and_padding() {
let parsed = parse_ps_line(" 123 45 /jdk/bin/java -Dk=v -cp a b").unwrap();
assert_eq!(parsed, entry(123, 45, "/jdk/bin/java -Dk=v -cp a b"));
assert_eq!(parse_ps_line(" PID PPID COMMAND"), None);
assert_eq!(parse_ps_line(" 7 1"), None);
}
}
+6 -82
View File
@@ -8,31 +8,11 @@ use std::sync::mpsc;
use std::time::{Duration, Instant};
use ide_jvm_attach::{
AttachError, HeapDumpReply, LISTENER_START_TIMEOUT, THREAD_DUMP_TIMEOUT, agent_properties, ensure_listener,
find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, histogram_safe_while_suspended, is_hotspot,
java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, parse_release, process_table,
select_run_jvm, temp_dir, thread_print, vm_flags,
AttachError, HeapDumpReply, agent_properties, find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command,
histogram_safe_while_suspended, java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply,
parse_release, vm_flags,
};
/// Two threads that each hold one monitor and wait for the other's after 200 ms.
const DEADLOCK_JAVA: &str = r#"
public class Deadlock {
static final Object A = new Object(), B = new Object();
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
}
public static void main(String[] args) {
new Thread(() -> { synchronized (A) { sleep(200); synchronized (B) { } } }, "sync-1").start();
new Thread(() -> { synchronized (B) { sleep(200); synchronized (A) { } } }, "sync-2").start();
System.out.println("READY");
System.out.flush();
sleep(60_000);
}
}
"#;
const MAIN_JAVA: &str = r#"
import java.util.ArrayList;
import java.util.List;
@@ -188,19 +168,15 @@ fn finds_a_real_jvm_by_its_jdwp_port() {
/// Compiles `MAIN_JAVA` with the `javac` next to `java`, since JDK 8 has no source launcher.
fn launch_main(java: &Path, dir: &Path, jvm_args: &[&str]) -> JvmGuard {
launch_class(java, dir, "Main", MAIN_JAVA, jvm_args)
}
fn launch_class(java: &Path, dir: &Path, class: &str, source_text: &str, jvm_args: &[&str]) -> JvmGuard {
let source = dir.join(format!("{class}.java"));
std::fs::write(&source, source_text).unwrap();
let source = dir.join("Main.java");
std::fs::write(&source, MAIN_JAVA).unwrap();
let status = Command::new(java.with_file_name("javac")).arg("-d").arg(dir).arg(&source).status().expect("javac");
assert!(status.success(), "javac failed");
let child = Command::new(java)
.args(jvm_args)
.arg("-cp")
.arg(dir)
.arg(class)
.arg("Main")
.current_dir(dir)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -334,55 +310,3 @@ fn dumps_while_suspended() {
assert!(guard.0.try_wait().unwrap().is_none(), "the JVM exited after resume");
vm_flags(pid, Duration::from_secs(10)).expect("the attach listener answers after resume");
}
#[test]
#[ignore = "needs a real JDK >= 8: set OPENIDEA_TEST_JAVA to its bin/java"]
fn ensure_listener_starts_a_listener_on_demand() {
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
return;
};
let dir = tempfile::tempdir().unwrap();
let mut guard = launch_main(&java, dir.path(), &[]);
let pid = guard.0.id();
wait_for_ready(&output_lines(&mut guard.0));
assert!(!has_listener(pid), "the JVM opened its listener without being asked");
assert!(is_hotspot(pid));
let started = Instant::now();
ensure_listener(pid, LISTENER_START_TIMEOUT).unwrap();
eprintln!("on-demand listener for pid {pid} in {:?}", started.elapsed());
assert!(has_listener(pid));
jcmd(pid, "VM.version", Duration::from_secs(10)).expect("the new listener answers");
let trigger = format!(".attach_pid{pid}");
for parent in [temp_dir(), dir.path().to_path_buf()] {
assert!(!parent.join(&trigger).exists(), "trigger file left in {parent:?}");
}
ensure_listener(pid, LISTENER_START_TIMEOUT).expect("an open listener is accepted as is");
}
#[test]
#[ignore = "needs a real JDK >= 8: set OPENIDEA_TEST_JAVA to its bin/java"]
fn thread_print_reports_a_deadlock() {
let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else {
eprintln!("OPENIDEA_TEST_JAVA is not set; skipping");
return;
};
let dir = tempfile::tempdir().unwrap();
let mut guard = launch_class(&java, dir.path(), "Deadlock", DEADLOCK_JAVA, &["-XX:+StartAttachListener"]);
let pid = guard.0.id();
wait_for_ready(&output_lines(&mut guard.0));
wait_for_listener(pid);
// The threads take their first monitor at once and the second after 200 ms.
std::thread::sleep(Duration::from_secs(1));
let dump = thread_print(pid, THREAD_DUMP_TIMEOUT).unwrap();
assert!(dump.contains("Found one Java-level deadlock"), "{dump}");
assert!(dump.contains("sync-1") && dump.contains("sync-2"), "{dump}");
// The run's JVM is found through the real process table, as the dump action does.
let table = process_table();
assert!(table.iter().any(|entry| entry.pid == pid && entry.command.contains("Deadlock")));
assert_eq!(select_run_jvm(&table, pid, None, is_hotspot), Some(pid));
}
+1 -20
View File
@@ -12,7 +12,6 @@ const BUILTIN: &[(&str, &str)] = &[
("arduino", include_str!("../../../languages/arduino.toml")),
("asciidoc", include_str!("../../../languages/asciidoc.toml")),
("astro", include_str!("../../../languages/astro.toml")),
("axaml", include_str!("../../../languages/axaml.toml")),
("bat", include_str!("../../../languages/bat.toml")),
("c", include_str!("../../../languages/c.toml")),
("clojure", include_str!("../../../languages/clojure.toml")),
@@ -886,16 +885,10 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "laravel-lsp"]);
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
// DEVSENSE runs without Node or PHP of its own (the npm launcher needs Node) and
// answers the Laravel strings itself. https://docs.devsense.com/other/lsp/docs/
let devsense = cfg.language_servers.iter().find(|s| s.name == "devsense-php-ls").unwrap();
assert!(devsense.fallback && devsense.replaces == ["laravel-lsp"]);
assert_eq!(devsense.command.as_str(), "devsense-php-ls");
assert_eq!(devsense.install_hint.as_deref(), Some("npm i -g devsense-php-ls"));
let lsp = cfg.language_servers.iter().find(|s| s.name == "laravel-lsp").unwrap();
assert_eq!(lsp.command.as_str(), "laravel-lsp");
// Its `lsp` command takes no options and speaks over stdio; `--stdio` stops it at startup.
@@ -1278,8 +1271,6 @@ mod tests {
("Cargo.toml", "toml"),
("Cargo.lock", "toml"),
("pom.xml", "xml"),
("Views/MainWindow.axaml", "axaml"),
("MainWindow.xaml", "xml"),
("README.md", "markdown"),
("Dockerfile", "dockerfile"),
("Dockerfile.dev", "dockerfile"),
@@ -1317,16 +1308,6 @@ mod tests {
}
}
#[test]
fn avalonia_xaml_is_xml_with_its_own_server() {
let reg = reg();
let axaml = reg.get(&LanguageId::new("axaml")).unwrap();
assert_eq!(axaml.tree_sitter.as_deref(), Some("xml"));
assert_eq!(axaml.ui_mode.as_deref(), Some("XML"));
let servers: Vec<_> = axaml.language_servers.iter().map(|s| (s.name.as_str(), s.fallback)).collect();
assert_eq!(servers, [("axsg-lsp", false), ("lemminx", true)]);
}
#[test]
fn gdscript_definition() {
let reg = reg();
+1 -71
View File
@@ -60,11 +60,6 @@ pub struct PythonMethodFacts {
/// Decorated with `override` from `typing` / `typing_extensions`.
pub override_decorated: bool,
pub body: MethodBody,
/// For 'Method may be static': the receiver parameter up to the next parameter (what
/// Make method static deletes), when the method is undecorated and not a dunder, and its
/// body does more than `pass`, `...`, a docstring or one `raise` without ever naming the
/// receiver, `super` or `__class__`.
pub unused_receiver: Option<crate::Range>,
}
/// What a method body does, for the shapes a check can decide without guessing.
@@ -214,65 +209,18 @@ fn methods_of(class: Node, text: &str, idx: &LineIndex, imports: &ImportBindings
}
let decorators = decorators_of(method, text);
out.push(PythonMethodFacts {
name,
selection: idx.range(name_node.start_byte(), name_node.end_byte()),
definition_line: member.start_position().row as u32,
params: parameters_of(method, text),
abstract_method: decorators.iter().any(|d| last_segment(d) == "abstractmethod"),
override_decorated: decorators.iter().any(|d| imports.is_typing_override(d)),
body: body_of(method, text),
unused_receiver: if decorators.is_empty() && !is_dunder(&name) {
unused_receiver(method, text).map(|(start, end)| idx.range(start, end))
} else {
None
},
name,
});
}
out
}
fn is_dunder(name: &str) -> bool {
name.len() > 4 && name.starts_with("__") && name.ends_with("__")
}
/// The bytes Make method static deletes: the receiver up to the next parameter (or up to the
/// closing parenthesis), when the body does real work without naming the receiver.
fn unused_receiver(function: Node, text: &str) -> Option<(usize, usize)> {
let body = function.child_by_field_name("body")?;
let statements: Vec<Node> = statements_of(body).into_iter().filter(|s| !is_string(*s)).collect();
// Stubs and placeholders (`pass`, `...`, `raise NotImplementedError`) are meant to be overridden.
if statements.iter().all(|s| is_noop(*s))
|| matches!(statements.as_slice(), [only] if only.kind() == "raise_statement")
{
return None;
}
let params = function.child_by_field_name("parameters")?;
let mut cursor = params.walk();
let mut named = params.named_children(&mut cursor);
let receiver = named.next()?;
let name = match receiver.kind() {
"identifier" => receiver,
"typed_parameter" => receiver.named_child(0).filter(|n| n.kind() == "identifier")?,
_ => return None,
};
let name = &text[name.byte_range()];
let next = named.next();
if next.is_some_and(|n| matches!(n.kind(), "positional_separator" | "keyword_separator")) {
return None;
}
let mut used = false;
let mut cursor = body.walk();
visit(&mut cursor, &mut |node| {
used |= node.kind() == "identifier"
&& matches!(&text[node.byte_range()], n if n == name || n == "super" || n == "__class__");
});
if used {
return None;
}
let end = next.map_or(params.end_byte() - 1, |n| n.start_byte());
Some((receiver.start_byte(), end))
}
/// The parameter names of a `function_definition`, or `None` when the signature contains a
/// form whose forwarding cannot be compared without guessing.
fn parameters_of(function: Node, text: &str) -> Option<Vec<String>> {
@@ -630,22 +578,4 @@ mod tests {
let f = facts("@dataclass\nclass C:\n x: int\n");
assert_eq!(f.classes[0].definition_line, 0);
}
#[test]
fn unused_receiver_is_the_parameter_make_static_deletes() {
let src = "class C:\n def helper(self, x):\n return x * 2\n\n def only(self):\n print(1)\n\n def typed(self: 'C',) -> int:\n return 1\n\n def uses(self):\n return self.x\n\n def nested(self):\n return lambda: self\n\n def sup(self):\n return super().sup()\n\n def stub(self):\n raise NotImplementedError\n\n def empty(self):\n \"\"\"Doc.\"\"\"\n\n @property\n def prop(self):\n return 1\n\n def __repr__(self):\n return 'C'\n\n def positional(self, /, x):\n return x\n";
let f = facts(src);
let deleted = |name: &str| {
method(&f, "C", name).unused_receiver.map(|r| {
let line = src.lines().nth(r.start.line as usize).unwrap();
line[r.start.col as usize..r.end.col as usize].to_string()
})
};
assert_eq!(deleted("helper").as_deref(), Some("self, "));
assert_eq!(deleted("only").as_deref(), Some("self"));
assert_eq!(deleted("typed").as_deref(), Some("self: 'C',"));
for name in ["uses", "nested", "sup", "stub", "empty", "prop", "__repr__", "positional"] {
assert_eq!(deleted(name), None, "{name}");
}
}
}
-5
View File
@@ -645,11 +645,6 @@ impl Handler for ClientHandler {
{
self.show_message(&mgr, &json!({ "type": 1, "message": text.lines().next().unwrap_or(text) }));
}
if self.server.name == "jdtls"
&& let Some(failure) = crate::jdtls::gradle_sync_failure(text)
{
mgr.report_gradle_sync_failure(failure);
}
if self.server.name == "jdtls"
&& params.get("type").and_then(Value::as_u64) == Some(1)
&& let Some(failure) = crate::jdtls::logged_build_plan_failure(text)
-96
View File
@@ -1293,66 +1293,7 @@ pub(crate) fn logged_build_plan_failure(message: &str) -> Option<(String, String
Some((reason, body))
}
/// How long a failed Gradle sync waits for jdtls' incompatible-JDK message (sent a few ms later).
const GRADLE_JDK_MESSAGE_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);
/// Buildship's log when a Gradle sync fails ("Synchronize project app failed due to an error
/// connecting to the Gradle build.", then the stack trace), as (project, notification body).
/// jdtls logs it below error level, so without this the import fails silently: every Java file
/// shows unresolved types and nothing says why. The deepest `Caused by` is the build's own error.
pub(crate) fn gradle_sync_failure(message: &str) -> Option<(String, String)> {
let first = message.lines().next()?;
let (_, rest) = first.split_once("Synchronize project ")?;
let (project, _) = rest.split_once(" failed due to ")?;
let cause = message
.lines()
.rev()
.find_map(|l| l.trim_start().strip_prefix("Caused by: "))
.or_else(|| message.lines().nth(1))
.map(|l| match l.split_once(": ") {
// `org.gradle.Some.Exception: what happened` → what happened
Some((class, text)) if class.contains('.') && !class.contains(char::is_whitespace) => text,
_ => l,
})
.map(str::trim)
.filter(|c| !c.is_empty() && !c.starts_with("at "));
const MAX: usize = 500;
let cause = cause.map(|c| match c.char_indices().nth(MAX) {
Some((end, _)) => format!("{}…", &c[..end]),
None => c.to_owned(),
});
let body = match cause {
Some(cause) => format!(
"Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. Cause: {cause}"
),
None => format!(
"Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project."
),
};
Some((project.to_owned(), body))
}
impl LspManager {
/// A failed Gradle sync of `project` (see [`gradle_sync_failure`]), shown once. jdtls follows
/// a sync that failed on an incompatible JDK with "Can't use Java … to import Gradle project
/// …", which has its own notification with the fix; wait for it so that one is the only one.
pub(crate) fn report_gradle_sync_failure(&self, (project, body): (String, String)) {
let Some(me) = self.me.upgrade() else { return };
self.runtime.spawn(async move {
tokio::time::sleep(GRADLE_JDK_MESSAGE_WAIT).await;
if me.shown_message_containing(SERVER, &format!(" to import Gradle project {project}")) {
return;
}
if me.first_message(SERVER, &body) {
me.sink().emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Error,
title: "Gradle project sync failed".into(),
body: Some(body),
});
}
});
}
/// JDT LS aborted its import with `message`: when reserved Windows device names
/// below `root` are the cause, say which (once). The walk runs off the RPC thread.
pub(crate) fn report_import_failure(&self, root: PathBuf, message: String) {
@@ -1461,43 +1402,6 @@ mod tests {
);
}
#[test]
fn a_failed_gradle_sync_is_explained_with_its_root_cause() {
let log = "Nov 25, 2026, 2:00:14 PM Synchronize project repro failed due to an error connecting to the Gradle build.\n\
org.gradle.tooling.BuildActionFailureException: The supplied phased action failed with an exception.\n\
\tat org.gradle.tooling.internal.consumer.connection.PhasedActionAwareConsumerConnection.doRun(PhasedActionAwareConsumerConnection.java:58)\n\
Caused by: org.gradle.api.plugins.InvalidPluginException: An exception occurred applying plugin request [id: 'war']\n\
\tat x\n\
Caused by: java.lang.IllegalArgumentException: Unable to determine constructor argument #2: missing parameter of type IdeArtifactRegistry, or no service of type IdeArtifactRegistry.\n\
\tat org.gradle.groovy.scripts.DefaultScript.apply(DefaultScript.java:133)\n\
\t... 12 more";
let (project, body) = gradle_sync_failure(log).unwrap();
assert_eq!(project, "repro");
assert_eq!(
body,
"Gradle could not sync repro. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. \
Cause: Unable to determine constructor argument #2: missing parameter of type IdeArtifactRegistry, or no service of type IdeArtifactRegistry."
);
// Without a `Caused by`, the logged exception's own message.
let (_, body) = gradle_sync_failure(
"Synchronize project app failed due to an error in the referenced Gradle build.\n\
org.gradle.tooling.BuildException: Could not run build action.\n\tat y",
)
.unwrap();
assert!(body.ends_with(" Cause: Could not run build action."), "{body}");
// A cause that is a plain sentence keeps its colons.
let (_, body) = gradle_sync_failure(
"Synchronize project app failed due to an error connecting to the Gradle build.\nx\nCaused by: Build failed: see above",
)
.unwrap();
assert!(body.ends_with(" Cause: Build failed: see above"), "{body}");
assert_eq!(gradle_sync_failure("Synchronizing projects\nCaused by: x.Y: z"), None);
assert_eq!(gradle_sync_failure("Failed to configure some Maven project(s)"), None);
}
#[test]
fn source_settings_preserve_java_defaults_and_library_resolution() {
let mut cfg = java_config();
-25
View File
@@ -1218,11 +1218,6 @@ impl LspManager {
self.shown_messages.lock().insert((server.to_owned(), text.to_owned()))
}
/// Whether `server` has shown a message containing `needle` in this project.
pub(crate) fn shown_message_containing(&self, server: &str, needle: &str) -> bool {
self.shown_messages.lock().iter().any(|(s, text)| s == server && text.contains(needle))
}
pub(crate) fn apply_edit_hook(&self) -> Option<ApplyEditHook> {
self.apply_edit_hook.read().clone()
}
@@ -2635,26 +2630,6 @@ impl LspManager {
Ok(())
}
/// Where other files import `doc`'s file (VS Code's Find File References): tsserver's
/// `fileReferences` through vtsls' `typescript.tsserverRequest`, which also answers for a
/// `.vue` component with the Vue TypeScript plugin (vtsls' own command refuses non-TS
/// documents). Unavailable when no TypeScript server serves the document.
pub async fn file_references(&self, doc: DocId, cancel: CancellationToken) -> IdeResult<Vec<Location>> {
let snap = self.snapshot(doc)?;
let targets =
self.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == ts_file_moves::COMMAND)).await;
let t = targets
.iter()
.find(|t| t.server.config.tsserver_project)
.ok_or_else(|| IdeError::unavailable("No language server finds file references"))?;
let params = json!({
"command": ts_file_moves::COMMAND,
"arguments": ["fileReferences", { "file": snap.path }],
});
let result: Value = self.call(t, "workspace/executeCommand", params, Some(&cancel), LONG_TIMEOUT).await?;
Ok(ts_file_moves::file_references(&result))
}
/// Whether a server of `doc` (`server`, when given) provides the command `name`. Code actions
/// can carry commands other editors' extensions run themselves after the edit (vtsls'
/// `_typescript.didOrganizeImports`): no server provides those.
-37
View File
@@ -63,47 +63,10 @@ pub(crate) fn edit(result: &Value) -> WorkspaceEdit {
}
}
#[derive(Deserialize)]
struct FileReference {
file: PathBuf,
start: Location,
end: Location,
}
#[derive(Deserialize)]
struct FileReferences {
refs: Vec<FileReference>,
}
/// tsserver's `fileReferences` answer (the command's `body`; 1-based lines and UTF-16 offsets): the imports of a file.
pub(crate) fn file_references(result: &Value) -> Vec<ide_core::Location> {
let body = result.get("body").unwrap_or(result);
let Ok(found) = serde_json::from_value::<FileReferences>(body.clone()) else { return Vec::new() };
let pos = |l: &Location| Pos::new(l.line.saturating_sub(1), l.offset.saturating_sub(1));
found
.refs
.into_iter()
.map(|r| ide_core::Location { path: r.file.into(), range: Range::new(pos(&r.start), pos(&r.end)), uri: None })
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_tsserver_file_references() {
let result = json!({ "success": true, "body": { "symbolName": "\"./Hello.vue\"", "refs": [
{ "file": "/p/src/App.vue", "start": { "line": 2, "offset": 19 }, "end": { "line": 2, "offset": 41 },
"lineText": "import Hello from './components/Hello.vue'", "isWriteAccess": false }
] } });
let refs = file_references(&result);
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].path, ide_core::IpcPath::from(PathBuf::from("/p/src/App.vue")));
assert_eq!(refs[0].range, Range::new(Pos::new(1, 18), Pos::new(1, 40)));
assert!(file_references(&json!({ "success": false })).is_empty());
}
#[test]
fn converts_tsserver_file_code_edits() {
let result = json!({ "success": true, "body": [
-52
View File
@@ -7652,58 +7652,6 @@ async fn gradle_incompatible_jdk_log_is_surfaced_once_across_message_channels()
assert_eq!(messages, vec![failure, "after"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_failed_gradle_sync_is_surfaced_once_unless_an_incompatible_jdk_explains_it() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let s = h.launcher.state("jdtls");
h.open("A.java", "class A {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let sync = |project: &str, cause: &str| {
format!(
"Nov 25, 2026, 2:00:14 PM Synchronize project {project} failed due to an error connecting to the Gradle build.\n\
org.gradle.tooling.BuildActionFailureException: The supplied phased action failed with an exception.\n\
\tat org.gradle.tooling.internal.consumer.DefaultPhasedBuildActionExecuter.run(DefaultPhasedBuildActionExecuter.java:68)\n\
Caused by: java.lang.IllegalArgumentException: {cause}\n\
\tat org.gradle.groovy.scripts.DefaultScript.apply(DefaultScript.java:133)"
)
};
// jdtls logs it below error level, and again on every sync.
for _ in 0..2 {
let message = sync("repro", "Unable to determine constructor argument #2");
s.peer().notify("window/logMessage", json!({ "type": 3, "message": message })).unwrap();
}
// An incompatible JDK fails the sync too, and jdtls then says so with its own fix.
s.peer()
.notify(
"window/logMessage",
json!({ "type": 3, "message": sync("old", "Unsupported class file major version 71") }),
)
.unwrap();
let jdk = "Can't use Java 27.0.1 and Gradle 7.5.1 to import Gradle project old.";
s.peer()
.notify("window/logMessage", json!({ "type": 1, "message": format!("{jdk}\njava.lang.Exception: details") }))
.unwrap();
let notes = || -> Vec<(String, String)> {
h.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Notify { title, body: Some(b), .. } => Some((title.clone(), b.clone())),
_ => None,
})
.collect()
};
eventually(|| notes().iter().any(|(t, _)| t == "Gradle project sync failed")).await;
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
let notes = notes();
let synced: Vec<_> =
notes.iter().filter(|(t, _)| t == "Gradle project sync failed").map(|(_, b)| b.as_str()).collect();
assert_eq!(synced.len(), 1, "{notes:?}");
assert!(synced[0].starts_with("Gradle could not sync repro. "), "{notes:?}");
assert!(synced[0].ends_with(" Cause: Unable to determine constructor argument #2"), "{notes:?}");
assert!(notes.iter().any(|(_, b)| b == jdk), "{notes:?}");
}
/// Pull Members Up / Push Members Down: the extension's answers, refusals and edits.
#[tokio::test(flavor = "multi_thread")]
async fn java_hierarchy_refactorings_use_the_extension_commands() {
-2
View File
@@ -317,8 +317,6 @@ pub trait HostApi: Send + Sync {
fn storage_keys(&self, prefix: &str) -> Result<Vec<String>, HostError>;
fn vcs_status(&self, root: &Path) -> Result<Option<RepositoryStatus>, HostError>;
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError>;
fn vcs_roots(&self, root: &Path) -> Result<Vec<String>, HostError>;
fn vcs_repository_at(&self, root: &Path, path: &str) -> Result<Option<crate::RepositoryInfo>, HostError>;
fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError>;
/// The commit being prepared in `client`'s window (`None`: no repository),
/// waiting for the window until `cancel` fires.
-25
View File
@@ -119,13 +119,6 @@ pub struct PickItem {
pub description: Option<String>,
}
/// A group of file extensions in a plugin's native chooser.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct PluginFileFilter {
pub name: String,
pub extensions: Vec<String>,
}
/// What a plugin asks the user (`ui.pick`, `ui.pick-many`, `ui.input`,
/// `ui.input-multiline`, `ui.confirm`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -139,8 +132,6 @@ pub enum Prompt {
Confirm { title: String, message: String },
#[serde(rename_all = "camelCase")]
PickDirectory { title: String, initial: Option<String> },
#[serde(rename_all = "camelCase")]
PickFile { title: String, save: bool, name: Option<String>, filters: Vec<PluginFileFilter> },
/// The host's own question under `net:ask` (never plugin-initiated): the
/// plugin reached an HTTPS host its manifest does not list.
#[serde(rename_all = "camelCase")]
@@ -408,18 +399,6 @@ pub struct RepositoryStatus {
pub changed_files: u32,
}
/// Reference and remotes of a path's mapped worktree (WIT `vcs.repository-info`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RepositoryInfo {
pub root: String,
pub relative_path: String,
pub branch: Option<String>,
pub commit: Option<String>,
pub upstream: Option<String>,
pub ahead: u32,
pub remotes: Vec<(String, String)>,
}
/// A file a pending commit changes (WIT `commit.commit-change`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -1014,15 +993,11 @@ pub struct FileProblems {
}
/// An editor decoration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Decoration {
pub range: ide_core::Range,
pub style: String,
pub hover: Option<String>,
pub after: Option<String>,
/// Markdown rendered in the editor's hover card (API 1.16); `hover` is the
/// plain-text fallback shown when this is absent.
pub markdown_hover: Option<String>,
}
/// A tree decoration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
+20 -105
View File
@@ -289,8 +289,6 @@ const MAX_FIND: u32 = 10_000;
const MAX_STATUS_TEXT: usize = 128;
const MAX_PICK_ITEMS: usize = 5000;
const MAX_PICK_KEY: usize = 256;
/// Filters of a `ui.pick-file` dialog, and extensions of each.
const MAX_FILE_FILTERS: usize = 32;
const MAX_ARGS: usize = 256;
const MAX_ARG_BYTES: usize = 4096;
const MAX_ENV: usize = 64;
@@ -421,17 +419,6 @@ impl log::Host for StoreData {
}
impl StoreData {
fn pick_path(&mut self, prompt: Prompt) -> Fallible<Option<String>> {
let answer = self.ask(prompt);
Ok(answer.and_then(|answer| {
let path = answer.and_then(|items| items.into_iter().next());
if let Some(path) = &path {
validate_ui_path(path)?;
}
Ok(path)
}))
}
/// Asks the user and waits; the wait doesn't count against the call's
/// wall-clock budget.
fn ask(&mut self, prompt: Prompt) -> Result<Option<Vec<String>>, wit::Error> {
@@ -807,27 +794,14 @@ impl ui::Host for StoreData {
{
return Ok(Err(error));
}
self.pick_path(Prompt::PickDirectory { title: clip(title, MAX_TITLE), initial })
}
fn pick_file(&mut self, title: String, dialog: ui::FileDialog) -> Fallible<Option<String>> {
let filters = dialog
.filters
.into_iter()
.take(MAX_FILE_FILTERS)
.map(|f| crate::PluginFileFilter {
name: clip(f.name, MAX_TITLE),
extensions: f.extensions.into_iter().take(MAX_FILE_FILTERS).map(|e| clip(e, MAX_PICK_KEY)).collect(),
})
.collect();
// A suggested file name only: the dialog starts where the user last was, never at a
// directory the plugin names.
let name = dialog
.name
.and_then(|n| n.rsplit(['/', '\\']).next().map(str::to_owned))
.filter(|n| !n.is_empty() && n != "." && n != "..")
.map(|n| clip(n, MAX_TITLE));
self.pick_path(Prompt::PickFile { title: clip(title, MAX_TITLE), save: dialog.save, name, filters })
let answer = self.ask(Prompt::PickDirectory { title: clip(title, MAX_TITLE), initial });
Ok(answer.and_then(|answer| {
let path = answer.and_then(|items| items.into_iter().next());
if let Some(path) = &path {
validate_ui_path(path)?;
}
Ok(path)
}))
}
fn pick_many(&mut self, title: String, items: Vec<ui::PickItem>) -> Fallible<Option<Vec<String>>> {
@@ -1446,34 +1420,6 @@ impl vcs::Host for StoreData {
let root = self.table.get(&project)?.root.clone();
Ok(self.host.vcs_remotes(&root).map_err(to_wit))
}
fn roots(&mut self, project: Resource<ProjectRes>) -> Fallible<Vec<String>> {
if let Err(e) = self.require(Capability::VcsRead) {
return Ok(Err(e));
}
Ok(self.host.vcs_roots(&self.table.get(&project)?.root).map_err(to_wit))
}
fn repository_at(&mut self, project: Resource<ProjectRes>, path: String) -> Fallible<Option<vcs::RepositoryInfo>> {
if let Err(e) = self.require(Capability::VcsRead) {
return Ok(Err(e));
}
Ok(self
.host
.vcs_repository_at(&self.table.get(&project)?.root, &path)
.map(|r| {
r.map(|r| vcs::RepositoryInfo {
root: r.root,
relative_path: r.relative_path,
branch: r.branch,
commit: r.commit,
upstream: r.upstream,
ahead: r.ahead,
remotes: r.remotes,
})
})
.map_err(to_wit))
}
}
impl build::Host for StoreData {
@@ -2856,23 +2802,6 @@ fn diagnostic_to_wit(d: ide_core::Diagnostic) -> diagnostics::Diagnostic {
related: Vec::new(),
}
}
impl StoreData {
/// Shared by `set` and `set-markdown`: both replace the same set-id namespace.
fn replace_decorations(&mut self, path: String, set_id: String, items: Vec<crate::Decoration>) -> Fallible<()> {
if let Err(e) = self.require(Capability::ProjectRead) {
return Ok(Err(e));
}
if items.len() > 10_000 {
return Ok(Err(wit::Error::Invalid("at most 10000 decorations per file".into())));
}
let real = match self.decoration_path(&path) {
Ok(real) => real,
Err(e) => return Ok(Err(e)),
};
Ok(self.host.decorations(Some(&real), &set_id, items).map_err(to_wit))
}
}
impl bindings::openidea::plugin::decorations::Host for StoreData {
fn set(
&mut self,
@@ -2880,35 +2809,21 @@ impl bindings::openidea::plugin::decorations::Host for StoreData {
set_id: String,
items: Vec<bindings::openidea::plugin::decorations::Decoration>,
) -> Fallible<()> {
if let Err(e) = self.require(Capability::ProjectRead) {
return Ok(Err(e));
}
if items.len() > 10_000 {
return Ok(Err(wit::Error::Invalid("at most 10000 decorations per file".into())));
}
let items = items
.into_iter()
.map(|d| crate::Decoration {
range: core_range(d.range),
style: d.style,
hover: d.hover,
after: d.after,
markdown_hover: None,
})
.map(|d| crate::Decoration { range: core_range(d.range), style: d.style, hover: d.hover, after: d.after })
.collect();
self.replace_decorations(path, set_id, items)
}
fn set_markdown(
&mut self,
path: String,
set_id: String,
items: Vec<bindings::openidea::plugin::decorations::MarkdownDecoration>,
) -> Fallible<()> {
let items = items
.into_iter()
.map(|d| crate::Decoration {
range: core_range(d.range),
style: d.style,
hover: d.hover,
after: d.after,
markdown_hover: d.markdown_hover,
})
.collect();
self.replace_decorations(path, set_id, items)
let real = match self.decoration_path(&path) {
Ok(real) => real,
Err(e) => return Ok(Err(e)),
};
Ok(self.host.decorations(Some(&real), &set_id, items).map_err(to_wit))
}
fn clear(&mut self, set_id: String) -> Fallible<()> {
if let Err(e) = self.require(Capability::ProjectRead) {
-1
View File
@@ -38,7 +38,6 @@ fn components() -> Vec<PathBuf> {
repo().join("crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm"),
repo().join("crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm"),
];
let official = repo().join("plugins/official");
Binary file not shown.
@@ -1 +1 @@
68517d169bea40ca5a5426a3a05ace3389417073b9369e79157a2beb051dcfc0
99d9091eed1143ad5df01e28631fba47f9a30f0ed99f078718a08183b85fa234
Loaded 100 of 777 files, more files were not shown because too many files have changed in this diff. Show more