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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2019 Red Hat Inc. and others.
* Copyright (c) 2019, 2026 Red Hat Inc. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
Expand All @@ -14,9 +14,11 @@

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.File;
import java.time.Duration;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
Expand All @@ -29,9 +31,12 @@
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
Expand All @@ -56,8 +61,11 @@
import org.eclipse.ui.tests.harness.util.DisplayHelper;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.wildwebdeveloper.debug.LaunchConstants;
import org.eclipse.wildwebdeveloper.debug.node.DebugAdapter;
import org.eclipse.wildwebdeveloper.debug.node.NodeAttachDebugDelegate;
import org.eclipse.wildwebdeveloper.debug.node.NodeRunDAPDebugDelegate;
import org.eclipse.wildwebdeveloper.debug.node.NodeRunDebugLaunchShortcut;
import org.eclipse.wildwebdeveloper.embedder.node.NodeJSManager;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -110,6 +118,71 @@ public void tearDownLaunch() throws DebugException {
removeAllLaunches();
}

@Test
public void testAttachHonorsCanceledMonitor() throws Exception {
final var config = launchManager
.getLaunchConfigurationType("org.eclipse.wildwebdeveloper.launchConfiguration.nodeDebugAttach")
.newInstance(ResourcesPlugin.getWorkspace().getRoot(), "canceledAttach");
config.setAttribute("address", "127.0.0.1");
config.setAttribute(LaunchConstants.PORT, 9229);
final ILaunch launch = new Launch(config, ILaunchManager.DEBUG_MODE, null);
launchManager.addLaunch(launch);
final var monitor = new NullProgressMonitor();
monitor.setCanceled(true);

final var error = assertThrows(CoreException.class,
() -> new NodeAttachDebugDelegate().launch(config, ILaunchManager.DEBUG_MODE, launch, monitor));
assertTrue(error.getStatus().getMessage().contains("canceled"), "Cancellation was not reported");
assertTrue(DisplayHelper.waitForCondition(Display.getDefault(), 5_000,
() -> Arrays.stream(launch.getProcesses()).allMatch(IProcess::isTerminated)), "Adapter process was not stopped");
}

@Test
public void testAdapterExitDuringStartupReportsErrorOutput() throws Exception {
final DebugAdapter adapter = startFakeAdapter("console.error('boom'); process.exit(1)");

final var error = assertThrows(CoreException.class,
() -> adapter.awaitListening(new NullProgressMonitor(), Duration.ofSeconds(10)));
assertTrue(error.getStatus().getMessage().contains("exited"), error.getStatus().getMessage());
assertTrue(error.getStatus().getMessage().contains("boom"), error.getStatus().getMessage());
}

@Test
public void testAdapterHandshakeTimeout() throws Exception {
final DebugAdapter adapter = startFakeAdapter("console.log('listening'); setInterval(() => {}, 1000)");
adapter.awaitListening(new NullProgressMonitor(), Duration.ofSeconds(10));

final var error = assertThrows(CoreException.class, () -> adapter.connect(new NullProgressMonitor(),
Duration.ofSeconds(1), TestDebug::waitForCancellation));
assertTrue(error.getStatus().getMessage().contains("did not complete"), error.getStatus().getMessage());
}

@Test
public void testAdapterExitDuringHandshake() throws Exception {
final DebugAdapter adapter = startFakeAdapter(
"console.log('listening'); setTimeout(() => { console.error('boom'); process.exit(1) }, 500)");
adapter.awaitListening(new NullProgressMonitor(), Duration.ofSeconds(10));

final var error = assertThrows(CoreException.class, () -> adapter.connect(new NullProgressMonitor(),
Duration.ofSeconds(30), TestDebug::waitForCancellation));
assertTrue(error.getStatus().getMessage().contains("exited"), error.getStatus().getMessage());
assertTrue(error.getStatus().getMessage().contains("boom"), error.getStatus().getMessage());
}

private DebugAdapter startFakeAdapter(String script) throws CoreException {
final ILaunch launch = new Launch(null, ILaunchManager.DEBUG_MODE, null);
return DebugAdapter.start(launch,
new String[] { NodeJSManager.getNodeJsLocation().getAbsolutePath(), "-e", script },
new File(System.getProperty("user.dir")));
}

