дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
fix(java): coordinate builds across overlapping project windows
Цей коміт міститься в:
1 джерело
3ee1062d91
коміт
7df1f037e1
8 files changed
+623
-16
No files matched your search
@@ -144,6 +144,7 @@ pub struct Host {
|
||||
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
|
||||
/// The IDE's Java build: resident javac processes shared by every window's launches.
|
||||
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
|
||||
pub(crate) java_build_coordinator: Arc<ide_lsp::JavaBuildCoordinator>,
|
||||
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
|
||||
/// SSH connections of Settings › SSH Configurations.
|
||||
pub ssh: Arc<ide_ssh::SshManager>,
|
||||
@@ -315,6 +316,7 @@ impl Host {
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
java_build: Default::default(),
|
||||
java_build_coordinator: Arc::default(),
|
||||
metrics_sampler: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
|
||||
@@ -272,6 +272,7 @@ impl Host {
|
||||
)?;
|
||||
mark("index");
|
||||
let lsp = LspManager::new(root.clone(), languages.clone(), sink.clone());
|
||||
lsp.set_java_build_coordinator(self.java_build_coordinator.clone());
|
||||
crate::plugins::injections::configure_lsp(&lsp);
|
||||
lsp.set_execution_allowed(trusted.load(Ordering::Acquire));
|
||||
lsp.set_content_roots(language_server_roots(&root, extra_roots.clone()));
|
||||
@@ -416,6 +417,7 @@ impl Host {
|
||||
&effective.inspections,
|
||||
lang_level,
|
||||
);
|
||||
let generated_workspace = !cfg.args.iter().any(|arg| arg == "-data");
|
||||
ide_sdk::java::configure_jdtls(
|
||||
cfg,
|
||||
server_root,
|
||||
@@ -427,6 +429,12 @@ impl Host {
|
||||
&bundles,
|
||||
lombok.jar(),
|
||||
);
|
||||
if generated_workspace && server_root != window_root {
|
||||
// The same build can be selected from a containing window and from a
|
||||
// window opened directly on it. They must not lock the same Eclipse
|
||||
// metadata directory while keeping independent editor buffers.
|
||||
scope_java_workspace(cfg, window_root);
|
||||
}
|
||||
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
|
||||
let gradle_dirs: Vec<_> = std::iter::once(data_dir.join("gradle"))
|
||||
.chain(dirs::cache_dir().map(|dir| dir.join("openidea").join("gradle")))
|
||||
@@ -3033,6 +3041,15 @@ fn exclude_globs(
|
||||
globs
|
||||
}
|
||||
|
||||
fn scope_java_workspace(cfg: &mut ide_language::LanguageServerConfig, window_root: &Path) {
|
||||
if let Some(index) = cfg.args.iter().position(|arg| arg == "-data")
|
||||
&& let Some(data) = cfg.args.get_mut(index + 1)
|
||||
{
|
||||
data.push_str("-window-");
|
||||
data.push_str(&project_key(window_root));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn project_key(root: &Path) -> String {
|
||||
// Stable FNV-1a directory name per project for caches.
|
||||
let s = root.to_string_lossy();
|
||||
@@ -3271,6 +3288,20 @@ mod vue_release_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod maven_linkage_tests {
|
||||
#[test]
|
||||
fn nested_java_workspaces_have_distinct_metadata_paths() {
|
||||
let mut cfg: ide_language::LanguageServerConfig = serde_json::from_value(serde_json::json!({
|
||||
"name": "jdtls", "command": "jdtls", "args": ["-data", "workspace"]
|
||||
}))
|
||||
.unwrap();
|
||||
let original = cfg.clone();
|
||||
super::scope_java_workspace(&mut cfg, std::path::Path::new("/parent"));
|
||||
assert_ne!(cfg.args, original.args);
|
||||
let mut other = original;
|
||||
super::scope_java_workspace(&mut other, std::path::Path::new("/other"));
|
||||
assert_ne!(cfg.args, other.args);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_gradle_links_preserve_independent_eclipse_projects() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
//! One background JDT builder per overlapping physical workspace on a host.
|
||||
//! Windows keep their own documents and language-service settings. An explicit
|
||||
//! build borrows the output directories from the background builder instead of
|
||||
//! letting two Eclipse workspaces write them at the same time.
|
||||
|
||||
use crate::server::{Running, Server};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, ServerId};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct JavaBuildCoordinator {
|
||||
state: Mutex<State>,
|
||||
changed: Notify,
|
||||
}
|
||||
|
||||
type Instance = (ServerId, u64);
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
entries: Vec<Entry>,
|
||||
builds: Vec<Build>,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
instance: Instance,
|
||||
server: Weak<Server>,
|
||||
roots: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
struct Build {
|
||||
instance: Instance,
|
||||
roots: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
fn intersections<'a>(a: &'a [PathBuf], b: &'a [PathBuf]) -> impl Iterator<Item = &'a Path> {
|
||||
a.iter().flat_map(move |a| {
|
||||
b.iter().filter_map(move |b| {
|
||||
if a.starts_with(b) {
|
||||
Some(a.as_path())
|
||||
} else if b.starts_with(a) {
|
||||
Some(b.as_path())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Keep the first live writer. A broader, later workspace is still useful for
|
||||
/// analysis; an explicit build in it can borrow the overlapping writer's turn.
|
||||
fn update_owners(&self) -> Vec<(Arc<Server>, u64, Vec<PathBuf>)> {
|
||||
let mut writers: Vec<&Entry> = Vec::new();
|
||||
let mut paused = Vec::new();
|
||||
for entry in &self.entries {
|
||||
let Some(server) = entry.server.upgrade() else { continue };
|
||||
let shadowed = writers.iter().any(|writer| intersections(&writer.roots, &entry.roots).next().is_some());
|
||||
if !shadowed {
|
||||
writers.push(entry);
|
||||
}
|
||||
let borrowed = self.builds.iter().find(|build| {
|
||||
build.instance != entry.instance && intersections(&build.roots, &entry.roots).next().is_some()
|
||||
});
|
||||
let suspended = shadowed || borrowed.is_some();
|
||||
let previous = server.java_coordinated_autobuild_suspended.swap(suspended, Ordering::SeqCst);
|
||||
if previous != suspended {
|
||||
if let Some(run) = server.initialized_gen(entry.instance.1) {
|
||||
let settings = crate::handler::all_settings(&server.effective_config());
|
||||
if let Err(error) =
|
||||
run.peer.notify("workspace/didChangeConfiguration", json!({ "settings": settings }))
|
||||
{
|
||||
tracing::debug!(%error, "jdtls: updating coordinated autobuild");
|
||||
}
|
||||
}
|
||||
if suspended && let Some(build) = borrowed {
|
||||
let roots = intersections(&build.roots, &entry.roots).map(Path::to_path_buf).collect();
|
||||
paused.push((server, entry.instance.1, roots));
|
||||
}
|
||||
}
|
||||
}
|
||||
paused
|
||||
}
|
||||
}
|
||||
|
||||
impl JavaBuildCoordinator {
|
||||
pub(crate) async fn register(
|
||||
self: &Arc<Self>,
|
||||
server: &Arc<Server>,
|
||||
generation: u64,
|
||||
roots: Vec<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Registration> {
|
||||
let roots = roots.into_iter().map(|p| dunce::canonicalize(&p).unwrap_or(p)).collect::<Vec<_>>();
|
||||
let instance = (server.id, generation);
|
||||
loop {
|
||||
let changed = self.changed.notified();
|
||||
tokio::pin!(changed);
|
||||
changed.as_mut().enable();
|
||||
{
|
||||
let mut state = self.state.lock();
|
||||
if !state.builds.iter().any(|build| intersections(&build.roots, &roots).next().is_some()) {
|
||||
state.entries.retain(|entry| entry.instance.0 != server.id && entry.server.strong_count() != 0);
|
||||
state.entries.push(Entry { instance, server: Arc::downgrade(server), roots });
|
||||
state.update_owners();
|
||||
return Ok(Registration { coordinator: self.clone(), instance });
|
||||
}
|
||||
}
|
||||
crate::jdtls::cancellable_wait(cancel, changed).await?;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire(
|
||||
self: &Arc<Self>,
|
||||
server: &Server,
|
||||
generation: u64,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPermit> {
|
||||
let instance = (server.id, generation);
|
||||
let (permit, paused) = loop {
|
||||
let changed = self.changed.notified();
|
||||
tokio::pin!(changed);
|
||||
changed.as_mut().enable();
|
||||
{
|
||||
let mut state = self.state.lock();
|
||||
let roots = state
|
||||
.entries
|
||||
.iter()
|
||||
.find(|entry| entry.instance == instance)
|
||||
.ok_or_else(|| IdeError::unavailable("Java workspace stopped before building"))?
|
||||
.roots
|
||||
.clone();
|
||||
if !state.builds.iter().any(|build| intersections(&build.roots, &roots).next().is_some()) {
|
||||
state.builds.push(Build { instance, roots: roots.clone() });
|
||||
let permit = BuildPermit { coordinator: self.clone(), instance, roots, outstanding: None };
|
||||
break (permit, state.update_owners());
|
||||
}
|
||||
}
|
||||
crate::jdtls::cancellable_wait(cancel, changed).await?;
|
||||
};
|
||||
|
||||
// Configuration stops scheduling new automatic builds. The classpath
|
||||
// request takes the Eclipse project scheduling rule, draining a build
|
||||
// already in progress before the borrower touches the same outputs.
|
||||
for (writer, generation, roots) in paused {
|
||||
let run = crate::jdtls::cancellable_wait(cancel, writer.wait_ready(Duration::from_secs(240))).await?;
|
||||
let Some(run) = run.filter(|run| run.generation == generation) else {
|
||||
if !writer.is_live(generation) {
|
||||
continue;
|
||||
}
|
||||
return Err(IdeError::unavailable("Overlapping Java workspace is still starting; retry the build"));
|
||||
};
|
||||
if crate::java_project::reports_import(&writer) {
|
||||
let ready = crate::jdtls::cancellable_wait(
|
||||
cancel,
|
||||
tokio::time::timeout(Duration::from_secs(240), writer.wait_java_ready(generation)),
|
||||
)
|
||||
.await?;
|
||||
if !matches!(ready, Ok(true)) && writer.is_live(generation) {
|
||||
return Err(IdeError::unavailable(
|
||||
"Overlapping Java workspace is still importing; retry the build",
|
||||
));
|
||||
}
|
||||
}
|
||||
let result = crate::jdtls::cancellable_wait(cancel, drain(&run, &roots, Some(cancel.clone()))).await?;
|
||||
if let Err(error) = result
|
||||
&& writer.is_live(generation)
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(permit)
|
||||
}
|
||||
}
|
||||
|
||||
/// Query the project's classpaths under its Eclipse scheduling rule. An
|
||||
/// ancestor can contain multiple Maven projects, and need not itself be a Java
|
||||
/// project. Check the actual imported projects rather than the directory alone.
|
||||
async fn drain(run: &Running, roots: &[PathBuf], cancel: Option<CancellationToken>) -> IdeResult<()> {
|
||||
let command = |name: &str, args: Value| {
|
||||
let cancel = cancel.clone();
|
||||
let peer = run.peer.clone();
|
||||
let params = json!({"command": name, "arguments": args});
|
||||
async move {
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(240),
|
||||
peer.request::<_, Value>("workspace/executeCommand", params, cancel),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("Overlapping Java workspace is still building; retry the build"))?
|
||||
.map_err(|e| crate::rpc_err("jdtls", "workspace/executeCommand", e))
|
||||
}
|
||||
};
|
||||
let projects = command("java.project.getAll", json!([])).await?;
|
||||
let paths = match projects.as_array() {
|
||||
Some(projects) => projects
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.filter_map(crate::jdtls::project_path)
|
||||
.map(|p| dunce::canonicalize(&p).unwrap_or(p))
|
||||
.filter(|p| roots.iter().any(|root| p.starts_with(root)))
|
||||
.collect::<Vec<_>>(),
|
||||
None => roots.to_vec(),
|
||||
};
|
||||
for project in paths {
|
||||
command("java.project.getClasspaths", json!([crate::path_to_uri_string(&project), "{\"scope\":\"runtime\"}"]))
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Owned by the actual server instance until its JVM exits, not by the window.
|
||||
/// Closing the first window promotes the next compatible background writer.
|
||||
pub(crate) struct Registration {
|
||||
coordinator: Arc<JavaBuildCoordinator>,
|
||||
instance: Instance,
|
||||
}
|
||||
|
||||
impl Drop for Registration {
|
||||
fn drop(&mut self) {
|
||||
self.coordinator.retire(self.instance.0, self.instance.1);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct BuildPermit {
|
||||
coordinator: Arc<JavaBuildCoordinator>,
|
||||
instance: Instance,
|
||||
roots: Vec<PathBuf>,
|
||||
outstanding: Option<Running>,
|
||||
}
|
||||
|
||||
impl BuildPermit {
|
||||
pub(crate) fn started(&mut self, run: &Running) {
|
||||
self.outstanding = Some(run.clone());
|
||||
}
|
||||
|
||||
pub(crate) fn finished(&mut self) {
|
||||
self.outstanding = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl JavaBuildCoordinator {
|
||||
pub(crate) fn retire(&self, server: ServerId, generation: u64) {
|
||||
let mut state = self.state.lock();
|
||||
state.entries.retain(|entry| entry.instance != (server, generation));
|
||||
state.update_owners();
|
||||
self.changed.notify_waiters();
|
||||
}
|
||||
|
||||
fn release(&self, instance: Instance) {
|
||||
let mut state = self.state.lock();
|
||||
state.builds.retain(|build| build.instance != instance);
|
||||
state.update_owners();
|
||||
self.changed.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BuildPermit {
|
||||
fn drop(&mut self) {
|
||||
let overlapping = {
|
||||
let state = self.coordinator.state.lock();
|
||||
state.builds.iter().find(|build| build.instance == self.instance).is_some_and(|build| {
|
||||
state.entries.iter().any(|entry| {
|
||||
entry.instance != self.instance && intersections(&build.roots, &entry.roots).next().is_some()
|
||||
})
|
||||
})
|
||||
};
|
||||
if let Some(run) = self.outstanding.take().filter(|_| overlapping) {
|
||||
// A cancelled JSON-RPC request can return before Eclipse stops the
|
||||
// compiler. Don't re-enable another writer until its scheduling
|
||||
// rule is free, even if the outer future was dropped.
|
||||
let coordinator = self.coordinator.clone();
|
||||
let instance = self.instance;
|
||||
let roots = std::mem::take(&mut self.roots);
|
||||
tokio::spawn(async move {
|
||||
if drain(&run, &roots, None).await.is_err() {
|
||||
run.peer.kill();
|
||||
run.peer.exited().await;
|
||||
}
|
||||
coordinator.release(instance);
|
||||
});
|
||||
} else {
|
||||
self.coordinator.release(self.instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::LanguageId;
|
||||
use ide_language::LanguageServerConfig;
|
||||
|
||||
fn server(root: &Path) -> Arc<Server> {
|
||||
let cfg: LanguageServerConfig = serde_json::from_value(json!({"name": "jdtls", "command": "jdtls"})).unwrap();
|
||||
Arc::new(Server::new(cfg, root.to_path_buf(), LanguageId::new("java")))
|
||||
}
|
||||
|
||||
fn suspended(server: &Server) -> bool {
|
||||
server.java_coordinated_autobuild_suspended.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn overlapping_windows_have_one_background_writer_and_promote_on_close() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = tmp.path().join("parent");
|
||||
let child = parent.join("child");
|
||||
let independent = tmp.path().join("independent");
|
||||
std::fs::create_dir_all(&child).unwrap();
|
||||
std::fs::create_dir_all(&independent).unwrap();
|
||||
let (a, b, c) = (server(&parent), server(&child), server(&independent));
|
||||
let coordinator = Arc::new(JavaBuildCoordinator::default());
|
||||
let cancel = CancellationToken::new();
|
||||
let a_reg = coordinator.register(&a, 1, vec![parent], &cancel).await.unwrap();
|
||||
let _b_reg = coordinator.register(&b, 1, vec![child], &cancel).await.unwrap();
|
||||
let _c_reg = coordinator.register(&c, 1, vec![independent], &cancel).await.unwrap();
|
||||
assert!(!suspended(&a));
|
||||
assert!(suspended(&b));
|
||||
assert!(!suspended(&c));
|
||||
drop(a_reg);
|
||||
assert!(!suspended(&b));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_builds_of_overlapping_workspaces_wait_but_disjoint_builds_do_not() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let parent = tmp.path().join("parent");
|
||||
let child = parent.join("child");
|
||||
let independent = tmp.path().join("independent");
|
||||
std::fs::create_dir_all(&child).unwrap();
|
||||
std::fs::create_dir_all(&independent).unwrap();
|
||||
let (a, b, c) = (server(&parent), server(&child), server(&independent));
|
||||
let coordinator = Arc::new(JavaBuildCoordinator::default());
|
||||
let cancel = CancellationToken::new();
|
||||
let _a_reg = coordinator.register(&a, 1, vec![parent], &cancel).await.unwrap();
|
||||
let _b_reg = coordinator.register(&b, 1, vec![child], &cancel).await.unwrap();
|
||||
let _c_reg = coordinator.register(&c, 1, vec![independent], &cancel).await.unwrap();
|
||||
let _a_build = coordinator.acquire(&a, 1, &cancel).await.unwrap();
|
||||
let _c_build = coordinator.acquire(&c, 1, &cancel).await.unwrap();
|
||||
assert!(tokio::time::timeout(Duration::from_millis(20), coordinator.acquire(&b, 1, &cancel)).await.is_err());
|
||||
assert!(suspended(&b));
|
||||
let stopped = CancellationToken::new();
|
||||
stopped.cancel();
|
||||
assert!(coordinator.acquire(&b, 1, &stopped).await.is_err());
|
||||
}
|
||||
}
|
||||
@@ -267,7 +267,7 @@ fn cache_owned_maven_settings(root: &Path) -> bool {
|
||||
root.join("pom.xml").is_file() && matches!(root.join(".settings").try_exists(), Ok(false))
|
||||
}
|
||||
|
||||
fn project_path(uri: &str) -> Option<PathBuf> {
|
||||
pub(crate) fn project_path(uri: &str) -> Option<PathBuf> {
|
||||
// jdtls commands use Java's `file:/p` as well as LSP's `file:///p`.
|
||||
let normalized = match uri.strip_prefix("file:") {
|
||||
Some(rest) if !rest.starts_with("//") => format!("file://{rest}"),
|
||||
@@ -350,6 +350,7 @@ pub struct JavaExternalBuild {
|
||||
server: Arc<Server>,
|
||||
run: Running,
|
||||
_lock: tokio::sync::OwnedMutexGuard<()>,
|
||||
_permit: crate::java_build_coordinator::BuildPermit,
|
||||
}
|
||||
|
||||
impl Drop for JavaExternalBuild {
|
||||
@@ -939,6 +940,19 @@ impl LspManager {
|
||||
let started = Instant::now();
|
||||
let (server, run) = self.jdtls(path, cancel).await?;
|
||||
let ready_ms = started.elapsed().as_millis();
|
||||
Self::jdtls_instance_request(&server, &run, method, params, timeout, cancel, ready_ms).await
|
||||
}
|
||||
|
||||
async fn jdtls_instance_request(
|
||||
server: &Server,
|
||||
run: &Running,
|
||||
method: &str,
|
||||
params: Value,
|
||||
timeout: Duration,
|
||||
cancel: &CancellationToken,
|
||||
ready_ms: u128,
|
||||
) -> IdeResult<Value> {
|
||||
let started = Instant::now();
|
||||
let phase = params.get("command").and_then(Value::as_str).unwrap_or(method).to_owned();
|
||||
let fut = run.peer.request::<Value, Value>(method, params, Some(cancel.clone()));
|
||||
let result = match tokio::time::timeout(timeout, fut).await {
|
||||
@@ -954,7 +968,7 @@ impl LspManager {
|
||||
tracing::info!(
|
||||
phase,
|
||||
ready_ms,
|
||||
request_ms = started.elapsed().as_millis() - ready_ms,
|
||||
request_ms = started.elapsed().as_millis(),
|
||||
success = result.is_ok(),
|
||||
"Java launch request"
|
||||
);
|
||||
@@ -1131,9 +1145,14 @@ impl LspManager {
|
||||
/// Keep this guard until Maven outputs have been copied out of JDT's reach.
|
||||
pub async fn java_external_build(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<JavaExternalBuild> {
|
||||
let (server, run) = self.jdtls(path, cancel).await?;
|
||||
let coordinator = self.java_build_coordinator.read().clone();
|
||||
let permit = coordinator.acquire(&server, run.generation, cancel).await?;
|
||||
let lock = cancellable_wait(cancel, server.java_build_lock.clone().lock_owned()).await?;
|
||||
if !server.is_live(run.generation) {
|
||||
return Err(IdeError::unavailable("Java workspace stopped before building"));
|
||||
}
|
||||
server.java_autobuild_suspended.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
let guard = JavaExternalBuild { server, run, _lock: lock };
|
||||
let guard = JavaExternalBuild { server, run, _lock: lock, _permit: permit };
|
||||
let settings = crate::handler::all_settings(&guard.server.effective_config());
|
||||
guard
|
||||
.run
|
||||
@@ -1147,19 +1166,28 @@ impl LspManager {
|
||||
/// class files are up to date before a launch.
|
||||
/// `full` asks jdtls for a clean build (`java/buildWorkspace(true)`, IDEA's Rebuild).
|
||||
pub async fn java_build(&self, path: &Path, full: bool, cancel: &CancellationToken) -> IdeResult<JavaBuildStatus> {
|
||||
let (server, _) = self.jdtls(path, cancel).await?;
|
||||
let _lock = cancellable_wait(cancel, server.java_build_lock.lock()).await?;
|
||||
let mut v = self.jdtls_request(path, "java/buildWorkspace", json!(full), BUILD_TIMEOUT, cancel).await?;
|
||||
// The first build can finish the Maven import before ServiceReady is handled.
|
||||
let (server, run) = self.jdtls(path, cancel).await?;
|
||||
let coordinator = self.java_build_coordinator.read().clone();
|
||||
let mut permit = coordinator.acquire(&server, run.generation, cancel).await?;
|
||||
let _lock = cancellable_wait(cancel, server.java_build_lock.lock()).await?;
|
||||
permit.started(&run);
|
||||
let request = || {
|
||||
Self::jdtls_instance_request(&server, &run, "java/buildWorkspace", json!(full), BUILD_TIMEOUT, cancel, 0)
|
||||
};
|
||||
let mut v = request().await?;
|
||||
// The first build can finish the Maven import before ServiceReady is handled.
|
||||
let changed = cancellable_wait(cancel, self.java_configure_compiler(&server, &run)).await??;
|
||||
// ServiceReady can update the options concurrently with that first build.
|
||||
let recheck = v.as_i64() == Some(2)
|
||||
&& compiler_defaults(&server.effective_config()).as_object().is_some_and(|o| !o.is_empty());
|
||||
if changed || recheck {
|
||||
v = self.jdtls_request(path, "java/buildWorkspace", json!(full), BUILD_TIMEOUT, cancel).await?;
|
||||
v = request().await?;
|
||||
}
|
||||
Ok(JavaBuildStatus::from_code(v.as_i64().unwrap_or(0)))
|
||||
let status = JavaBuildStatus::from_code(v.as_i64().unwrap_or(0));
|
||||
if status != JavaBuildStatus::Cancelled {
|
||||
permit.finished();
|
||||
}
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
/// Runtime (`test == false`) or test classpath of the project containing `path`.
|
||||
|
||||
@@ -23,6 +23,7 @@ mod go_scope;
|
||||
mod handler;
|
||||
mod injections;
|
||||
mod inspect;
|
||||
mod java_build_coordinator;
|
||||
pub mod java_project;
|
||||
pub mod jdtls;
|
||||
mod kotlin_lsp;
|
||||
@@ -58,6 +59,7 @@ mod xml_comment;
|
||||
|
||||
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
|
||||
pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions};
|
||||
pub use java_build_coordinator::JavaBuildCoordinator;
|
||||
pub use jdtls::exception_breakpoints::JdtExceptionBreakpoints;
|
||||
pub use jdtls::jvm_inspect::JdtJvmInspector;
|
||||
pub use jdtls::stream_trace::JdtStreamTracer;
|
||||
@@ -338,6 +340,7 @@ pub struct LspManager {
|
||||
jdtls_shared_hook: RwLock<Option<Arc<JdtlsSharedFn>>>,
|
||||
locale_hook: RwLock<Option<Arc<LocaleFn>>>,
|
||||
jdtls_workspace: Mutex<JdtlsWorkspace>,
|
||||
java_build_coordinator: RwLock<Arc<JavaBuildCoordinator>>,
|
||||
reconfigure_lock: tokio::sync::Mutex<()>,
|
||||
shutting_down: AtomicBool,
|
||||
execution_allowed: AtomicBool,
|
||||
@@ -669,6 +672,7 @@ impl LspManager {
|
||||
jdtls_shared_hook: RwLock::new(None),
|
||||
locale_hook: RwLock::new(None),
|
||||
jdtls_workspace: Mutex::new(Default::default()),
|
||||
java_build_coordinator: RwLock::new(Arc::default()),
|
||||
reconfigure_lock: tokio::sync::Mutex::new(()),
|
||||
shutting_down: AtomicBool::new(false),
|
||||
execution_allowed: AtomicBool::new(true),
|
||||
@@ -729,6 +733,11 @@ impl LspManager {
|
||||
self.jdtls_import_roots.read().clone()
|
||||
}
|
||||
|
||||
/// Coordinates Java builders across all project windows of the host.
|
||||
pub fn set_java_build_coordinator(&self, coordinator: Arc<JavaBuildCoordinator>) {
|
||||
*self.java_build_coordinator.write() = coordinator;
|
||||
}
|
||||
|
||||
/// Shares JDT LS within this manager; callers reconfigure after the hook's value changes.
|
||||
pub fn set_jdtls_shared_hook(&self, hook: Box<JdtlsSharedFn>) {
|
||||
*self.jdtls_shared_hook.write() = Some(Arc::from(hook));
|
||||
@@ -1082,6 +1091,15 @@ impl LspManager {
|
||||
|
||||
async fn run_instance(self: Arc<Self>, server: Arc<Server>, generation: u64) {
|
||||
let Some(cancel) = server.starting_status(generation, &self.sink) else { return };
|
||||
let registration = if is_local_jdtls(&server.config) {
|
||||
let coordinator = self.java_build_coordinator.read().clone();
|
||||
match coordinator.register(&server, generation, self.server_workspace_roots(&server), &cancel).await {
|
||||
Ok(registration) => Some(registration),
|
||||
Err(_) => return,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Includes settings/prepare, blocking-pool queueing, launch and initialize.
|
||||
let started = std::time::Instant::now();
|
||||
tracing::info!(server = ?server.id, generation, name = %server.name, "starting language server");
|
||||
@@ -1242,7 +1260,7 @@ impl LspManager {
|
||||
}
|
||||
Self::kill_peer(&server, &peer).await;
|
||||
// Treated like a crash so transient failures retry with backoff.
|
||||
self.spawn_supervisor(server, generation, peer);
|
||||
self.spawn_supervisor(server, generation, peer, registration);
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -1309,13 +1327,24 @@ impl LspManager {
|
||||
self.check_vue_navigation(&server).await;
|
||||
server.refresh_busy_status(&self.sink);
|
||||
server.announce_ready(generation);
|
||||
self.spawn_supervisor(server, generation, peer);
|
||||
self.spawn_supervisor(server, generation, peer, registration);
|
||||
}
|
||||
|
||||
fn spawn_supervisor(&self, server: Arc<Server>, generation: u64, peer: ide_jsonrpc::Peer) {
|
||||
fn spawn_supervisor(
|
||||
&self,
|
||||
server: Arc<Server>,
|
||||
generation: u64,
|
||||
peer: ide_jsonrpc::Peer,
|
||||
registration: Option<java_build_coordinator::Registration>,
|
||||
) {
|
||||
let weak = self.me.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let code = peer.closed().await;
|
||||
if registration.is_some() && peer.pid().is_some() {
|
||||
peer.kill();
|
||||
peer.exited().await;
|
||||
}
|
||||
drop(registration);
|
||||
if let Some(me) = weak.upgrade() {
|
||||
me.on_instance_closed(server, generation, code).await;
|
||||
}
|
||||
@@ -4723,7 +4752,7 @@ impl LspManager {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let current = s.effective_config();
|
||||
let current = s.instance_config();
|
||||
let locale_changed = s.effective_locale().is_some_and(|l| l != next_locale);
|
||||
if next == current && !locale_changed {
|
||||
continue;
|
||||
@@ -5035,6 +5064,7 @@ impl LspManager {
|
||||
Self::kill_peer(server, &peer).await;
|
||||
if is_local_jdtls(&server.config) {
|
||||
let _startup = server.startup_lock.lock().await;
|
||||
self.java_build_coordinator.read().retire(server.id, run.generation);
|
||||
}
|
||||
server.end_stop(run.generation, &self.sink);
|
||||
self.file_watch_roots_changed();
|
||||
|
||||
@@ -207,6 +207,7 @@ pub struct Server {
|
||||
/// JDT retirement waits for launch and initialization cleanup, even before `Ready`.
|
||||
pub startup_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
pub java_autobuild_suspended: std::sync::atomic::AtomicBool,
|
||||
pub java_coordinated_autobuild_suspended: std::sync::atomic::AtomicBool,
|
||||
pub external_project: tokio::sync::Mutex<crate::external_project::State>,
|
||||
pub external_diagnostics: std::sync::atomic::AtomicBool,
|
||||
pub external_refresh_queued: std::sync::atomic::AtomicBool,
|
||||
@@ -262,6 +263,7 @@ impl Server {
|
||||
java_absent_outputs: Mutex::new(Default::default()),
|
||||
startup_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
java_autobuild_suspended: std::sync::atomic::AtomicBool::new(false),
|
||||
java_coordinated_autobuild_suspended: std::sync::atomic::AtomicBool::new(false),
|
||||
external_project: tokio::sync::Mutex::new(Default::default()),
|
||||
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
|
||||
external_refresh_queued: std::sync::atomic::AtomicBool::new(false),
|
||||
@@ -273,8 +275,10 @@ impl Server {
|
||||
|
||||
/// Configuration of the current (or last) instance; the base config before the first launch.
|
||||
pub fn effective_config(&self) -> LanguageServerConfig {
|
||||
let mut config = self.effective.lock().clone().unwrap_or_else(|| self.config.clone());
|
||||
if self.java_autobuild_suspended.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
let mut config = self.instance_config();
|
||||
if self.java_autobuild_suspended.load(std::sync::atomic::Ordering::SeqCst)
|
||||
|| self.java_coordinated_autobuild_suspended.load(std::sync::atomic::Ordering::SeqCst)
|
||||
{
|
||||
let mut settings = crate::handler::all_settings(&config);
|
||||
settings["java"]["autobuild"]["enabled"] = serde_json::json!(false);
|
||||
config.settings = Some(settings);
|
||||
@@ -282,6 +286,11 @@ impl Server {
|
||||
config
|
||||
}
|
||||
|
||||
/// Settings used to launch the instance, before temporary builder suspension.
|
||||
pub fn instance_config(&self) -> LanguageServerConfig {
|
||||
self.effective.lock().clone().unwrap_or_else(|| self.config.clone())
|
||||
}
|
||||
|
||||
/// The configured server's display name for the current (or last) instance.
|
||||
pub fn display_name(&self) -> Option<String> {
|
||||
self.effective.lock().as_ref().and_then(|c| c.display_name.clone())
|
||||
|
||||
@@ -315,7 +315,14 @@ type MockLanguage<'a> = (&'a str, &'a str, &'a [(&'a str, Value)]);
|
||||
|
||||
/// Several languages; documents open as the first.
|
||||
fn harness_languages(languages: &[MockLanguage<'_>], adjust: impl Fn(&mut LanguageServerConfig)) -> Harness {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
harness_languages_in(tempfile::tempdir().unwrap(), languages, adjust)
|
||||
}
|
||||
|
||||
fn harness_languages_in(
|
||||
dir: tempfile::TempDir,
|
||||
languages: &[MockLanguage<'_>],
|
||||
adjust: impl Fn(&mut LanguageServerConfig),
|
||||
) -> Harness {
|
||||
// Edits and references report canonical paths.
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let configs = languages
|
||||
@@ -3320,6 +3327,74 @@ async fn java_build_waits_for_a_reconfigured_server_to_restart() {
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_overlapping_windows_coordinate_autobuild_and_explicit_builds() {
|
||||
let configure = |cfg: &mut LanguageServerConfig| {
|
||||
cfg.settings = Some(json!({"java": {"autobuild": {"enabled": true}}}));
|
||||
};
|
||||
let parent = harness_configured("java", "java", &[("jdtls", incremental_caps())], configure);
|
||||
let child = harness_languages_in(
|
||||
tempfile::tempdir_in(&parent.root).unwrap(),
|
||||
&[("java", "java", &[("jdtls", incremental_caps())])],
|
||||
configure,
|
||||
);
|
||||
let coordinator = Arc::new(ide_lsp::JavaBuildCoordinator::default());
|
||||
parent.mgr.set_java_build_coordinator(coordinator.clone());
|
||||
child.mgr.set_java_build_coordinator(coordinator);
|
||||
parent.open("Parent.java", "class Parent {}");
|
||||
parent.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
child.open("Child.java", "class Child {}");
|
||||
child.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let (primary, secondary) = (parent.launcher.state("jdtls"), child.launcher.state("jdtls"));
|
||||
assert_eq!(
|
||||
primary.requested("initialize")[0]["initializationOptions"]["settings"]["java"]["autobuild"]["enabled"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
secondary.requested("initialize")[0]["initializationOptions"]["settings"]["java"]["autobuild"]["enabled"],
|
||||
false
|
||||
);
|
||||
child.mgr.reconfigure().await;
|
||||
assert_eq!(secondary.launches.load(Ordering::SeqCst), 1);
|
||||
|
||||
primary.respond("workspace/executeCommand", json!({}));
|
||||
primary.peer().notify("language/status", json!({"type": "ServiceReady", "message": "ServiceReady"})).unwrap();
|
||||
secondary.respond("java/buildWorkspace", json!(1));
|
||||
assert_eq!(
|
||||
child.mgr.java_build(&child.root, false, &Default::default()).await.unwrap(),
|
||||
ide_lsp::jdtls::JavaBuildStatus::Succeeded
|
||||
);
|
||||
assert!(primary.requested("workspace/executeCommand").iter().any(|p| p["command"] == "java.project.getClasspaths"));
|
||||
eventually(|| {
|
||||
primary
|
||||
.notified("workspace/didChangeConfiguration")
|
||||
.last()
|
||||
.is_some_and(|p| p["settings"]["java"]["autobuild"]["enabled"] == true)
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
primary
|
||||
.notified("workspace/didChangeConfiguration")
|
||||
.iter()
|
||||
.any(|p| p["settings"]["java"]["autobuild"]["enabled"] == false)
|
||||
);
|
||||
assert!(
|
||||
secondary
|
||||
.notified("workspace/didChangeConfiguration")
|
||||
.iter()
|
||||
.all(|p| p["settings"]["java"]["autobuild"]["enabled"] == false)
|
||||
);
|
||||
parent.mgr.shutdown_all().await;
|
||||
eventually(|| {
|
||||
secondary
|
||||
.notified("workspace/didChangeConfiguration")
|
||||
.last()
|
||||
.is_some_and(|p| p["settings"]["java"]["autobuild"]["enabled"] == true)
|
||||
})
|
||||
.await;
|
||||
child.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_build_asks_for_a_full_build_when_rebuilding() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
|
||||
@@ -2152,3 +2152,84 @@ async fn some_sass_indented_end_to_end() {
|
||||
assert!(errors.iter().any(|d| d.range.start.line >= 5), "{errors:?}");
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// #7733: opening a reactor and its child in independent windows must not
|
||||
/// run a second automatic compiler over the existing Maven output directories.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS), a compatible JDK and Maven"]
|
||||
async fn jdtls_overlapping_windows_do_not_rebuild_the_same_maven_outputs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap().join("reactor");
|
||||
let child = root.join("core");
|
||||
let source = child.join("src/main/java/demo/Greeter.java");
|
||||
std::fs::create_dir_all(source.parent().unwrap()).unwrap();
|
||||
std::fs::write(root.join("pom.xml"), r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>reactor</artifactId><version>1</version><packaging>pom</packaging><modules><module>core</module></modules><properties><maven.compiler.release>21</maven.compiler.release></properties></project>"#).unwrap();
|
||||
std::fs::write(child.join("pom.xml"), r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>reactor</artifactId><version>1</version></parent><artifactId>core</artifactId></project>"#).unwrap();
|
||||
let text = "package demo;\npublic class Greeter { public int value() { return 1; } }\n";
|
||||
std::fs::write(&source, text).unwrap();
|
||||
let coordinator = Arc::new(ide_lsp::JavaBuildCoordinator::default());
|
||||
let create = |root: &Path, workspace: &str| {
|
||||
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
|
||||
java.language_servers.retain(|s| s.name == "jdtls");
|
||||
let server = &mut java.language_servers[0];
|
||||
if let Ok(bin) = std::env::var("OPENIDEA_TEST_JDTLS") {
|
||||
server.command = bin;
|
||||
}
|
||||
server.args.extend(["-data".into(), dir.path().join(workspace).to_string_lossy().into_owned()]);
|
||||
let (mgr, events) = manager(root, LanguageRegistry::from_configs(vec![java]));
|
||||
mgr.set_java_build_coordinator(coordinator.clone());
|
||||
(mgr, events)
|
||||
};
|
||||
let (parent, _) = create(&root, "parent-data");
|
||||
let (secondary, _) = create(&child, "child-data");
|
||||
let parent_doc = DocId::next();
|
||||
parent.did_open(parent_doc, &source, &LanguageId::new("java"), 1, text);
|
||||
assert_eq!(
|
||||
parent.java_build(&child, false, &Default::default()).await.unwrap(),
|
||||
ide_lsp::jdtls::JavaBuildStatus::Succeeded
|
||||
);
|
||||
let output = child.join("target/classes/demo/Greeter.class");
|
||||
let before = std::fs::metadata(&output).unwrap().modified().unwrap();
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
|
||||
let child_doc = DocId::next();
|
||||
secondary.did_open(child_doc, &source, &LanguageId::new("java"), 1, text);
|
||||
secondary
|
||||
.wait_jdtls_imported(&source, tokio::time::Instant::now() + Duration::from_secs(120), &Default::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let cp = secondary.java_classpath(&child, false, &Default::default()).await.unwrap();
|
||||
assert!(cp.class_paths.iter().any(|p| p.ends_with("target/classes") || p.ends_with("target\\classes")));
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
assert_eq!(
|
||||
std::fs::metadata(&output).unwrap().modified().unwrap(),
|
||||
before,
|
||||
"the secondary workspace automatically rebuilt the shared class"
|
||||
);
|
||||
eprintln!("secondary imported the Maven project without rewriting Greeter.class");
|
||||
|
||||
assert_eq!(
|
||||
secondary.java_build(&child, false, &Default::default()).await.unwrap(),
|
||||
ide_lsp::jdtls::JavaBuildStatus::Succeeded
|
||||
);
|
||||
parent.shutdown_all().await;
|
||||
let changed = text.replace("return 1;", "return 2;");
|
||||
let line = text.lines().nth(1).unwrap();
|
||||
secondary.did_change(
|
||||
child_doc,
|
||||
2,
|
||||
&[AppliedChange {
|
||||
range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)),
|
||||
text: changed.lines().nth(1).unwrap().to_owned(),
|
||||
}],
|
||||
&|| changed.clone(),
|
||||
);
|
||||
std::fs::write(&source, &changed).unwrap();
|
||||
secondary.did_save(child_doc, &changed);
|
||||
let previous = std::fs::read(&output).unwrap();
|
||||
retry("promoted secondary automatically compiles the saved change", Duration::from_secs(60), || async {
|
||||
std::fs::read(&output).ok().filter(|bytes| bytes != &previous).map(|_| ())
|
||||
})
|
||||
.await;
|
||||
secondary.shutdown_all().await;
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача