Skip to content

Commit 7e8b2c1

Browse files
gselzerclaude
andcommitted
Tell language servers when script environments change
A script's environment can become available without the script changing: when a script run builds it, or when packages it declares are installed for completion. ResidentWorkerService now notifies listeners of finished builds, and DependencyOverlays of ready overlays; the jedi plugin passes both on to LanguageServerService.environmentsChanged(), so open scripts move to the servers of where they run now. Tests ask through script sessions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f2de3ca commit 7e8b2c1

6 files changed

Lines changed: 110 additions & 70 deletions

File tree

‎src/main/java/org/scijava/plugins/scripting/appose/python/ApposePythonEnvironments.java‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
import org.apposed.appose.util.Environments;
5050
import org.scijava.plugins.scripting.appose.python._internal.InlineMetadata;
5151
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorker;
52+
import org.scijava.plugins.scripting.appose.python._internal.BuildListener;
5253
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorkerService;
5354
import org.scijava.plugins.scripting.appose.python.completion.DependencyOverlays;
5455
import org.scijava.plugins.scripting.appose.python.completion.JediLanguageServerSpec;
@@ -98,8 +99,19 @@ protected boolean removeEldestEntry(
9899

99100
private DependencyOverlays overlays;
100101

102+
/** Told when where scripts run may have changed. */
103+
private volatile Runnable onChange = () -> {};
104+
101105
private ApposePythonEnvironments(final ResidentWorkerService workers) {
102106
this.workers = workers;
107+
// NB: A script run builds its environment: its Python is known then.
108+
if (workers != null) workers.addBuildListener(new BuildListener() {
109+
110+
@Override
111+
public void buildFinished(final String envName, final Throwable error) {
112+
if (error == null) changed();
113+
}
114+
});
103115
}
104116

105117
/** Gets those of a context (by its resident worker service). */
@@ -127,9 +139,22 @@ org.scijava.code.lsp.Environment environment(final String text,
127139
: Collections.singletonList(overlay), null, null);
128140
}
129141

142+
/**
143+
* Sets what to do when where scripts run may have changed without them
144+
* changing: when an environment is built, or an overlay is ready.
145+
*/
146+
void onChange(final Runnable onChange) {
147+
this.onChange = onChange == null ? () -> {} : onChange;
148+
}
149+
150+
private void changed() {
151+
onChange.run();
152+
}
153+
130154
/** Sets the dependency overlays, e.g. to use fake ones in tests. */
131155
synchronized void setOverlays(final DependencyOverlays overlays) {
132156
this.overlays = overlays;
157+
if (overlays != null) overlays.setOnReady(this::changed);
133158
}
134159

135160
/** The file path of a {@code file:} URI, or null. */
@@ -181,6 +206,7 @@ private synchronized DependencyOverlays overlays() {
181206
dir) -> installOverlay(workers, python, dependencies, dir), new File(
182207
Environments.apposeEnvsDir(), TOOLING_ENV + "-overlays"),
183208
OVERLAY_SETTLE, System::currentTimeMillis);
209+
overlays.setOnReady(this::changed);
184210
return overlays;
185211
}
186212

