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
55 changes: 54 additions & 1 deletion scijava-lsp/src/main/java/org/scijava/lsp/ScriptSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -112,6 +113,7 @@ public final class ScriptSession implements AutoCloseable {
private volatile Supplier<File> file = () -> null;
private final Logger log;
private volatile Consumer<List<Diagnostic>> diagnosticsListener;
private volatile ServerListener serverListener;

/** The server, once all it was told or asked so far is sent. */
private CompletableFuture<Optional<LanguageServer>> server =
Expand Down Expand Up @@ -196,6 +198,14 @@ public void setDiagnosticsListener(
diagnosticsListener = listener;
}

/**
* Sets the listener for LSP server status updates. This lets clients tell
* a server that failed to start apart from one with nothing to complete.
*/
public void setServerListener(final ServerListener listener) {
serverListener = listener;
}

/**
* Tells the server the script's text: opening it, the first time (or under
* a new name, or on a new server); otherwise, if it changed, sending it as
Expand Down Expand Up @@ -464,6 +474,7 @@ private boolean follow() {
catch (final RuntimeException | LinkageError exc) {
final Logger l = log;
if (l != null) l.warn("Could not start a language server", exc);
report(listener -> listener.failed(exc));
return Optional.empty();
}
}, TALK);
Expand Down Expand Up @@ -535,18 +546,41 @@ private LanguageServer start(final Environment env) {
if (s instanceof LanguageClientAware) {
((LanguageClientAware) s).connect(new Client(s));
}
Throwable failure = null;
try {
final CompletableFuture<InitializeResult> init = s.initialize(
new InitializeParams());
if (init != null) init.get(INITIALIZE_TIMEOUT, TimeUnit.MILLISECONDS);
}
catch (final ExecutionException exc) {
failure = exc.getCause() == null ? exc : exc.getCause();
}
catch (final Exception exc) {
// NB: Not initialized (in time): asked anyway, answering what it can.
failure = exc;
}
s.initialized(new InitializedParams());
// NB: The server is used even if it failed to initialize in time.
final Throwable cause = failure;
report(listener -> {
if (cause == null) listener.started();
else listener.failed(cause);
});
return s;
}

/** Reports an event to the LSP server listener, if any. */
private void report(final Consumer<ServerListener> message) {
final ServerListener listener = serverListener;
if (listener == null) return;
try {
message.accept(listener);
}
catch (final RuntimeException exc) {
final Logger l = log;
if (l != null) l.debug("Server listener failed", exc);
}
}

/** Shuts a server down. */
private void stop(final LanguageServer s) {
try {
Expand Down Expand Up @@ -689,6 +723,25 @@ private void heard(final PublishDiagnosticsParams p) {

// -- Helper classes --

/**
* The listener interface for LSP server status updates. Its methods are
* called on the session's thread.
*/
public interface ServerListener {

/** Invoked when a server has started and initialized. */
void started();

/**
* Invoked when a server fails to start, or fails to initialize in time.
* After a failed start, requests get empty answers until another server
* starts. After a failed initialization, the server is still used.
*
* @param cause The exception that caused the failure.
*/
void failed(Throwable cause);
}

/** Receives a server's messages. */
private final class Client implements LanguageClient {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,8 @@ public static class HighPlugin implements LanguageServerPlugin {

/** The server to create next, if not a new one (e.g. a special one). */
static volatile FakeServer next;
/** Exception to throw when creating a server, to simulate a failed start. */
static volatile RuntimeException failure;

@Override
public boolean supports(final String language) {
Expand All @@ -225,6 +227,8 @@ public boolean supports(final String language) {
public LanguageServer create(final String language,
final Environment environment)
{
final RuntimeException f = failure;
if (f != null) throw f;
final FakeServer special = next;
return register(special != null ? special : new FakeServer("high",
language, environment));
Expand Down
79 changes: 79 additions & 0 deletions scijava-lsp/src/test/java/org/scijava/lsp/ScriptSessionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,85 @@ private void awaitHeard(final String... expected) {
.equals(Arrays.asList(expected)));
}

/** Tests that server startup is reported correctly to listeners. */
@Test
public void testServerStarted() throws Exception {
final List<String> fared = new CopyOnWriteArrayList<>();
try (ScriptSession session = new ScriptSession(service, fake)) {
session.setServerListener(listener(fared));
session.update("x");
waitFor(() -> !fared.isEmpty());
assertEquals(Collections.singletonList("started"), fared);
}
}

/** Tests that a failed server start is reported to listeners. */
@Test
public void testServerFailed() throws Exception {
final List<String> fared = new CopyOnWriteArrayList<>();
HighPlugin.failure = new IllegalStateException("broken plugin");
try (ScriptSession session = new ScriptSession(service, fake)) {
session.setServerListener(listener(fared));
session.update("x");
// NB: Without a server, completion gives an empty list.
assertTrue(session.completion("x", 1).get(10, TimeUnit.SECONDS)
.getItems().isEmpty());
assertEquals(Collections.singletonList("failed broken plugin"), fared);
}
finally {
HighPlugin.failure = null;
}
}

/**
* Tests that a failed server initialization is reported to listeners, and
* that the server is still used.
*/
@Test
public void testServerNotInitialized() {
final List<String> fared = new CopyOnWriteArrayList<>();
final FakeServer refusing = new FakeServer("refusing", new Environment()) {

@Override
public CompletableFuture<InitializeResult> initialize(
final InitializeParams params)
{
final CompletableFuture<InitializeResult> no =
new CompletableFuture<>();
no.completeExceptionally(new IllegalStateException("no init"));
return no;
}
};
HighPlugin.next = refusing;
try (ScriptSession session = new ScriptSession(service, fake)) {
session.setServerListener(listener(fared));
session.update("x");
waitFor(() -> refusing.events.contains("open 1 x"));
assertEquals(Collections.singletonList("failed no init"), fared);
}
finally {
HighPlugin.next = null;
}
}

/** Creates a listener which records the events it receives. */
private static ScriptSession.ServerListener listener(
final List<String> fared)
{
return new ScriptSession.ServerListener() {

@Override
public void started() {
fared.add("started");
}

@Override
public void failed(final Throwable cause) {
fared.add("failed " + cause.getMessage());
}
};
}

private static List<String> messages(final List<Diagnostic> diagnostics) {
return diagnostics.stream().map(d -> d.getMessage().getLeft()).collect(
Collectors.toList());
Expand Down
Loading