From a4b23c45b99bce2be49bce3362e4028c2a1332a1 Mon Sep 17 00:00:00 2001 From: Parker Wahle Date: Wed, 2 Dec 2026 17:08:14 -0500 Subject: [PATCH] Stop waiting for a server that has exited When the language server's process ended, for example because the server crashed on start, the client waited forever: LSP4J leaves a request pending if no response comes, and the wait for a file's diagnostics never looked at the process. Fail each request still pending when the process ends, through an endpoint that wraps the one LSP4J creates, and stop waiting for diagnostics once the process has ended. Both report the server's exit code. Add a test server that exits on start, when a document is opened, or when code actions are requested. Fixes #69. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Mv4cZ3LFVAJ9aG5SntwnAr --- changelog.xml | 3 + .../org/bsplines/lspcli/client/Checker.kt | 2 + .../client/LanguageServerExitedException.kt | 16 ++ .../client/LanguageServerProcessEndpoint.kt | 42 ++++++ .../lspcli/client/LspCliLanguageClient.kt | 8 +- .../resources/LspCliMessagesBundle.properties | 1 + .../lspcli/client/LanguageServerExitTest.kt | 92 ++++++++++++ .../lspcli/testtools/ExitingLanguageServer.kt | 139 ++++++++++++++++++ 8 files changed, 302 insertions(+), 1 deletion(-) create mode 100644 src/main/kotlin/org/bsplines/lspcli/client/LanguageServerExitedException.kt create mode 100644 src/main/kotlin/org/bsplines/lspcli/client/LanguageServerProcessEndpoint.kt create mode 100644 src/test/kotlin/org/bsplines/lspcli/client/LanguageServerExitTest.kt create mode 100644 src/test/kotlin/org/bsplines/lspcli/testtools/ExitingLanguageServer.kt diff --git a/changelog.xml b/changelog.xml index 8aeb046..a37a32e 100644 --- a/changelog.xml +++ b/changelog.xml @@ -17,6 +17,9 @@ Stop waiting forever for diagnostics once the language server has logged more than a pipe holds, which on Windows (about 4 KB) took a few files. The language server's standard error output, where servers write their log, was a pipe that nothing read, so the server blocked in its next write to the log once the pipe was full. It is now discarded, or passed through to the standard error output with `--verbose`. + + Stop waiting forever for a language server whose process has ended, for example because it crashed on start. Waiting for the answer to `initialize`, for a file's diagnostics, or for code actions now fails with the server's exit code instead. + diff --git a/src/main/kotlin/org/bsplines/lspcli/client/Checker.kt b/src/main/kotlin/org/bsplines/lspcli/client/Checker.kt index 7cc5ce5..c25e69d 100644 --- a/src/main/kotlin/org/bsplines/lspcli/client/Checker.kt +++ b/src/main/kotlin/org/bsplines/lspcli/client/Checker.kt @@ -104,6 +104,8 @@ class Checker( break } + val process: Process = this.languageClient.languageServerProcess + if (!process.isAlive) throw LanguageServerExitedException(process.exitValue()) Thread.sleep(WAIT_FOR_DIAGNOSTIC_MILLISECONDS) } diff --git a/src/main/kotlin/org/bsplines/lspcli/client/LanguageServerExitedException.kt b/src/main/kotlin/org/bsplines/lspcli/client/LanguageServerExitedException.kt new file mode 100644 index 0000000..c54bacf --- /dev/null +++ b/src/main/kotlin/org/bsplines/lspcli/client/LanguageServerExitedException.kt @@ -0,0 +1,16 @@ +/* Copyright (C) 2021-2025 + * Julian Valentin, Daniel Spitzer, lsp-cli-plus Development Community + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +package org.bsplines.lspcli.client + +import org.bsplines.lspcli.tools.I18n + +/** Thrown instead of waiting for a language server whose process has ended. */ +class LanguageServerExitedException( + val exitCode: Int, +) : RuntimeException(I18n.format("serverExitedWithExitCode", exitCode.toString())) diff --git a/src/main/kotlin/org/bsplines/lspcli/client/LanguageServerProcessEndpoint.kt b/src/main/kotlin/org/bsplines/lspcli/client/LanguageServerProcessEndpoint.kt new file mode 100644 index 0000000..3d7e0b0 --- /dev/null +++ b/src/main/kotlin/org/bsplines/lspcli/client/LanguageServerProcessEndpoint.kt @@ -0,0 +1,42 @@ +/* Copyright (C) 2021-2025 + * Julian Valentin, Daniel Spitzer, lsp-cli-plus Development Community + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +package org.bsplines.lspcli.client + +import org.eclipse.lsp4j.jsonrpc.Endpoint +import java.util.concurrent.CompletableFuture + +/** + * Endpoint that sends requests and notifications to a language server through [remoteEndpoint], + * and fails a request with [LanguageServerExitedException] if the server's [process] ends before + * the request is answered. LSP4J leaves such a request pending, so that waiting for its result + * would never end. + */ +class LanguageServerProcessEndpoint( + private val remoteEndpoint: Endpoint, + process: Process, +) : Endpoint { + private val processExit: CompletableFuture = + process.onExit().thenApply { throw LanguageServerExitedException(it.exitValue()) } + + override fun request( + method: String, + parameter: Any?, + ): CompletableFuture<*> { + @Suppress("UNCHECKED_CAST") + val result = this.remoteEndpoint.request(method, parameter) as CompletableFuture + return result.applyToEither(this.processExit) { it } + } + + override fun notify( + method: String, + parameter: Any?, + ) { + this.remoteEndpoint.notify(method, parameter) + } +} diff --git a/src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt b/src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt index 205de2e..56dc670 100644 --- a/src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt +++ b/src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt @@ -24,6 +24,7 @@ import org.eclipse.lsp4j.MessageParams import org.eclipse.lsp4j.PublishDiagnosticsParams import org.eclipse.lsp4j.ShowMessageRequestParams import org.eclipse.lsp4j.jsonrpc.Launcher +import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints import org.eclipse.lsp4j.launch.LSPLauncher import org.eclipse.lsp4j.services.LanguageClient import org.eclipse.lsp4j.services.LanguageServer @@ -136,7 +137,12 @@ class LspCliLanguageClient( launcherBuilder.setExecutorService(executorService) val launcher: Launcher = launcherBuilder.create() - val server: LanguageServer = launcher.remoteProxy + // Fail requests once the server's process ends instead of waiting for them forever. + val server: LanguageServer = + ServiceEndpoints.toServiceObject( + LanguageServerProcessEndpoint(launcher.remoteEndpoint, this.languageServerProcess), + LspCliLanguageServer::class.java, + ) launcher.startListening() executorService.shutdown() diff --git a/src/main/resources/LspCliMessagesBundle.properties b/src/main/resources/LspCliMessagesBundle.properties index af2143c..3d028d1 100644 --- a/src/main/resources/LspCliMessagesBundle.properties +++ b/src/main/resources/LspCliMessagesBundle.properties @@ -11,6 +11,7 @@ couldNotWriteFile = Could not write file '{0}' followingExceptionOccurred = The following exception occurred: initializingLanguageServer = Initializing language server... requiredArgumentNotSpecified = Required argument '{0}' not specified +serverExitedWithExitCode = The language server exited with exit code {0} settingLocale = Setting locale to '{0}' startingLanguageServer = Starting language server with command line '{0}' in directory '{1}'... waitingForDiagnosticsForFile = Waiting for diagnostics for file '{0}'... diff --git a/src/test/kotlin/org/bsplines/lspcli/client/LanguageServerExitTest.kt b/src/test/kotlin/org/bsplines/lspcli/client/LanguageServerExitTest.kt new file mode 100644 index 0000000..b2a2ec6 --- /dev/null +++ b/src/test/kotlin/org/bsplines/lspcli/client/LanguageServerExitTest.kt @@ -0,0 +1,92 @@ +/* Copyright (C) 2021-2025 + * Julian Valentin, Daniel Spitzer, lsp-cli-plus Development Community + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +package org.bsplines.lspcli.client + +import org.bsplines.lspcli.LspCliLauncher +import org.bsplines.lspcli.testtools.ExitingLanguageServer +import org.bsplines.lspcli.testtools.ExitingLanguageServer.ExitPoint +import org.bsplines.lspcli.testtools.TestTools +import org.junit.jupiter.api.assertTimeoutPreemptively +import java.nio.file.Path +import java.time.Duration +import java.util.concurrent.ExecutionException +import kotlin.io.path.Path +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs + +/** + * The client stops waiting for a language server whose process ends, wherever it waits for the + * server. Before, each of these waits never ended. + */ +class LanguageServerExitTest { + @Test + fun `initialize fails when the server exits on start`() { + val exception: ExecutionException = + assertTimeoutPreemptively(Duration.ofSeconds(TIMEOUT_SECONDS)) { + assertFailsWith { + LspCliLanguageClient(ExitingLanguageServer.getCommandLine(ExitPoint.Start)) + } + } + assertExitedWithExitCode(exception.cause) + } + + @Test + fun `check fails when the server exits before publishing diagnostics`() { + val exception: Throwable = checkUntilServerExits(ExitPoint.DidOpen) + assertExitedWithExitCode(exception) + } + + @Test + fun `check fails when the server exits before answering a code action request`() { + val exception: Throwable = checkUntilServerExits(ExitPoint.CodeAction) + assertIs(exception) + assertExitedWithExitCode(exception.cause) + } + + @Test + fun `launcher returns an error when the server exits`() { + val serverCommandLine: String = + ExitingLanguageServer.getCommandLine(ExitPoint.DidOpen).joinToString(" ") { + it.replace(" ", "\\ ") + } + val returnCode: Int = + assertTimeoutPreemptively(Duration.ofSeconds(TIMEOUT_SECONDS)) { + LspCliLauncher.run(arrayOf("--server-command-line", serverCommandLine, createTestFile())) + } + assertEquals(1, returnCode) + } + + companion object { + private const val TIMEOUT_SECONDS = 30L + + private fun createTestFile(): String = TestTools.createTextFile("This is a test.", "exit.txt") + + private fun checkUntilServerExits(exitPoint: ExitPoint): Throwable { + val path: Path = Path(createTestFile()) + var client: LspCliLanguageClient? = null + + try { + return assertTimeoutPreemptively(Duration.ofSeconds(TIMEOUT_SECONDS)) { + val curClient = LspCliLanguageClient(ExitingLanguageServer.getCommandLine(exitPoint)) + client = curClient + assertFailsWith { Checker(curClient).check(path) } + } + } finally { + client?.languageServerProcess?.destroyForcibly() + } + } + + private fun assertExitedWithExitCode(exception: Throwable?) { + assertIs(exception) + assertEquals(ExitingLanguageServer.EXIT_CODE, exception.exitCode) + } + } +} diff --git a/src/test/kotlin/org/bsplines/lspcli/testtools/ExitingLanguageServer.kt b/src/test/kotlin/org/bsplines/lspcli/testtools/ExitingLanguageServer.kt new file mode 100644 index 0000000..92cc4d4 --- /dev/null +++ b/src/test/kotlin/org/bsplines/lspcli/testtools/ExitingLanguageServer.kt @@ -0,0 +1,139 @@ +/* Copyright (C) 2021-2025 + * Julian Valentin, Daniel Spitzer, lsp-cli-plus Development Community + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +package org.bsplines.lspcli.testtools + +import org.eclipse.lsp4j.CodeAction +import org.eclipse.lsp4j.CodeActionParams +import org.eclipse.lsp4j.Command +import org.eclipse.lsp4j.Diagnostic +import org.eclipse.lsp4j.DidChangeConfigurationParams +import org.eclipse.lsp4j.DidChangeTextDocumentParams +import org.eclipse.lsp4j.DidChangeWatchedFilesParams +import org.eclipse.lsp4j.DidCloseTextDocumentParams +import org.eclipse.lsp4j.DidOpenTextDocumentParams +import org.eclipse.lsp4j.DidSaveTextDocumentParams +import org.eclipse.lsp4j.InitializeParams +import org.eclipse.lsp4j.InitializeResult +import org.eclipse.lsp4j.Position +import org.eclipse.lsp4j.PublishDiagnosticsParams +import org.eclipse.lsp4j.Range +import org.eclipse.lsp4j.ServerCapabilities +import org.eclipse.lsp4j.jsonrpc.messages.Either +import org.eclipse.lsp4j.launch.LSPLauncher +import org.eclipse.lsp4j.services.LanguageClient +import org.eclipse.lsp4j.services.LanguageClientAware +import org.eclipse.lsp4j.services.LanguageServer +import org.eclipse.lsp4j.services.TextDocumentService +import org.eclipse.lsp4j.services.WorkspaceService +import java.util.concurrent.CompletableFuture +import kotlin.system.exitProcess + +/** + * Language server for tests, run in a process of its own, that exits with [EXIT_CODE] at + * [exitPoint], as a server that crashes does. Up to then, it answers requests and publishes one + * diagnostic for each document that is opened. + */ +@Suppress("TooManyFunctions") +class ExitingLanguageServer( + private val exitPoint: ExitPoint, +) : LanguageServer, + LanguageClientAware, + TextDocumentService, + WorkspaceService { + enum class ExitPoint { + /** On start, before the server reads the `initialize` request */ + Start, + + /** When a document is opened, before the server publishes the document's diagnostics */ + DidOpen, + + /** When code actions are requested, after the server has published the diagnostics */ + CodeAction, + } + + private var client: LanguageClient? = null + + override fun connect(client: LanguageClient?) { + this.client = client + } + + override fun initialize(params: InitializeParams?): CompletableFuture = + CompletableFuture.completedFuture(InitializeResult(ServerCapabilities())) + + override fun shutdown(): CompletableFuture = CompletableFuture.completedFuture(null) + + override fun exit() { + exitProcess(0) + } + + override fun getTextDocumentService(): TextDocumentService = this + + override fun getWorkspaceService(): WorkspaceService = this + + override fun didOpen(params: DidOpenTextDocumentParams?) { + if (this.exitPoint == ExitPoint.DidOpen) exitProcess(EXIT_CODE) + val uri: String = params?.textDocument?.uri ?: return + val diagnostic = Diagnostic(Range(Position(0, 0), Position(0, 1)), "Test diagnostic") + this.client?.publishDiagnostics(PublishDiagnosticsParams(uri, listOf(diagnostic))) + } + + override fun codeAction( + params: CodeActionParams?, + ): CompletableFuture>> { + if (this.exitPoint == ExitPoint.CodeAction) exitProcess(EXIT_CODE) + return CompletableFuture.completedFuture(emptyList()) + } + + override fun didChange(params: DidChangeTextDocumentParams?) { + } + + override fun didClose(params: DidCloseTextDocumentParams?) { + } + + override fun didSave(params: DidSaveTextDocumentParams?) { + } + + override fun didChangeConfiguration(params: DidChangeConfigurationParams?) { + } + + override fun didChangeWatchedFiles(params: DidChangeWatchedFilesParams?) { + } + + companion object { + const val EXIT_CODE = 42 + + @JvmStatic + fun main(arguments: Array) { + val exitPoint: ExitPoint = ExitPoint.valueOf(arguments[0]) + if (exitPoint == ExitPoint.Start) exitProcess(EXIT_CODE) + + val server = ExitingLanguageServer(exitPoint) + val launcher = LSPLauncher.createServerLauncher(server, System.`in`, System.out) + server.connect(launcher.remoteProxy) + launcher.startListening().get() + } + + /** + * Command line that starts this server with the Java runtime and the class path of the + * tests. + */ + fun getCommandLine(exitPoint: ExitPoint): List = + listOf( + ProcessHandle + .current() + .info() + .command() + .orElseThrow(), + "-classpath", + System.getProperty("java.class.path"), + ExitingLanguageServer::class.java.name, + exitPoint.name, + ) + } +}