‎src/main/java/org/scijava/plugins/scripting/appose/python/JediServerPlugin.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,13 @@ public boolean supports(final ScriptLanguage language) {
8585

8686
@Override
8787
public Environment environment(final TextDocumentItem document) {
88+
final ApposePythonEnvironments environments = ApposePythonEnvironments.of(
89+
workers);
90+
// NB: Scripts move as their environments are built, or overlays ready.
91+
environments.onChange(servers::environmentsChanged);
8892
// NB: On opening the script, its dependencies are settled.
89-
return ApposePythonEnvironments.of(workers).environment(document.getText(),
90-
document.getUri(), document.getVersion() <= 1);
93+
return environments.environment(document.getText(), document.getUri(),
94+
document.getVersion() <= 1);
9195
}
9296

9397
@Override

‎src/main/java/org/scijava/plugins/scripting/appose/python/_internal/ResidentWorkerService.java‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import java.util.HashMap;
3434
import java.util.List;
3535
import java.util.Map;
36+
import java.util.concurrent.CopyOnWriteArrayList;
3637
import java.util.function.Function;
3738
import java.util.function.Supplier;
3839

@@ -75,6 +76,10 @@ public class ResidentWorkerService extends AbstractService implements
7576
/** Environments by name and activation, each with its configuration and worker. */
7677
private final Map<String, Entry> entries = new HashMap<>();
7778

79+
/** Told about every environment's builds. */
80+
private final List<BuildListener> buildListeners =
81+
new CopyOnWriteArrayList<>();
82+
7883
/**
7984
* Gets the resident worker for the named environment, creating the
8085
* environment and worker if needed.
@@ -107,13 +112,30 @@ public ResidentWorker worker(final String name, final String activate,
107112
activate);
108113
env.addBuildListener(SciJavaTasks.buildListener(taskService,
109114
statusService, log));
115+
env.addBuildListener(new BuildListener() {
116+
117+
@Override
118+
public void buildFinished(final String envName, final Throwable error) {
119+
for (final BuildListener l : buildListeners) {
120+
l.buildFinished(envName, error);
121+
}
122+
}
123+
});
110124
worker = new ResidentWorker(env, launcher);
111125
entries.put(key, new Entry(config, worker));
112126
}
113127
if (stale != null) stale.release();
114128
return worker;
115129
}
116130

131+
/**
132+
* Adds a listener told when any environment's build ends (e.g. so that
133+
* code completion can use it).
134+
*/
135+
public void addBuildListener(final BuildListener listener) {
136+
buildListeners.add(listener);
137+
}
138+
117139
/**
118140
* Gets the resident worker for the named environment, if there is one with
119141
* the given configuration. Unlike {@link #worker}, this never creates,

‎src/main/java/org/scijava/plugins/scripting/appose/python/completion/DependencyOverlays.java‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,9 @@ public interface Installer {
106106
/** The dependencies last seen for each environment, and since when. */
107107
private final Map<String, Seen> seen = new HashMap<>();
108108

109+
/** Told when an overlay is ready. */
110+
private volatile Runnable onReady = () -> {};
111+
109112
/**
110113
* @param installer Does the installing, on a background thread.
111114
* @param root Directory holding the overlays (one per environment).
@@ -122,6 +125,14 @@ public DependencyOverlays(final Installer installer, final File root,
122125
this.clock = clock;
123126
}
124127

128+
/**
129+
* Sets what to do when an overlay becomes ready (on the installing
130+
* thread), e.g. tell language servers to look again.
131+
*/
132+
public void setOnReady(final Runnable onReady) {
133+
this.onReady = onReady == null ? () -> {} : onReady;
134+
}
135+
125136
/**
126137
* Gets the overlay providing the packages the environment lacks, if it is
127138
* ready; starts preparing it once the dependencies have settled. Never
@@ -154,8 +165,13 @@ public String overlay(final String envName, final String python,
154165
}
155166
else if (!settled && now - last.since < settleMillis) return null;
156167
final File overlay = new File(root, envName);
157-
installs.put(key, CompletableFuture.supplyAsync(() -> installer.install(
158-
python, dependencies, overlay), executor));
168+
final CompletableFuture<String> started = CompletableFuture.supplyAsync(
169+
() -> installer.install(python, dependencies, overlay), executor);
170+
installs.put(key, started);
171+
// NB: Once done, so that asking again gets the overlay.
172+
started.thenAccept(dir -> {
173+
if (dir != null) onReady.run();
174+
});
159175
return null;
160176
}
161177
}

‎src/test/java/org/scijava/plugins/scripting/appose/python/ApposePythonCompletionIntegrationTest.java‎

Lines changed: 30 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -46,25 +46,16 @@
4646

4747
import org.eclipse.lsp4j.CompletionItem;
4848
import org.eclipse.lsp4j.CompletionList;
49-
import org.eclipse.lsp4j.CompletionParams;
5049
import org.eclipse.lsp4j.Diagnostic;
51-
import org.eclipse.lsp4j.DidChangeTextDocumentParams;
52-
import org.eclipse.lsp4j.DidOpenTextDocumentParams;
5350
import org.eclipse.lsp4j.Hover;
54-
import org.eclipse.lsp4j.HoverParams;
5551
import org.eclipse.lsp4j.SignatureHelp;
56-
import org.eclipse.lsp4j.SignatureHelpParams;
57-
import org.eclipse.lsp4j.TextDocumentContentChangeEvent;
58-
import org.eclipse.lsp4j.TextDocumentIdentifier;
59-
import org.eclipse.lsp4j.TextDocumentItem;
60-
import org.eclipse.lsp4j.VersionedTextDocumentIdentifier;
6152
import org.junit.AfterClass;
6253
import org.junit.BeforeClass;
6354
import org.junit.Test;
6455
import org.scijava.Context;
6556
import org.scijava.code.lsp.LanguageServerService;
6657
import org.scijava.code.lsp.Positions;
67-
import org.scijava.code.lsp.MergedLanguageServer;
58+
import org.scijava.code.lsp.ScriptSession;
6859
import org.scijava.code.lsp.UpdatingCompletionList;
6960
import org.scijava.module.ModuleService;
7061
import org.scijava.script.ScriptInfo;
@@ -95,21 +86,22 @@ public class ApposePythonCompletionIntegrationTest {
9586

9687
private static Context context;
9788
private static ScriptLanguage language;
98-
private static MergedLanguageServer server;
89+
private static LanguageServerService servers;
9990
private static File scriptDir;
10091

10192
@BeforeClass
10293
public static void setUp() throws URISyntaxException {
10394
context = new Context();
10495
language = context.service(ScriptService.class).getLanguageByName(
10596
"appose-python");
106-
server = context.service(LanguageServerService.class).server(language);
97+
servers = context.service(LanguageServerService.class);
10798
scriptDir = new File(ApposePythonCompletionIntegrationTest.class
10899
.getResource("/appose-test/requirements.txt").toURI()).getParentFile();
109100
}
110101

111102
@AfterClass
112103
public static void tearDown() {
104+
sessions.values().forEach(ScriptSession::close);
113105
if (context != null) context.dispose();
114106
}
115107

@@ -123,8 +115,8 @@ public void testStandardLibrary() throws Exception {
123115
.equals("dumps") && c.getLabelDetails() != null).findFirst().get();
124116
assertTrue(dumps.getLabelDetails().getDetail(), dumps.getLabelDetails()
125117
.getDetail().startsWith("(Any obj, bool skipkeys"));
126-
assertTrue(dumps.getDocumentation() != null || server
127-
.resolveCompletionItem(dumps).get(1, TimeUnit.MINUTES)
118+
assertTrue(dumps.getDocumentation() != null || session(null).resolve(
119+
dumps).get(1, TimeUnit.MINUTES)
128120
.getDocumentation() != null);
129121
report("import json\njson.l", null, "loads", "o");
130122
}
@@ -153,13 +145,12 @@ public void testScriptEnvironment() throws Exception {
153145
@Test
154146
public void testSignatureHelp() throws Exception {
155147
final String code = "import json\njson.dumps(obj, ";
156-
final String uri = sync(code, null);
148+
final ScriptSession session = session(null);
157149
final long deadline = System.currentTimeMillis() + BUILD_TIMEOUT;
158150
SignatureHelp help = null;
159151
while (help == null && System.currentTimeMillis() < deadline) {
160-
help = server.signatureHelp(new SignatureHelpParams(
161-
new TextDocumentIdentifier(uri), Positions.position(code, code
162-
.length()))).get(1, TimeUnit.MINUTES);
152+
help = session.signatureHelp(code, code.length()).get(1,
153+
TimeUnit.MINUTES);
163154
}
164155
assertTrue(help.getSignatures().get(0).getLabel().contains("dumps("));
165156
assertFalse(help.getSignatures().get(0).getParameters().isEmpty());
@@ -169,13 +160,12 @@ public void testSignatureHelp() throws Exception {
169160
@Test
170161
public void testHover() throws Exception {
171162
final String code = "import json\njson.dumps(1)";
172-
final String uri = sync(code, null);
163+
final ScriptSession session = session(null);
173164
final long deadline = System.currentTimeMillis() + BUILD_TIMEOUT;
174165
Hover hover = null;
175166
while (hover == null && System.currentTimeMillis() < deadline) {
176-
hover = server.hover(new HoverParams(new TextDocumentIdentifier(uri),
177-
Positions.position(code, code.indexOf("dumps") + 2))).get(1,
178-
TimeUnit.MINUTES);
167+
hover = session.hover(code, code.indexOf("dumps") + 2).get(1,
168+
TimeUnit.MINUTES);
179169
}
180170
assertTrue(String.valueOf(hover), hover.getContents().getRight().getValue()
181171
.contains("JSON"));
@@ -190,19 +180,17 @@ public void testHover() throws Exception {
190180
public void testDiagnostics() throws Exception {
191181
// A syntax error, on the script's third line.
192182
final String code = "#@ double sigma\nx = sigma\ny = (1 +\n";
193-
final LanguageServerService servers = context.service(
194-
LanguageServerService.class);
195183
final long deadline = System.currentTimeMillis() + BUILD_TIMEOUT;
196184
List<Diagnostic> problems = Collections.emptyList();
197185
while (problems.isEmpty() && System.currentTimeMillis() < deadline) {
198-
problems = servers.diagnose(language, "untitled:/diagnose.py", code,
186+
problems = servers.diagnose(language, code,
199187
120_000);
200188
}
201189
assertFalse(problems.isEmpty());
202190
assertTrue(problems.toString(), problems.get(0).getRange().getStart()
203191
.getLine() >= 2);
204192
// Fixed: no more problems.
205-
assertTrue(servers.diagnose(language, "untitled:/diagnose.py", code
193+
assertTrue(servers.diagnose(language, code
206194
.replace("(1 +", "(1 + 2)"), 120_000).isEmpty());
207195
}
208196

@@ -249,26 +237,18 @@ public void testNewDependency() throws Exception {
249237

250238
// -- Helper methods --
251239

252-
/** The open documents' versions, by URI. */
253-
private static final Map<String, Integer> versions = new HashMap<>();
240+
/** The scripts' sessions, by path ("" for an untitled one). */
241+
private static final Map<String, ScriptSession> sessions = new HashMap<>();
254242

255-
/** Opens a script on the server, or changes it; returns its URI. */
256-
private static String sync(final String code, final String path) {
257-
final String uri = path == null ? "untitled:/integration.py" : new File(
258-
path).toURI().toString();
259-
final Integer version = versions.get(uri);
260-
if (version == null) {
261-
versions.put(uri, 1);
262-
server.didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri,
263-
"appose-python", 1, code)));
264-
}
265-
else {
266-
versions.put(uri, version + 1);
267-
server.didChange(new DidChangeTextDocumentParams(
268-
new VersionedTextDocumentIdentifier(uri, version + 1), Collections
269-
.singletonList(new TextDocumentContentChangeEvent(code))));
270-
}
271-
return uri;
243+
/** The session about a script (null path: untitled). */
244+
private static ScriptSession session(final String path) {
245+
return sessions.computeIfAbsent(path == null ? "" : path, p -> servers
246+
.session(language).setFile(path == null ? null : new File(path)));
247+
}
248+
249+
/** Tells the servers a script's text. */
250+
private static ScriptSession sync(final String code, final String path) {
251+
return session(path).update(code);
272252
}
273253

