Skip to content
Merged
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
3 changes: 3 additions & 0 deletions changelog.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
<action type="fix" issue="ltex-plus/ltex-ls-plus#231" due-to="Parker Wahle (@regulad)">
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`.
</action>
<action type="fix" issue="ltex-plus/lsp-cli-plus#69" due-to="Parker Wahle (@regulad)">
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.
</action>
</release>
<release version="3.0.1" date="2026-11-23">
<action type="fix" issue="ltex-plus/ltex-ls-plus#199" due-to="Andrea Alberti (@alberti42)">
Expand Down
2 changes: 2 additions & 0 deletions src/main/kotlin/org/bsplines/lspcli/client/Checker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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()))
Original file line number Diff line number Diff line change
@@ -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<Any?> =
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<Any?>
return result.applyToEither(this.processExit) { it }
}

override fun notify(
method: String,
parameter: Any?,
) {
this.remoteEndpoint.notify(method, parameter)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -136,7 +137,12 @@ class LspCliLanguageClient(
launcherBuilder.setExecutorService(executorService)

val launcher: Launcher<LspCliLanguageServer> = 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()

Expand Down
1 change: 1 addition & 0 deletions src/main/resources/LspCliMessagesBundle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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}'...
Original file line number Diff line number Diff line change
@@ -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<ExecutionException> {
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<ExecutionException>(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<Exception> { Checker(curClient).check(path) }
}
} finally {
client?.languageServerProcess?.destroyForcibly()
}
}

private fun assertExitedWithExitCode(exception: Throwable?) {
assertIs<LanguageServerExitedException>(exception)
assertEquals(ExitingLanguageServer.EXIT_CODE, exception.exitCode)
}
}
}
139 changes: 139 additions & 0 deletions src/test/kotlin/org/bsplines/lspcli/testtools/ExitingLanguageServer.kt
Original file line number Diff line number Diff line change
@@ -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<InitializeResult> =
CompletableFuture.completedFuture(InitializeResult(ServerCapabilities()))

override fun shutdown(): CompletableFuture<Any> = 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<List<Either<Command, CodeAction>>> {
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<String>) {
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<String> =
listOf(
ProcessHandle
.current()
.info()
.command()
.orElseThrow(),
"-classpath",
System.getProperty("java.class.path"),
ExitingLanguageServer::class.java.name,
exitPoint.name,
)
}
}
Loading