Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ mapping.
If you disable the built-in Java tasks and provide your own main-method task,
add `"ZED_JAVA_RUNNABLE": "main"` to that task's `env` object to opt in. Its
environment variables are forwarded to the debug configuration, excluding the
locator's `ZED_JAVA_RUNNABLE` and `ZED_JAVA_MAIN_CLASS` metadata. Test runnables
are not handled by this locator.
locator's `ZED_JAVA_RUNNABLE` and `ZED_JAVA_MAIN_CLASS` metadata.

### Main methods with JDTLS

Expand Down Expand Up @@ -224,6 +223,29 @@ installation, and its DAP proxy to be enabled. The Scala extension's
[debugging documentation](https://github.com/scalameta/metals-zed#debugging)
describes its setup and restrictions.

### Test gutter actions

Test method and class tasks use the `ZED_JAVA_RUNNABLE=test-method` and
`ZED_JAVA_RUNNABLE=test-class` markers. Their existing Run commands are preserved.
The locator creates a `testTarget` containing the source file, class, optional
outer class, and optional method. Discovery and compilation happen only when
you select Debug; creating the gutter action does not contact a language server.
Project-wide test tasks are not converted to debug scenarios.

With JDTLS, the first test debug launch downloads the pinned Microsoft Java Test
Runner. The extension loads the bundles into the running language server, discovers
tests in the selected file, and resolves the framework's launch arguments. JUnit
methods use their JDT handles, including parameter types.
TestNG uses its bundled runner. A local callback socket receives the test runner's
result protocol; this does not provide a test-results explorer. Build failures,
missing targets, and ambiguous method names stop the launch.

Test gutter debugging is available with the `Java` adapter. All invocations of a
parameterized method are selected together.

Custom project tasks that replace the built-in Java tasks must also include the
appropriate marker. Select `Java` in `languages.Java.debuggers` for test debugging.

### Debugging with JDTLS

Debug support is enabled via our [Fork of Java Debug](https://github.com/zed-industries/java-debug), which the extension will automatically download and start for you. Please refer to the [Zed Documentation](https://zed.dev/docs/debugger#getting-started) for general information about how debugging works in Zed.
Expand Down
12 changes: 12 additions & 0 deletions debug_adapter_schemas/Java.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@
"type": "string",
"description": "The absolute path to a Java source file. Use $ZED_FILE for the currently focused Java source file. Resolves the main class and project from this file and builds before launch. Use mainClass and projectName to disambiguate multiple entries."
},
"testTarget": {
"type": "object",
"description": "Resolve a test class or method from its source file when debugging starts. Requires the bundled Java Test Runner with JDTLS.",
"properties": {
"file": { "type": "string" },
"className": { "type": "string" },
"outerClass": { "type": "string" },
"method": { "type": "string" }
},
"required": ["file", "className"],
"additionalProperties": false
},
"args": {
"oneOf": [
{
Expand Down
6 changes: 6 additions & 0 deletions languages/java/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
"java-test-method",
"java-test-method-nested"
],
"env": {
"ZED_JAVA_RUNNABLE": "test-method"
},
"shell": {
"with_arguments": {
"program": "/bin/sh",
Expand All @@ -47,6 +50,9 @@
"java-test-class",
"java-test-class-nested"
],
"env": {
"ZED_JAVA_RUNNABLE": "test-class"
},
"shell": {
"with_arguments": {
"program": "/bin/sh",
Expand Down
42 changes: 39 additions & 3 deletions proxy/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,19 @@ struct HttpBody {
impl HttpBody {
fn timeout(&self) -> Duration {
if self.method == "workspace/executeCommand"
&& self.params.get("command").and_then(Value::as_str)
== Some("vscode.java.buildWorkspace")
&& self
.params
.get("command")
.and_then(Value::as_str)
.is_some_and(|command| {
matches!(
command,
"vscode.java.buildWorkspace"
| "java.reloadBundles"
| "vscode.java.test.findTestTypesAndMethods"
| "vscode.java.test.junit.argument"
)
})
{
BUILD_TIMEOUT
} else {
Expand Down Expand Up @@ -91,6 +102,27 @@ pub fn handle_http(
}
};

if req.method == "zed/javaTestRunner/start" {
let result = req.params["adapterPort"]
.as_u64()
.and_then(|port| u16::try_from(port).ok())
.filter(|port| *port > 0)
.ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid DAP port")
})
.and_then(crate::test_runner::start);
let response = match result {
Ok((dap_port, result_port)) => serde_json::json!({
"result": { "dapPort": dap_port, "resultPort": result_port }
}),
Err(error) => serde_json::json!({
"error": { "code": -32603, "message": error.to_string() }
}),
};
write_response(&mut stream, &response);
return;
}

let seq = counter.fetch_add(1, Ordering::Relaxed);
let id = Value::String(format!("{owned_id_prefix}http-{seq}"));
let rx = pending.register(id.clone());
Expand Down Expand Up @@ -147,7 +179,11 @@ pub fn handle_http(
})
};

let resp_body = serde_json::to_vec(&response).unwrap();
write_response(&mut stream, &response);
}

fn write_response(stream: &mut std::net::TcpStream, response: &Value) {
let resp_body = serde_json::to_vec(response).unwrap();
let http_resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n",
resp_body.len()
Expand Down
1 change: 1 addition & 0 deletions proxy/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod http;
mod log;
mod output;
mod pending;
mod test_runner;

use completions::{process_completions, sanitize_resolved_completion};
use decompile::{DecompileCoordinator, Priority, RewriteJob, RewriteMode, SharedWriter};
Expand Down
168 changes: 168 additions & 0 deletions proxy/src/test_runner.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
use std::{
io::{self, Read},
net::{Shutdown, TcpListener, TcpStream},
sync::atomic::{AtomicBool, Ordering},
thread,
time::{Duration, Instant},
};

const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const POLL_INTERVAL: Duration = Duration::from_millis(25);

pub fn start(adapter_port: u16) -> io::Result<(u16, u16)> {
let dap = bind_listener()?;
let results = bind_listener()?;
let ports = (dap.local_addr()?.port(), results.local_addr()?.port());
thread::Builder::new()
.name("java-test-session".into())
.spawn(move || {
if let Err(error) = serve(dap, results, adapter_port, CONNECT_TIMEOUT) {
crate::lsp_warn!("Java test session ended: {error}");
}
})?;
Ok(ports)
}

fn bind_listener() -> io::Result<TcpListener> {
let listener = TcpListener::bind("127.0.0.1:0")?;
listener.set_nonblocking(true)?;
Ok(listener)
}

fn accept(listener: TcpListener, keep_waiting: impl Fn() -> bool) -> io::Result<Option<TcpStream>> {
while keep_waiting() {
match listener.accept() {
Ok((stream, _)) => {
stream.set_nonblocking(false)?;
return Ok(Some(stream));
}
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
thread::sleep(POLL_INTERVAL);
}
Err(error) => return Err(error),
}
}
Ok(None)
}

fn serve(
dap: TcpListener,
results: TcpListener,
adapter_port: u16,
timeout: Duration,
) -> io::Result<()> {
let deadline = Instant::now() + timeout;
let Some(editor) = accept(dap, || Instant::now() < deadline)? else {
return Ok(());
};
let adapter = TcpStream::connect_timeout(&([127, 0, 0, 1], adapter_port).into(), timeout)?;
let finished = AtomicBool::new(false);
thread::scope(|scope| {
scope.spawn(|| {
if let Err(error) = drain_results(results, &finished) {
crate::lsp_warn!("Java test result connection ended: {error}");
}
});
let result = relay(&editor, &adapter);
finished.store(true, Ordering::Relaxed);
result
})
}

fn relay(editor: &TcpStream, adapter: &TcpStream) -> io::Result<()> {
editor.set_nodelay(true)?;
adapter.set_nodelay(true)?;
thread::scope(|scope| {
let request = scope.spawn(|| forward(editor, adapter));
let response = forward(adapter, editor);
let request = request.join().unwrap();
response.and(request)
})
}

fn forward(mut source: &TcpStream, mut destination: &TcpStream) -> io::Result<()> {
let result = io::copy(&mut source, &mut destination).map(|_| ());
let _ = source.shutdown(Shutdown::Both);
let _ = destination.shutdown(Shutdown::Both);
result
}

fn drain_results(listener: TcpListener, finished: &AtomicBool) -> io::Result<()> {
let active = || !finished.load(Ordering::Relaxed);
let Some(mut stream) = accept(listener, active)? else {
return Ok(());
};
stream.set_read_timeout(Some(POLL_INTERVAL))?;
let mut buffer = [0; 4096];
while active() {
match stream.read(&mut buffer) {
Ok(0) => break,
Ok(_) => {}
Err(error)
if matches!(
error.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
) => {}
Err(error) => return Err(error),
}
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;

#[test]
fn editor_disconnect_releases_results_with_or_without_a_connected_runner() {
for connect_runner in [false, true] {
let adapter = TcpListener::bind("127.0.0.1:0").unwrap();
let adapter_port = adapter.local_addr().unwrap().port();
let dap = bind_listener().unwrap();
let results = bind_listener().unwrap();
let address = results.local_addr().unwrap();
let mut editor = TcpStream::connect(dap.local_addr().unwrap()).unwrap();
let runner = connect_runner.then(|| TcpStream::connect(address).unwrap());
let handler = thread::spawn(move || serve(dap, results, adapter_port, CONNECT_TIMEOUT));
let (mut adapter, _) = adapter.accept().unwrap();
editor
.set_read_timeout(Some(Duration::from_secs(1)))
.unwrap();
adapter
.set_read_timeout(Some(Duration::from_secs(1)))
.unwrap();
let mut message = [0];
editor.write_all(b"J").unwrap();
adapter.read_exact(&mut message).unwrap();
assert_eq!(&message, b"J");
adapter.write_all(b"D").unwrap();
editor.read_exact(&mut message).unwrap();
assert_eq!(&message, b"D");
drop(editor);
handler.join().unwrap().unwrap();
assert!(TcpStream::connect(address).is_err());
if let Some(mut runner) = runner {
runner
.set_read_timeout(Some(Duration::from_secs(1)))
.unwrap();
match runner.read(&mut message) {
Ok(0) => {}
Err(error) if error.kind() == io::ErrorKind::ConnectionReset => {}
result => panic!("Expected the result connection to close, got {result:?}"),
}
}
}
}

#[test]
fn both_ports_close_when_editor_never_connects() {
let dap = bind_listener().unwrap();
let results = bind_listener().unwrap();
let dap_address = dap.local_addr().unwrap();
let result_address = results.local_addr().unwrap();
serve(dap, results, 1, POLL_INTERVAL).unwrap();
assert!(TcpStream::connect(dap_address).is_err());
assert!(TcpStream::connect(result_address).is_err());
}
}
Loading