274254
/** Completes until the expected completion appears (environments build). */
@@ -295,10 +275,8 @@ private static List<CompletionItem> completeUntil(final String code,
295275
private static List<CompletionItem> complete(final String code,
296276
final String path, final boolean settled) throws Exception
297277
{
298-
final String uri = sync(code, path);
299-
CompletionList list = server.completion(new CompletionParams(
300-
new TextDocumentIdentifier(uri), Positions.position(code, code.length())))
301-
.get(1, TimeUnit.MINUTES).getRight();
278+
CompletionList list = session(path).completion(code, code.length())
279+
.get(1, TimeUnit.MINUTES);
302280
if (settled && list instanceof UpdatingCompletionList) {
303281
final CompletionList better = ((UpdatingCompletionList) list).update()
304282
.get(1, TimeUnit.MINUTES);
@@ -321,11 +299,10 @@ private static void report(final String code, final String path,
321299
final int n = complete(code + more, path, true).size();
322300
final long cached = System.nanoTime() - t0;
323301
final String other = code.substring(0, code.lastIndexOf('.') + 1) + "s";
324-
final String uri = sync(other, path);
302+
final ScriptSession session = session(path);
325303
t0 = System.nanoTime();
326-
final CompletionList first = server.completion(new CompletionParams(
327-
new TextDocumentIdentifier(uri), Positions.position(other, other
328-
.length()))).get(1, TimeUnit.MINUTES).getRight();
304+
final CompletionList first = session.completion(other, other.length())
305+
.get(1, TimeUnit.MINUTES);
329306
final long wait = System.nanoTime() - t0;
330307
final CompletionList update = first instanceof UpdatingCompletionList
331308
? ((UpdatingCompletionList) first).update().get(1, TimeUnit.MINUTES)

‎src/test/java/org/scijava/plugins/scripting/appose/python/ApposePythonServersTest.java‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,6 @@
4343
import net.imglib2.img.Img;
4444

4545
import org.eclipse.lsp4j.CompletionItem;
46-
import org.eclipse.lsp4j.CompletionParams;
47-
import org.eclipse.lsp4j.DidOpenTextDocumentParams;
48-
import org.eclipse.lsp4j.TextDocumentIdentifier;
4946
import org.eclipse.lsp4j.TextDocumentItem;
5047
import org.junit.After;
5148
import org.junit.Before;
@@ -54,7 +51,7 @@
5451
import org.scijava.code.lsp.LanguageServerService;
5552
import org.scijava.code.lsp.Environment;
5653
import org.scijava.code.lsp.LanguageServerPlugin;
57-
import org.scijava.code.lsp.Positions;
54+
import org.scijava.code.lsp.ScriptSession;
5855
import org.scijava.plugin.PluginService;
5956
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorkerService;
6057
import org.scijava.plugins.scripting.appose.python.completion.ApposePythonDialect;
@@ -307,15 +304,13 @@ public void testServerOptions() {
307304

308305
/** Completes with the syntax-only server. */
309306
private List<String> complete(final String code) {
310-
final PythonSyntaxLanguageServer server = new PythonSyntaxLanguageServer(
311-
context.service(LanguageServerService.class));
312-
server.didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(
313-
"untitled:/a.py", "appose-python", 1, code)));
314-
try {
315-
return server.completion(new CompletionParams(new TextDocumentIdentifier(
316-
"untitled:/a.py"), Positions.position(code, code.length()))).get(10,
317-
TimeUnit.SECONDS).getRight().getItems().stream().map(
318-
CompletionItem::getLabel).collect(Collectors.toList());
307+
try (ScriptSession session = ScriptSession.owning(
308+
new PythonSyntaxLanguageServer(context.service(
309+
LanguageServerService.class)), language))
310+
{
311+
return session.completion(code, code.length()).get(10,
312+
TimeUnit.SECONDS).getItems().stream().map(CompletionItem::getLabel)
313+
.collect(Collectors.toList());
319314
}
320315
catch (final Exception exc) {
321316
throw new RuntimeException(exc);

0 commit comments

Comments
 (0)