/** Like LSP4E, returns normally once canceled. */
private static void waitForCancellation(IProgressMonitor monitor) {
while (!monitor.isCanceled()) {
Thread.onSpinWait();
}
}

@Test
public void testRunExpandEnv() throws Exception {
File f = File.createTempFile("testEnv", ".js");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
/*******************************************************************************
* Copyright (c) 2026 Vogella GmbH and others.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Lars Vogel (Vogella GmbH) - initial implementation
*******************************************************************************/
package org.eclipse.wildwebdeveloper.debug.node;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.IStreamListener;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.core.model.IStreamMonitor;

/**
* A debug adapter server process, whose startup and DAP handshake fail instead of hanging.
*/
public class DebugAdapter {

/** Performs the DAP handshake, which must stop when the monitor is canceled. */
@FunctionalInterface
public interface Handshake {
void run(IProgressMonitor monitor) throws CoreException;
}

public static final String HOST = "127.0.0.1"; //$NON-NLS-1$

private static final int MAX_OUTPUT = 10_000;

private final ILaunch launch;
private final Process process;
private final IProcess debugProcess;
private final StringBuilder output = new StringBuilder();
private final StringBuilder standardOutput = new StringBuilder();
private volatile boolean listening;

public static int findFreePort() throws CoreException {
try (ServerSocket serverSocket = new ServerSocket(0)) {
return serverSocket.getLocalPort();
} catch (IOException ex) {
throw new CoreException(Status.error("No free port for the debug adapter.", ex)); //$NON-NLS-1$
}
}

public static DebugAdapter start(ILaunch launch, String[] commandLine, File workingDirectory) throws CoreException {
Map<String, String> environment = new HashMap<>(System.getenv());
environment.put("DA_TEST_DISABLE_TELEMETRY", Boolean.TRUE.toString()); //$NON-NLS-1$
Process process = DebugPlugin.exec(commandLine, workingDirectory,
environment.entrySet().stream().map(e -> e.getKey() + '=' + e.getValue()).toArray(String[]::new), false);
return new DebugAdapter(launch, process);
}

private DebugAdapter(ILaunch launch, Process process) {
this.launch = launch;
this.process = process;
this.debugProcess = DebugPlugin.newProcess(launch, process, "debug adapter"); //$NON-NLS-1$
listen(debugProcess.getStreamsProxy().getOutputStreamMonitor(), (text, monitor) -> {
append(text);
if (!listening) {
// the announcement may be split across several callbacks
standardOutput.append(text);
listening = standardOutput.indexOf("listening") >= 0; //$NON-NLS-1$
}
});
listen(debugProcess.getStreamsProxy().getErrorStreamMonitor(), (text, monitor) -> {
append(text);
if (!text.isBlank()) {
ILog.get().warn("Debug adapter (stderr): " + text.trim()); //$NON-NLS-1$
// also visible in the build logs of CI
System.err.println("Debug adapter (stderr): " + text.trim()); //$NON-NLS-1$
}
});
}

private static void listen(IStreamMonitor monitor, IStreamListener listener) {
// also replay what arrived before the listener was added
synchronized (monitor) {
monitor.addListener(listener);
listener.streamAppended(monitor.getContents(), monitor);
}
}

private void append(String text) {
synchronized (output) {
output.append(text);
output.delete(0, Math.max(0, output.length() - MAX_OUTPUT));
}
}

/**
* Waits until the adapter accepts connections. An adapter which is still running
* after the timeout is left to the handshake.
*/
public void awaitListening(IProgressMonitor monitor, Duration timeout) throws CoreException {
long deadline = System.nanoTime() + timeout.toNanos();
while (!listening && System.nanoTime() < deadline) {
if (monitor != null && monitor.isCanceled()) {
destroy();
throw canceled();
}
if (!process.isAlive()) {
throw failed("Debug adapter process exited.", null); //$NON-NLS-1$
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
destroy();
Thread.currentThread().interrupt();
throw canceled();
}
}
if (!listening) {
ILog.get().warn("Debug adapter did not report a listening port in time. Adapter output so far: " + output()); //$NON-NLS-1$
}
}

/**
* Runs the handshake, canceling it if the adapter exits or the timeout elapses.
* The adapter is destroyed unless the handshake succeeds.
*/
public void connect(IProgressMonitor monitor, Duration timeout, Handshake handshake) throws CoreException {
SubMonitor handshakeMonitor = SubMonitor.convert(monitor);
AtomicReference<String> failure = new AtomicReference<>();
Thread watchdog = new Thread(() -> watch(handshakeMonitor, timeout, failure), "WWD debug launch watchdog"); //$NON-NLS-1$
watchdog.setDaemon(true);
watchdog.start();
boolean connected = false;
try {
try {
handshake.run(handshakeMonitor);
} catch (CoreException | RuntimeException ex) {
if (failure.get() != null) {
throw failed(failure.get(), ex);
}
if (ex instanceof OperationCanceledException) {
throw canceled();
}
throw ex;
}
// LSP4E returns normally from a canceled launch
if (failure.get() != null) {
throw failed(failure.get(), null);
}
if (handshakeMonitor.isCanceled()) {
throw canceled();
}
connected = true;
} finally {
watchdog.interrupt();
if (!connected) {
destroy();
}
}
}

private void watch(IProgressMonitor monitor, Duration timeout, AtomicReference<String> failure) {
long deadline = System.nanoTime() + timeout.toNanos();
try {
while (!monitor.isCanceled()) {
if (!process.isAlive()) {
failure.set("Debug adapter process exited."); //$NON-NLS-1$
} else if (System.nanoTime() >= deadline) {
logThreadDump();
failure.set("Debug adapter handshake did not complete within " + timeout.toSeconds() + " seconds."); //$NON-NLS-1$ //$NON-NLS-2$
}
if (failure.get() != null) {
monitor.setCanceled(true);
return;
}
Thread.sleep(100);
}
} catch (InterruptedException ex) {
// handshake completed
}
}

private static void logThreadDump() {
StringBuilder dump = new StringBuilder("Debug adapter handshake timed out.\n"); //$NON-NLS-1$
Thread.getAllStackTraces().forEach((thread, stack) -> {
dump.append('"').append(thread.getName()).append("\" state=").append(thread.getState()).append('\n'); //$NON-NLS-1$
for (StackTraceElement element : stack) {
dump.append(" at ").append(element).append('\n'); //$NON-NLS-1$
}
});
ILog.get().error(dump.toString());
System.err.println(dump);
}

/** Terminates the adapter once all debug targets and other processes of the launch ended. */
public void terminateWithLaunch() {
DebugPlugin.getDefault().addDebugEventListener(new IDebugEventSetListener() {
@Override
public void handleDebugEvents(DebugEvent[] events) {
if (Arrays.stream(events).anyMatch(event -> event.getKind() == DebugEvent.TERMINATE
&& event.getSource() instanceof final IDebugTarget target && target.getLaunch() == launch)
&& Arrays.stream(launch.getDebugTargets()).allMatch(IDebugTarget::isTerminated)
&& List.of(debugProcess).equals(Arrays.stream(launch.getProcesses())
.filter(Predicate.not(IProcess::isTerminated)).toList())) {
try {
debugProcess.terminate();
} catch (DebugException ex) {
destroy();
}
DebugPlugin.getDefault().removeDebugEventListener(this);
}
}
});
}

public void destroy() {
process.destroy();
}

private String output() {
synchronized (output) {
return output.toString().trim();
}
}

private CoreException failed(String reason, Throwable cause) {
// give the stream readers of an exited process the chance to finish
for (int i = 0; i < 20 && !process.isAlive() && !debugProcess.isTerminated(); i++) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
break;
}
}
destroy();
return new CoreException(Status.error(reason + " Adapter output: " + output(), cause)); //$NON-NLS-1$
}

private static CoreException canceled() {
return new CoreException(new Status(IStatus.CANCEL, DebugAdapter.class, "Debug adapter launch canceled.")); //$NON-NLS-1$
}
}
Loading
Loading