From 249683d4267651c55be81098f6c307e07043de38 Mon Sep 17 00:00:00 2001 From: Lars Vogel Date: Mon, 30 Nov 2026 13:13:31 +0100 Subject: [PATCH] Bound Node debug adapter startup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Share startup and DAP handshake handling between the Node debug delegates, so that cancellation, adapter exit and timeouts end the launch with an error which includes the adapter output. Assisted-by: multiple AI agents and layers of automated tooling 🤖 --- .../wildwebdeveloper/tests/TestDebug.java | 75 ++++- .../debug/node/DebugAdapter.java | 265 ++++++++++++++++++ .../debug/node/NodeAttachDebugDelegate.java | 83 +----- .../debug/node/VSCodeJSDebugDelegate.java | 166 ++--------- 4 files changed, 376 insertions(+), 213 deletions(-) create mode 100644 org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/DebugAdapter.java diff --git a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestDebug.java b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestDebug.java index 83269255f8..c86b638011 100644 --- a/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestDebug.java +++ b/org.eclipse.wildwebdeveloper.tests/src/org/eclipse/wildwebdeveloper/tests/TestDebug.java @@ -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 @@ -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; @@ -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; @@ -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; @@ -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"); diff --git a/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/DebugAdapter.java b/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/DebugAdapter.java new file mode 100644 index 0000000000..51bb099d1c --- /dev/null +++ b/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/DebugAdapter.java @@ -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 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 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 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$ + } +} diff --git a/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/NodeAttachDebugDelegate.java b/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/NodeAttachDebugDelegate.java index 9852dec441..d7abab4029 100644 --- a/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/NodeAttachDebugDelegate.java +++ b/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/NodeAttachDebugDelegate.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019, 2024 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 2.0 @@ -15,35 +15,19 @@ import java.io.File; import java.io.IOException; -import java.net.ServerSocket; import java.net.URL; import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Predicate; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; -import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.variables.VariablesPlugin; -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.ILaunchConfiguration; -import org.eclipse.debug.core.model.IDebugTarget; -import org.eclipse.debug.core.model.IProcess; -import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.lsp4e.debug.DSPPlugin; -import org.eclipse.swt.widgets.Display; import org.eclipse.wildwebdeveloper.debug.LaunchConstants; import org.eclipse.wildwebdeveloper.embedder.node.NodeJSManager; @@ -80,63 +64,26 @@ public void launch(ILaunchConfiguration configuration, String mode, ILaunch laun if (runtimeExecutable != null) { param.put(RUNTIME_EXECUTABLE, runtimeExecutable.getAbsolutePath()); } + File file; try { URL fileURL = FileLocator.toFileURL(getClass().getResource(NODE_DEBUG_CMD)); - File file = new File(fileURL.getPath()); - int port = 0; - try (ServerSocket serverSocket = new ServerSocket(0)) { - port = serverSocket.getLocalPort(); - } catch (IOException ex) { - ILog.get().error(ex.getMessage(), ex); - } - Process vscodeJsDebugExec = DebugPlugin.exec(new String[] { runtimeExecutable.getAbsolutePath(), file.getAbsolutePath(), Integer.toString(port) }, new File(System.getProperty("user.dir")), new String[] { "DA_TEST_DISABLE_TELEMETRY=true"}, false); - IProcess vscodeJsDebugIProcess = DebugPlugin.newProcess(launch, vscodeJsDebugExec, "debug adapter"); - AtomicBoolean started = new AtomicBoolean(); - vscodeJsDebugIProcess.getStreamsProxy().getOutputStreamMonitor().addListener((text, mon) -> { - if (text.toLowerCase().contains("listening")) { - started.set(true); - } - }); - Instant request = Instant.now(); - while (!started.get() && Duration.between(request, Instant.now()).compareTo(Duration.ofSeconds(3)) < 3) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - } - } - + file = new File(fileURL.getPath()); + } catch (IOException ex) { + throw new CoreException(Status.error("Debug adapter not found.", ex)); //$NON-NLS-1$ + } + int port = DebugAdapter.findFreePort(); + DebugAdapter adapter = DebugAdapter.start(launch, new String[] { runtimeExecutable.getAbsolutePath(), + file.getAbsolutePath(), Integer.toString(port), DebugAdapter.HOST }, new File(System.getProperty("user.dir"))); //$NON-NLS-1$ + adapter.awaitListening(monitor, Duration.ofSeconds(10)); + adapter.connect(monitor, Duration.ofMinutes(2), handshakeMonitor -> { DSPLaunchDelegateLaunchBuilder builder = new DSPLaunchDelegateLaunchBuilder(configuration, mode, launch, - monitor); - builder.setAttachDebugAdapter("::1", port); + handshakeMonitor); + builder.setAttachDebugAdapter(DebugAdapter.HOST, port); builder.setMonitorDebugAdapter(configuration.getAttribute(DSPPlugin.ATTR_DSP_MONITOR_DEBUG_ADAPTER, false)); builder.setDspParameters(param); super.launch(builder); - IDebugEventSetListener shutdownParentOnCompletion = 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)) { - if (Arrays.stream(launch.getDebugTargets()).allMatch(IDebugTarget::isTerminated) - && List.of(vscodeJsDebugIProcess).equals(Arrays.stream(launch.getProcesses()).filter(Predicate.not(IProcess::isTerminated)).toList())) { - try { - vscodeJsDebugIProcess.terminate(); - } catch (DebugException ex) { - vscodeJsDebugExec.destroy(); - } - DebugPlugin.getDefault().removeDebugEventListener(this); - } - } - } - }; - DebugPlugin.getDefault().addDebugEventListener(shutdownParentOnCompletion); - } catch (IOException e) { - IStatus errorStatus = Status.error(e.getMessage(), e); - ILog.get().log(errorStatus); - Display.getDefault().asyncExec(() -> ErrorDialog.openError(Display.getDefault().getActiveShell(), "Debug error", e.getMessage(), errorStatus)); //$NON-NLS-1$ - } - + }); + adapter.terminateWithLaunch(); } } diff --git a/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/VSCodeJSDebugDelegate.java b/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/VSCodeJSDebugDelegate.java index 54694e7ee6..6ddbed759d 100644 --- a/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/VSCodeJSDebugDelegate.java +++ b/org.eclipse.wildwebdeveloper/src/org/eclipse/wildwebdeveloper/debug/node/VSCodeJSDebugDelegate.java @@ -18,19 +18,15 @@ import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Type; -import java.net.ServerSocket; import java.net.URL; import java.nio.file.Path; import java.time.Duration; -import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Predicate; import java.util.regex.Pattern; import org.eclipse.core.resources.IContainer; @@ -47,20 +43,14 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.SubMonitor; +import org.eclipse.core.runtime.Status; import org.eclipse.core.variables.VariablesPlugin; -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.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchManager; -import org.eclipse.debug.core.model.IDebugTarget; -import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.internal.ui.DebugUIPlugin; import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.lsp4e.LanguageServerPlugin; import org.eclipse.lsp4e.debug.DSPPlugin; import org.eclipse.lsp4e.debug.launcher.DSPLaunchDelegate; import org.eclipse.swt.widgets.Display; @@ -171,144 +161,32 @@ public void launch(ILaunchConfiguration configuration, String mode, ILaunch laun return; } + File file; try { URL fileURL = FileLocator.toFileURL(getClass().getResource(NODE_DEBUG_CMD)); - File file = new File(fileURL.getPath()); - int port = 0; - try (ServerSocket serverSocket = new ServerSocket(0)) { - port = serverSocket.getLocalPort(); - } catch (IOException ex) { - ILog.get().error(ex.getMessage(), ex); - } - File cwdFile = cwd == null || cwd.isBlank() ? new File(System.getProperty("user.dir")) : new File(cwd); //$NON-NLS-1$ - Map processEnv = new HashMap<>(System.getenv()); - processEnv.put("DA_TEST_DISABLE_TELEMETRY", Boolean.TRUE.toString()); - // The debug server binds the host given as argv[2] (default: "localhost"). - // "localhost" may resolve to ::1 on some systems (e.g. certain CI agents), - // while the adapter's internal servers bind 127.0.0.1 explicitly, which - // breaks the debuggee's internal connections to the adapter and hangs - // debug launches. Bind 127.0.0.1 explicitly to keep everything IPv4. - Process vscodeJsDebugExec = DebugPlugin.exec(new String[] { NodeJSManager.getNodeJsLocation().getAbsolutePath(), file.getAbsolutePath(), Integer.toString(port), "127.0.0.1" }, cwdFile, processEnv.entrySet().stream().map(entry -> entry.getKey() + '=' + entry.getValue()).toArray(String[]::new), false); - IProcess vscodeJsDebugIProcess = DebugPlugin.newProcess(launch, vscodeJsDebugExec, "debug adapter"); - AtomicReference host = new AtomicReference<>(); // sometimes ::1, sometimes 127.0.0.1... - String portSuffix = ":" + port; - // The "listening :" announcement may be delivered split across - // several stream monitor callbacks, so the output is accumulated and the - // whole buffer is parsed on every callback instead of each chunk alone. - StringBuilder adapterOutput = new StringBuilder(); - vscodeJsDebugIProcess.getStreamsProxy().getOutputStreamMonitor().addListener((text, mon) -> { - if (text == null || text.isEmpty()) { - return; - } - synchronized (adapterOutput) { - adapterOutput.append(text); - if (host.get() == null) { - int listeningIndex = adapterOutput.indexOf("listening"); //$NON-NLS-1$ - if (listeningIndex >= 0) { - for (String word : adapterOutput.substring(listeningIndex).split("\\s+")) { //$NON-NLS-1$ - if (word.endsWith(portSuffix)) { - host.set(word.substring(0, word.length() - portSuffix.length())); - break; - } - } - } - } - } - }); - // Surface the debug adapter's stderr in the error log: it is otherwise only - // visible in the consoles and makes remote/troubleshooted launches hard to diagnose. - vscodeJsDebugIProcess.getStreamsProxy().getErrorStreamMonitor().addListener((text, mon) -> { - if (text != null && !text.isEmpty()) { - ILog.get().warn("Debug adapter (stderr): " + text.trim()); //$NON-NLS-1$ - System.err.println("Debug adapter (stderr): " + text.trim()); //$NON-NLS-1$ - } - }); - Instant deadline = Instant.now().plus(Duration.ofSeconds(10)); - while (host.get() == null && Instant.now().isBefore(deadline)) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - break; - } - } - if (host.get() == null) { - String outputSoFar; - synchronized (adapterOutput) { - outputSoFar = adapterOutput.toString(); - } - // Attaching with a null host falls back to the loopback address - ILog.get().warn("Debug adapter did not report a listening port in time, falling back to the loopback address. Adapter output so far: '" //$NON-NLS-1$ - + outputSoFar + "'"); //$NON-NLS-1$ - } - - // The DSP attach + DAP handshake (LSP4E DSPDebugTarget.initialize) waits for - // the adapter's responses without any timeout of its own and only aborts - // when the progress monitor is canceled. Bound it with a watchdog so a - // non-answering debug adapter fails the launch visibly (with a thread dump - // and adapter state for diagnosis) instead of hanging the launch forever. - SubMonitor launchMonitor = SubMonitor.convert(monitor); - Thread watchdog = new Thread(() -> { - try { - Thread.sleep(Duration.ofMinutes(2).toMillis()); - } catch (InterruptedException ex) { - return; // launch completed in time - } - if (!launchMonitor.isCanceled()) { - String outputSoFar; - synchronized (adapterOutput) { - outputSoFar = adapterOutput.toString(); - } - StringBuilder dump = new StringBuilder("Debug adapter launch did not complete within 2 minutes, canceling." //$NON-NLS-1$ - + " Debug adapter process alive: " + vscodeJsDebugExec.isAlive() //$NON-NLS-1$ - + ", output so far: '" + outputSoFar + "'.\n"); //$NON-NLS-1$ //$NON-NLS-2$ - Thread.getAllStackTraces().forEach((thread, stack) -> { - dump.append('"').append(thread.getName()).append('"') // - .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); - launchMonitor.setCanceled(true); - } - }, "WWD debug launch watchdog"); //$NON-NLS-1$ - watchdog.setDaemon(true); - watchdog.start(); + file = new File(fileURL.getPath()); + } catch (IOException ex) { + throw new CoreException(Status.error("Debug adapter not found.", ex)); //$NON-NLS-1$ + } + int port = DebugAdapter.findFreePort(); + File cwdFile = cwd == null || cwd.isBlank() ? new File(System.getProperty("user.dir")) : new File(cwd); //$NON-NLS-1$ + // The debug server binds the host given as argv[2] (default: "localhost"). + // "localhost" may resolve to ::1 on some systems (e.g. certain CI agents), + // while the adapter's internal servers bind 127.0.0.1 explicitly, which + // breaks the debuggee's internal connections to the adapter and hangs + // debug launches. Bind 127.0.0.1 explicitly to keep everything IPv4. + DebugAdapter adapter = DebugAdapter.start(launch, new String[] { NodeJSManager.getNodeJsLocation().getAbsolutePath(), + file.getAbsolutePath(), Integer.toString(port), DebugAdapter.HOST }, cwdFile); + adapter.awaitListening(monitor, Duration.ofSeconds(10)); + adapter.connect(monitor, Duration.ofMinutes(2), handshakeMonitor -> { DSPLaunchDelegateLaunchBuilder builder = new DSPLaunchDelegateLaunchBuilder(configuration, mode, launch, - launchMonitor); - builder.setAttachDebugAdapter(host.get(), port); + handshakeMonitor); + builder.setAttachDebugAdapter(DebugAdapter.HOST, port); builder.setMonitorDebugAdapter(configuration.getAttribute(DSPPlugin.ATTR_DSP_MONITOR_DEBUG_ADAPTER, false)); builder.setDspParameters(param); - try { - super.launch(builder); - } finally { - watchdog.interrupt(); - } - IDebugEventSetListener shutdownParentOnCompletion = 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)) { - if (Arrays.stream(launch.getDebugTargets()).allMatch(IDebugTarget::isTerminated) - && List.of(vscodeJsDebugIProcess).equals(Arrays.stream(launch.getProcesses()).filter(Predicate.not(IProcess::isTerminated)).toList())) { - try { - vscodeJsDebugIProcess.terminate(); - } catch (DebugException ex) { - vscodeJsDebugExec.destroy(); - } - DebugPlugin.getDefault().removeDebugEventListener(this); - } - } - } - }; - DebugPlugin.getDefault().addDebugEventListener(shutdownParentOnCompletion); - } catch (IOException ex) { - LanguageServerPlugin.logError(ex); - } + super.launch(builder); + }); + adapter.terminateWithLaunch(); } protected File computeRuntimeExecutable(ILaunchConfiguration configuration) {