@hydranium/data-server 1.0.0-next.28 → 1.0.0-next.281
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -73
- package/lib/data-server.d.ts +428 -291
- package/lib/data-server.d.ts.map +1 -1
- package/lib/data-server.js +716 -502
- package/lib/data-server.js.map +1 -1
- package/lib/messages/index.d.ts +1 -1
- package/lib/messages/index.d.ts.map +1 -1
- package/lib/messages/index.js +1 -1
- package/lib/messages/index.js.map +1 -1
- package/lib/node/node-diagnostics-provider.d.ts.map +1 -1
- package/lib/node/node-diagnostics-provider.js +2 -1
- package/lib/node/node-diagnostics-provider.js.map +1 -1
- package/lib/testing/data-server-harness.d.ts +31 -14
- package/lib/testing/data-server-harness.d.ts.map +1 -1
- package/lib/testing/data-server-harness.js +8 -3
- package/lib/testing/data-server-harness.js.map +1 -1
- package/lib/testing/index.d.ts +1 -0
- package/lib/testing/index.d.ts.map +1 -1
- package/lib/testing/index.js.map +1 -1
- package/package.json +32 -44
- package/src/data-server.ts +865 -542
- package/src/messages/index.ts +8 -1
- package/src/node/node-diagnostics-provider.ts +2 -8
- package/src/testing/data-server-harness.ts +55 -26
- package/src/testing/index.ts +5 -2
package/lib/data-server.js
CHANGED
|
@@ -6,26 +6,43 @@
|
|
|
6
6
|
*
|
|
7
7
|
* SPDX-License-Identifier: MIT
|
|
8
8
|
********************************************************************************/
|
|
9
|
-
import { createRpcProxy, defineMessage, DisposableCollection, isDocumentSource, isElementSource, isSyntheticSource, messageError, ReferenceSource } from '@hydranium/protocol';
|
|
9
|
+
import { createRpcProxy, defineMessage, describeErrorWithStack, DisposableCollection, HYDRANIUM_ERROR_CODES, isDocumentSource, isElementSource, isResponseError, isSyntheticSource, messageData, messageError, ReferenceSource, SessionClosedError, TIMED_OUT, TransferDocument, UNKNOWN_CLIENT_ID, textHash } from '@hydranium/protocol';
|
|
10
10
|
import { DATA_SERVER_DIAGNOSTICS_METHODS, DATA_SERVER_PROTOCOL_METHODS, DATA_SERVER_WIRE_PREFIX } from '@hydranium/protocol/data';
|
|
11
|
-
import {
|
|
11
|
+
import { DOCUMENT_RELEASE_CLIENT_ID } from '@hydranium/core';
|
|
12
12
|
import { defaultDataServerDiagnostics } from './default-diagnostics.js';
|
|
13
13
|
/**
|
|
14
14
|
* Raised when a profiling command arrives with no capture running.
|
|
15
15
|
*
|
|
16
|
-
* A `ResponseError` rather than a plain `Error` so the identity survives the
|
|
17
|
-
*
|
|
18
|
-
* internal error
|
|
19
|
-
*
|
|
16
|
+
* A `ResponseError` rather than a plain `Error` so the identity survives to the
|
|
17
|
+
* response boundary, which is where the message is rendered. An unwrapped throw
|
|
18
|
+
* reaches the client as a generic internal error instead: no code for a caller
|
|
19
|
+
* to switch on, and nothing for the boundary to render from.
|
|
20
20
|
*/
|
|
21
21
|
export const NO_ACTIVE_PROFILE = defineMessage('hydranium/data-server/no-active-profile', 'No profiling capture is active; call startProfiling first.');
|
|
22
22
|
/**
|
|
23
23
|
* The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
|
|
24
24
|
* survives reconstruction and is what a caller switches on.
|
|
25
25
|
*/
|
|
26
|
-
export const NO_ACTIVE_PROFILE_CODE =
|
|
26
|
+
export const NO_ACTIVE_PROFILE_CODE = HYDRANIUM_ERROR_CODES.noActiveProfile;
|
|
27
27
|
export const noActiveProfileError = () => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
|
|
28
|
+
/**
|
|
29
|
+
* Raised when a reference question's wait for the build exceeds
|
|
30
|
+
* {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
31
|
+
*
|
|
32
|
+
* A `ResponseError` because a class name does not cross RPC: without the code a
|
|
33
|
+
* wire client cannot tell a wedged build from a reference that resolves to
|
|
34
|
+
* nothing, which is the distinction the wait exists to keep.
|
|
35
|
+
*/
|
|
36
|
+
export const REFERENCE_SETTLE_TIMEOUT = defineMessage('hydranium/data-server/reference-settle-timeout', 'The model is still being processed; try again in a moment.');
|
|
37
|
+
/** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
|
|
38
|
+
export const REFERENCE_SETTLE_TIMEOUT_CODE = HYDRANIUM_ERROR_CODES.referenceSettleTimeout;
|
|
39
|
+
/** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */
|
|
40
|
+
export const referenceSettleTimeoutError = (elapsedMs) => new ResponseError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT.format(), {
|
|
41
|
+
elapsedMs,
|
|
42
|
+
...messageData(REFERENCE_SETTLE_TIMEOUT)
|
|
43
|
+
});
|
|
28
44
|
import { DocumentState, UriUtils } from '@hydranium/langium';
|
|
45
|
+
import { ResponseError } from 'vscode-jsonrpc';
|
|
29
46
|
/**
|
|
30
47
|
* Domain separator between text and diagnostics inputs of
|
|
31
48
|
* {@link DataServer.computeDocumentFingerprint}'s hash. A single NUL byte is
|
|
@@ -34,47 +51,30 @@ import { DocumentState, UriUtils } from '@hydranium/langium';
|
|
|
34
51
|
*/
|
|
35
52
|
const FINGERPRINT_SEPARATOR = '\0';
|
|
36
53
|
/**
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* **A cryptographic hash via `node:crypto` is the wrong trade**: the
|
|
41
|
-
* fingerprint only needs a stable signal that `(text, diagnostics)` changed
|
|
42
|
-
* between emissions, and a `node:*` import would cost
|
|
43
|
-
* `@hydranium/data-server` its browser-portability. Parts are fed
|
|
44
|
-
* incrementally, char by char, so multi-MB document text is never
|
|
45
|
-
* concatenated into one string.
|
|
54
|
+
* `LSPErrorCodes.ServerCancelled`, with which Langium's document wait rejects
|
|
55
|
+
* for a URI that has no document; `vscode-languageserver-protocol` is not a
|
|
56
|
+
* dependency of this package.
|
|
46
57
|
*/
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
|
|
60
|
-
h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
61
|
-
const high = (h2 >>> 0).toString(16).padStart(8, '0');
|
|
62
|
-
const low = (h1 >>> 0).toString(16).padStart(8, '0');
|
|
63
|
-
return high + low;
|
|
64
|
-
}
|
|
65
|
-
/** Hash a document's raw text + diagnostics — the `'text-diagnostics'` strategy. */
|
|
66
|
-
function textDiagnosticsFingerprint(document) {
|
|
67
|
-
return fingerprintHash([document.textDocument.getText(), FINGERPRINT_SEPARATOR, JSON.stringify(document.diagnostics ?? [])]);
|
|
58
|
+
const SERVER_CANCELLED = -32802;
|
|
59
|
+
/**
|
|
60
|
+
* Hash `text`, the text the model was parsed from, + `model`'s diagnostics — the `'text-diagnostics'` strategy.
|
|
61
|
+
* The text comes from the root's ledger record or CST, as the document's own may have moved on,
|
|
62
|
+
* and a repair in place leaves the CST on the unrepaired text;
|
|
63
|
+
* a root built without a CST hashes as `'transfer-document'`.
|
|
64
|
+
* Absent diagnostics must hash apart from `[]`, as in {@link transferDocumentFingerprint}.
|
|
65
|
+
*/
|
|
66
|
+
function textDiagnosticsFingerprint(text, model) {
|
|
67
|
+
return text === undefined
|
|
68
|
+
? transferDocumentFingerprint(model)
|
|
69
|
+
: textHash([text, FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
|
|
68
70
|
}
|
|
69
|
-
/**
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
JSON.stringify(transferDocument.diagnostics)
|
|
77
|
-
]);
|
|
71
|
+
/**
|
|
72
|
+
* Hash an encoded model's root + diagnostics — the `'transfer-document'` strategy.
|
|
73
|
+
* Absent diagnostics must hash apart from `[]`: a client skipping a render on an
|
|
74
|
+
* equal hash would otherwise miss a validation that found nothing.
|
|
75
|
+
*/
|
|
76
|
+
function transferDocumentFingerprint(model) {
|
|
77
|
+
return textHash([JSON.stringify(model.root), FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
|
|
78
78
|
}
|
|
79
79
|
/**
|
|
80
80
|
* `logAfterMs` threshold passed to {@link Tracer.time} around
|
|
@@ -105,13 +105,19 @@ const FINGERPRINT_LOG_AFTER_MS = 5;
|
|
|
105
105
|
* adopters subclass ONLY when they need to decorate wire returns or
|
|
106
106
|
* notifications. The usual adoption path is DI rebinds alone.
|
|
107
107
|
*
|
|
108
|
+
* **`TTransfer` is not checked.** It declares the union of the transfer roots
|
|
109
|
+
* the workspace's languages produce. Which root a document has is known only
|
|
110
|
+
* at runtime, from its language, so a `TTransfer` missing a language compiles.
|
|
111
|
+
*
|
|
108
112
|
* Lifecycle: the constructor registers framework request handlers (plus
|
|
109
113
|
* any names supplied via {@link DataServerOptions.additionalMethods}) and
|
|
110
114
|
* builds the {@link DataClientProtocol} notification proxy on the same
|
|
111
115
|
* connection in one {@link createRpcProxy} call (binding `this` as its
|
|
112
|
-
* `localTarget`) under the configured namespace, and
|
|
113
|
-
* `
|
|
114
|
-
* dispatches
|
|
116
|
+
* `localTarget`) under the configured namespace, and follows documents
|
|
117
|
+
* through `ModelService`'s events: at the configured phase, `onModelUpdated`
|
|
118
|
+
* dispatches per-document `clientProxy.onDocumentUpdated` for watched URIs and
|
|
119
|
+
* `onModelsBuilt` a single `clientProxy.onDocumentsBuilt` naming the batch's
|
|
120
|
+
* unwatched documents.
|
|
115
121
|
*
|
|
116
122
|
* The data-server requires the full {@link ServerSharedServices}
|
|
117
123
|
* shape — `HydraniumTextDocuments` for client-attributed updates,
|
|
@@ -136,85 +142,34 @@ export class DataServer {
|
|
|
136
142
|
* extending rather than restate a value the framework may change.
|
|
137
143
|
*/
|
|
138
144
|
static DEFAULT_OPTIONS = {
|
|
139
|
-
subscriptionPhase: DocumentState.Validated
|
|
145
|
+
subscriptionPhase: DocumentState.Validated,
|
|
146
|
+
referenceSettleTimeoutMs: 60_000
|
|
140
147
|
};
|
|
141
148
|
options;
|
|
142
|
-
/**
|
|
143
|
-
|
|
149
|
+
/** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
|
|
150
|
+
uriWatchRecords = new Map();
|
|
144
151
|
/**
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
*
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
* the document open forever — resident, and with its last-close revert
|
|
151
|
-
* suppressed. The store has no notion of which connection a clientId reached
|
|
152
|
-
* it over, so the connection-scoped set has to live here; teaching it a client
|
|
153
|
-
* identity is the more robust and much larger alternative.
|
|
154
|
-
*/
|
|
155
|
-
openedDocuments = new Map();
|
|
156
|
-
/** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
|
|
157
|
-
clientProxy;
|
|
158
|
-
disposables = new DisposableCollection();
|
|
152
|
+
* Per client id, the key each URI it watched resolved to when it watched.
|
|
153
|
+
* An unwatch looks the key up here: once a file is gone, a symlink to it
|
|
154
|
+
* no longer resolves to the key the watch is under.
|
|
155
|
+
*/
|
|
156
|
+
watchKeys = new Map();
|
|
159
157
|
/**
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
* URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
|
|
165
|
-
* the LSP side, so reason fidelity stays consistent between heads.
|
|
158
|
+
* The live client sessions this connection registered, by client id. A
|
|
159
|
+
* document request carrying one of these ids acts as that session; one
|
|
160
|
+
* carrying any other id fails. A session leaves once it ends, so a
|
|
161
|
+
* connection that registers many over its life does not accumulate them.
|
|
166
162
|
*/
|
|
167
|
-
|
|
163
|
+
clientSessions = new Map();
|
|
168
164
|
/**
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
* `
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
* `HydraniumTextDocuments.refreshContent` fires `onDidChangeContent`
|
|
178
|
-
* purely to re-trigger the build pipeline — the text and diagnostics
|
|
179
|
-
* are identical to the prior emit.
|
|
180
|
-
* 2. **Cascade rebuilds with no diagnostic delta.** Langium rebuilds a
|
|
181
|
-
* document when a dependency changes; if the rebuild produces the
|
|
182
|
-
* same diagnostics, there is nothing new to communicate to subscribers.
|
|
183
|
-
*
|
|
184
|
-
* Without this filter, both scenarios reach subscribers as wire-side
|
|
185
|
-
* `'changed'` events. A subscriber that interprets `'changed'` as
|
|
186
|
-
* "another client wrote new content" and resets its in-memory root to
|
|
187
|
-
* the server view then misreads the spurious event as a concurrent
|
|
188
|
-
* third-party write and loses the user's edits.
|
|
189
|
-
*
|
|
190
|
-
* Initialised on {@link watchModelDocument} to the current
|
|
191
|
-
* document fingerprint so the FIRST phase event after a fresh
|
|
192
|
-
* subscription is also de-duplicated against the state subscribers
|
|
193
|
-
* obtained via `getModelDocument` — they do not need a redundant phase
|
|
194
|
-
* notification for the state they just fetched.
|
|
195
|
-
*
|
|
196
|
-
* Cleared in {@link unwatchModelDocument} when the last
|
|
197
|
-
* subscriber for a URI leaves so memory does not accumulate.
|
|
198
|
-
*
|
|
199
|
-
* Stored as a cyrb53 hex digest (16 chars per URI) rather than the raw
|
|
200
|
-
* text + diagnostics serialisation so the memory cost is constant in
|
|
201
|
-
* document size. See {@link computeDocumentFingerprint} for the inputs.
|
|
202
|
-
*/
|
|
203
|
-
lastEmittedFingerprint = new Map();
|
|
204
|
-
/**
|
|
205
|
-
* URIs whose LAST client just closed. The update handler rebuilds such a
|
|
206
|
-
* document from its disk content (discarding unsaved in-session edits),
|
|
207
|
-
* but {@link dispatchPhaseEvent} gates on the subscription map — and the
|
|
208
|
-
* last close typically also removed the last watcher, so consumers that
|
|
209
|
-
* only ever fetch via `getModelDocument` would keep showing the
|
|
210
|
-
* discarded state forever. Marked on the last-close transition (see
|
|
211
|
-
* {@link subscribeToTextDocumentCloses}) and consumed by
|
|
212
|
-
* {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
|
|
213
|
-
* phase event even without a subscription — de-duplicated against
|
|
214
|
-
* {@link lastEmittedFingerprint} where an entry survives, so a close
|
|
215
|
-
* whose disk state equals the last emitted state stays silent.
|
|
216
|
-
*/
|
|
217
|
-
pendingRevertBroadcasts = new Set();
|
|
165
|
+
* Typed client proxy — sends `data-server/on*` notifications back over the same wire.
|
|
166
|
+
* The proxy sends any `on[A-Z]*` name other than `onDidOpenConnection` and
|
|
167
|
+
* `onDidCloseConnection`, for which it returns its own events, so a subclass
|
|
168
|
+
* with notifications of its own narrows only the type:
|
|
169
|
+
* `declare protected readonly clientProxy: TheirClient`.
|
|
170
|
+
*/
|
|
171
|
+
clientProxy;
|
|
172
|
+
disposables = new DisposableCollection();
|
|
218
173
|
tracer;
|
|
219
174
|
/** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
|
|
220
175
|
activeProfile;
|
|
@@ -226,11 +181,8 @@ export class DataServer {
|
|
|
226
181
|
encoder;
|
|
227
182
|
/**
|
|
228
183
|
* In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
|
|
229
|
-
*
|
|
230
|
-
*
|
|
231
|
-
* while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
|
|
232
|
-
* `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
|
|
233
|
-
* to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
|
|
184
|
+
* Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
|
|
185
|
+
* {@link encoder} converts one into the other on the way out.
|
|
234
186
|
*/
|
|
235
187
|
modelService;
|
|
236
188
|
constructor(connection, services, options = {}) {
|
|
@@ -239,8 +191,7 @@ export class DataServer {
|
|
|
239
191
|
this.options = this.resolveOptions(options);
|
|
240
192
|
this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
|
|
241
193
|
// DI-bound: adopters rebind `services.model.TransferEncoder` /
|
|
242
|
-
// `services.model.ModelService` with their own subclasses.
|
|
243
|
-
// framework upper bounds; the casts below narrow to this instance's generics.
|
|
194
|
+
// `services.model.ModelService` with their own subclasses.
|
|
244
195
|
const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
|
|
245
196
|
if (!encoder || !modelService) {
|
|
246
197
|
throw new Error('DataServer requires `services.model.TransferEncoder` and `services.model.ModelService` to be bound. ' +
|
|
@@ -263,35 +214,42 @@ export class DataServer {
|
|
|
263
214
|
methodNamespace: this.options.methodNamespace,
|
|
264
215
|
localTarget: this,
|
|
265
216
|
localMethods: registeredMethods,
|
|
266
|
-
latency: this.latency
|
|
217
|
+
latency: this.latency,
|
|
218
|
+
// Bound at the chokepoint rather than per handler, so an adopter's
|
|
219
|
+
// `additionalMethods` are rendered on the same terms as the
|
|
220
|
+
// framework's own rejections.
|
|
221
|
+
renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
|
|
267
222
|
});
|
|
268
|
-
this.disposables.push(this.
|
|
269
|
-
|
|
270
|
-
}));
|
|
271
|
-
this.subscribeToDocumentBuilder();
|
|
223
|
+
this.disposables.push(this.modelService.onModelDeleted(event => this.dispatchDeleteEvent(event)));
|
|
224
|
+
this.subscribeToModelUpdates();
|
|
272
225
|
this.subscribeToTextDocumentSaves();
|
|
273
|
-
this.
|
|
226
|
+
this.subscribeToDirtyChanges();
|
|
227
|
+
this.subscribeToModelReleases();
|
|
274
228
|
this.subscribeToProjectManager();
|
|
275
229
|
// Self-register teardown so an adopter that keeps no reference to the
|
|
276
230
|
// server still releases per-connection state, with no lifecycle hook of
|
|
277
|
-
// its own.
|
|
278
|
-
|
|
231
|
+
// its own. The client did not close anything itself, so its sessions end
|
|
232
|
+
// as lost and each document it was the last to have open waits out the
|
|
233
|
+
// store's release grace. See `dispose`.
|
|
234
|
+
this.disposables.push(connection.onClose(() => this.dispose('lost')));
|
|
279
235
|
}
|
|
280
236
|
/**
|
|
281
237
|
* Release everything the constructor wired up — the bound protocol
|
|
282
|
-
* handlers and every listener — and clear
|
|
283
|
-
*
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
* this server's and so outlives the connection unless released here.
|
|
238
|
+
* handlers and every listener — and clear {@link uriWatchRecords}, so a
|
|
239
|
+
* long-lived shared services bundle does not retain per-connection memory
|
|
240
|
+
* after the connection closes. Also ends every session this connection registered, which closes
|
|
241
|
+
* every document it has open: the SHARED store's state rather than this
|
|
242
|
+
* server's, which outlives the connection unless released here.
|
|
288
243
|
*
|
|
289
|
-
* Idempotent: subsequent calls are no-ops.
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
*
|
|
244
|
+
* Idempotent: subsequent calls are no-ops. Runs by itself when the
|
|
245
|
+
* connection closes, so adopters who don't hold a reference still get
|
|
246
|
+
* per-connection cleanup; adopters that DO hold a reference may call
|
|
247
|
+
* `dispose()` directly for early teardown. The sessions end with `cause`:
|
|
248
|
+
* `'closed'` releases every document whose last open they close at once,
|
|
249
|
+
* and `'lost'`, the connection's own close, lets each wait out the release
|
|
250
|
+
* grace.
|
|
293
251
|
*/
|
|
294
|
-
dispose() {
|
|
252
|
+
dispose(cause = 'closed') {
|
|
295
253
|
this.disposed = true;
|
|
296
254
|
// Release an in-flight interactive capture so the process-wide inspector
|
|
297
255
|
// singleton is not left active after the connection closes.
|
|
@@ -300,98 +258,134 @@ export class DataServer {
|
|
|
300
258
|
this.activeProfile = undefined;
|
|
301
259
|
void capture.stop({}).catch(() => undefined);
|
|
302
260
|
}
|
|
303
|
-
// AFTER `disposables.dispose()`, deliberately:
|
|
304
|
-
//
|
|
305
|
-
//
|
|
261
|
+
// AFTER `disposables.dispose()`, deliberately: ending a session releases
|
|
262
|
+
// each document it was the last to hold, and this server's own
|
|
263
|
+
// `onModelReleased` subscription would otherwise mark a release broadcast
|
|
264
|
+
// for a connection that is already gone.
|
|
306
265
|
this.disposables.dispose();
|
|
307
|
-
this.
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
this.
|
|
266
|
+
for (const [clientId, session] of this.clientSessions) {
|
|
267
|
+
this.endSession(clientId, session, cause);
|
|
268
|
+
}
|
|
269
|
+
this.uriWatchRecords.clear();
|
|
270
|
+
this.watchKeys.clear();
|
|
311
271
|
}
|
|
312
272
|
// ============================================================
|
|
313
|
-
// DataServerProtocol implementation
|
|
273
|
+
// DataServerProtocol implementation
|
|
314
274
|
// ============================================================
|
|
315
275
|
//
|
|
316
|
-
//
|
|
317
|
-
//
|
|
318
|
-
// the wire boundary via
|
|
319
|
-
//
|
|
320
|
-
//
|
|
321
|
-
//
|
|
322
|
-
async
|
|
323
|
-
//
|
|
324
|
-
//
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
// `baseVersion` against, so reporting the snapshot's would make the
|
|
344
|
-
// caller's first tagged write self-conflict. A genuine concurrent edit
|
|
345
|
-
// still trips the gate and is reconciled by the caller's replay rather
|
|
346
|
-
// than predicted here.
|
|
347
|
-
return { ...document, version: this.services.workspace.TextDocuments.version(args.uri) };
|
|
276
|
+
// Reads go to `ModelService`; a request that opens or writes a document
|
|
277
|
+
// goes to the session this connection registered under its `clientId`.
|
|
278
|
+
// Each answer is encoded on the wire boundary via
|
|
279
|
+
// `encoder.astDocumentToTransferDocument`. To change how documents are
|
|
280
|
+
// read, override on the ModelService subclass; to change how they are
|
|
281
|
+
// written, on the session class the bound `ClientSessionFactory` builds.
|
|
282
|
+
async createSession(args) {
|
|
283
|
+
// After teardown nothing would ever end a session registered now, and its
|
|
284
|
+
// id would stay taken for the life of the process.
|
|
285
|
+
if (this.disposed) {
|
|
286
|
+
throw new SessionClosedError(args.clientId);
|
|
287
|
+
}
|
|
288
|
+
const session = this.modelService.createSession(args.label, args.clientId, { resumeToken: args.resumeToken });
|
|
289
|
+
this.clientSessions.set(args.clientId, session);
|
|
290
|
+
// A session also ends without closeSession, as when a client registers
|
|
291
|
+
// again on another connection, and its watches and entry here would
|
|
292
|
+
// otherwise outlive it.
|
|
293
|
+
session.onDidDispose(cause => {
|
|
294
|
+
// A session class may report its end late, once a replacement holds
|
|
295
|
+
// the id here; the replacement's entry and watches stay.
|
|
296
|
+
if (this.clientSessions.get(args.clientId) !== session) {
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
this.dropWatches(args.clientId);
|
|
300
|
+
this.clientSessions.delete(args.clientId);
|
|
301
|
+
this.tracer.debug(`Forget session ${args.clientId}: it ended as ${cause}`);
|
|
302
|
+
});
|
|
348
303
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
304
|
+
/** End a session this connection registered. */
|
|
305
|
+
async closeSession(args) {
|
|
306
|
+
const session = this.clientSessions.get(args.clientId);
|
|
307
|
+
if (session) {
|
|
308
|
+
this.endSession(args.clientId, session);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
|
|
312
|
+
endSession(clientId, session, cause = 'closed') {
|
|
313
|
+
this.dropWatches(clientId);
|
|
314
|
+
session.dispose(cause);
|
|
315
|
+
}
|
|
316
|
+
dropWatches(clientId) {
|
|
317
|
+
this.watchKeys.delete(clientId);
|
|
318
|
+
for (const [uri, record] of this.uriWatchRecords) {
|
|
319
|
+
if (record.watchers.delete(clientId)) {
|
|
320
|
+
this.pruneUriWatchRecord(uri);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
async createModelDocument(args) {
|
|
325
|
+
const session = this.requireSession(args.clientId);
|
|
326
|
+
await session.create(args.uri, args.text);
|
|
327
|
+
return this.openedSnapshot(args.uri, () => session.close(args.uri));
|
|
328
|
+
}
|
|
329
|
+
async updateModelDocuments(args) {
|
|
330
|
+
const astDocuments = await this.requireSession(args.clientId).updateAll({
|
|
331
|
+
updates: args.updates.map(update => this.toSessionWrite(update))
|
|
332
|
+
});
|
|
333
|
+
return astDocuments.map(astDocument => this.encodeDocument(astDocument));
|
|
356
334
|
}
|
|
357
335
|
/**
|
|
358
|
-
*
|
|
359
|
-
*
|
|
336
|
+
* The session write a wire write request carries. Only the fields a session
|
|
337
|
+
* takes: a field an adopter adds to a request reaches the session only
|
|
338
|
+
* through an override of this.
|
|
360
339
|
*/
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
340
|
+
toSessionWrite(request) {
|
|
341
|
+
return { uri: request.uri, model: request.model, baseVersion: request.baseVersion };
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The session this connection registered under `clientId`, which every
|
|
345
|
+
* document request acts as. An id that is not one fails with the
|
|
346
|
+
* closed-session code: opening or writing under it would leave an open that
|
|
347
|
+
* no session end ever closes.
|
|
348
|
+
*/
|
|
349
|
+
requireSession(clientId) {
|
|
350
|
+
const session = this.clientSessions.get(clientId);
|
|
351
|
+
if (!session) {
|
|
352
|
+
throw new SessionClosedError(clientId, 'The client session is not registered on this connection.');
|
|
369
353
|
}
|
|
354
|
+
return session;
|
|
355
|
+
}
|
|
356
|
+
async openModelDocument(args) {
|
|
357
|
+
const session = this.requireSession(args.clientId);
|
|
358
|
+
const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
|
|
359
|
+
await session.open(args.uri, args.options);
|
|
360
|
+
// A repeat open keeps the earlier one, which is still in use.
|
|
361
|
+
return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
|
|
370
362
|
}
|
|
371
363
|
/**
|
|
372
|
-
*
|
|
373
|
-
*
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
*/
|
|
386
|
-
closeOpenDocuments() {
|
|
387
|
-
const held = [...this.openedDocuments];
|
|
388
|
-
this.openedDocuments.clear();
|
|
389
|
-
for (const [uri, clientIds] of held) {
|
|
390
|
-
for (const clientId of clientIds) {
|
|
391
|
-
void Promise.resolve(this.modelService.close({ uri, clientId })).catch(() => undefined);
|
|
392
|
-
}
|
|
364
|
+
* The snapshot a session's open or create answers with. When the read
|
|
365
|
+
* fails, `rollback` undoes the open this call made before the failure is
|
|
366
|
+
* rethrown: the caller sees no open, so nothing on its side would ever close
|
|
367
|
+
* it.
|
|
368
|
+
*/
|
|
369
|
+
async openedSnapshot(uri, rollback) {
|
|
370
|
+
try {
|
|
371
|
+
return await this.getModelDocument({ uri });
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
// The open's failure is the one the caller needs, not the cleanup's.
|
|
375
|
+
await rollback?.().catch(() => undefined);
|
|
376
|
+
throw error;
|
|
393
377
|
}
|
|
394
378
|
}
|
|
379
|
+
async closeModelDocument(args) {
|
|
380
|
+
// Through the handle, so a close under an ended session fails as that
|
|
381
|
+
// session's calls do, and a session class's own close is honoured.
|
|
382
|
+
const session = this.requireSession(args.clientId);
|
|
383
|
+
// Closing also releases the watch for (uri, clientId) — a forgotten
|
|
384
|
+
// unwatch would otherwise leak phase-event dispatch until the connection
|
|
385
|
+
// closes. Idempotent: a close without a prior watch is a no-op.
|
|
386
|
+
await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
|
|
387
|
+
await session.close(args.uri);
|
|
388
|
+
}
|
|
395
389
|
async getModelDocument(args) {
|
|
396
390
|
// Smart dispatch: a warm document (already in LangiumDocuments) is
|
|
397
391
|
// returned at its settle phase without a redundant build; a cold URI
|
|
@@ -404,72 +398,124 @@ export class DataServer {
|
|
|
404
398
|
// unsubscribed caller that needs diagnostics inline passes
|
|
405
399
|
// `includeDiagnostics: true` to settle at `Validated` instead.
|
|
406
400
|
const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
|
|
407
|
-
|
|
408
|
-
|
|
401
|
+
try {
|
|
402
|
+
return this.encodeDocument(await this.modelService.ensureDocumentState(args.uri, state));
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
// The protocol answers a read of a URI with no document with an
|
|
406
|
+
// envelope that has no model.
|
|
407
|
+
if (this.isMissingDocument(error, args.uri)) {
|
|
408
|
+
return this.envelope(UriUtils.toUri(args.uri));
|
|
409
|
+
}
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
409
412
|
}
|
|
410
413
|
async updateModelDocument(args) {
|
|
411
|
-
const astDocument = await this.
|
|
412
|
-
return this.
|
|
414
|
+
const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
|
|
415
|
+
return this.encodeDocument(astDocument);
|
|
413
416
|
}
|
|
414
417
|
async saveModelDocument(args) {
|
|
415
|
-
const astDocument = await this.
|
|
416
|
-
return this.
|
|
418
|
+
const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
|
|
419
|
+
return { ...this.encodeDocument(astDocument), persisted: astDocument.persisted };
|
|
420
|
+
}
|
|
421
|
+
async persistModelDocument(args) {
|
|
422
|
+
const version = await this.requireSession(args.clientId).persist({ uri: args.uri, baseVersion: args.baseVersion });
|
|
423
|
+
const astDocument = await this.modelService.ensureDocumentState(args.uri, this.services.workspace.DocumentBuilder.finalBuildState());
|
|
424
|
+
return { ...this.encodeDocument(astDocument), persisted: { version } };
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Delete the document through the session, then release the session's
|
|
428
|
+
* watch of it, as {@link closeModelDocument} does. Released only after the
|
|
429
|
+
* delete: one that fails leaves the session its open and its watch. Other
|
|
430
|
+
* sessions' watches survive, as for any deletion.
|
|
431
|
+
*/
|
|
432
|
+
async deleteModelDocument(args) {
|
|
433
|
+
const session = this.requireSession(args.clientId);
|
|
434
|
+
// Keyed before the delete: once the file is gone, a symlink to it no
|
|
435
|
+
// longer resolves to the key the watch is under.
|
|
436
|
+
const uri = this.canonicalKey(args.uri);
|
|
437
|
+
await session.delete({ uri: args.uri, baseVersion: args.baseVersion });
|
|
438
|
+
await this.unwatchModelDocument({ uri, clientId: args.clientId });
|
|
417
439
|
}
|
|
418
440
|
/**
|
|
419
441
|
* Record a watch for `(uri, clientId)`. Subsequent phase events on `uri`
|
|
420
442
|
* fan out to the wired `clientProxy.onDocumentUpdated`. The
|
|
421
443
|
* bidirectional pattern means the event channel is the client
|
|
422
444
|
* notification surface, not a returned handle — this method only
|
|
423
|
-
* registers the
|
|
445
|
+
* registers the watcher in {@link uriWatchRecords}.
|
|
424
446
|
*
|
|
425
|
-
* Also baselines the
|
|
426
|
-
* {@link
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
* redundant phase notification for that same state.
|
|
447
|
+
* Also baselines the URI's emission fingerprint (see
|
|
448
|
+
* {@link dispatchPhaseEvent}) to the document's current state when the
|
|
449
|
+
* first watcher for the URI registers. This guarantees that any phase event firing immediately after
|
|
450
|
+
* the watch with no observable change is suppressed — watchers obtain
|
|
451
|
+
* initial state via `getModelDocument` (or {@link openModelDocument}) and
|
|
452
|
+
* do not need a redundant phase notification for that same state.
|
|
432
453
|
*/
|
|
433
454
|
async watchModelDocument(args) {
|
|
434
455
|
const uri = this.canonicalKey(args.uri);
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
456
|
+
const keys = this.watchKeys.get(args.clientId) ?? new Map();
|
|
457
|
+
this.watchKeys.set(args.clientId, keys.set(args.uri, uri));
|
|
458
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set() };
|
|
459
|
+
this.uriWatchRecords.set(uri, record);
|
|
460
|
+
record.watchers.add(args.clientId);
|
|
461
|
+
if (record.fingerprint === undefined) {
|
|
462
|
+
const document = this.modelService.getDocument(args.uri);
|
|
463
|
+
if (document && !this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
|
|
464
|
+
record.fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
|
|
465
|
+
record.fingerprintVersion = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
|
|
445
466
|
}
|
|
446
467
|
}
|
|
447
468
|
}
|
|
448
469
|
/**
|
|
449
470
|
* Remove a watch for `(uri, clientId)` previously created by
|
|
450
471
|
* {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
|
|
451
|
-
* Dispatch for `uri` stops once no watchers remain,
|
|
452
|
-
*
|
|
453
|
-
*
|
|
454
|
-
*
|
|
472
|
+
* Dispatch for `uri` stops once no watchers remain, and the emission
|
|
473
|
+
* fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
|
|
474
|
+
*
|
|
475
|
+
* A URI the client watched is unwatched under the key it resolved to then,
|
|
476
|
+
* from {@link watchKeys}, which still holds once its file is gone.
|
|
455
477
|
*/
|
|
456
478
|
async unwatchModelDocument(args) {
|
|
457
|
-
const
|
|
458
|
-
const
|
|
459
|
-
|
|
479
|
+
const keys = this.watchKeys.get(args.clientId);
|
|
480
|
+
const uri = keys?.get(args.uri) ?? this.canonicalKey(args.uri);
|
|
481
|
+
// Every spelling the client watched it under was this one watch.
|
|
482
|
+
keys?.forEach((key, spelling) => {
|
|
483
|
+
if (key === uri) {
|
|
484
|
+
keys.delete(spelling);
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
if (keys?.size === 0) {
|
|
488
|
+
this.watchKeys.delete(args.clientId);
|
|
489
|
+
}
|
|
490
|
+
if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
|
|
491
|
+
this.pruneUriWatchRecord(uri);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Drop what `uri` no longer needs: the
|
|
496
|
+
* {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
|
|
497
|
+
* and the whole record once it holds no
|
|
498
|
+
* {@link DataServerUriWatchRecord.releaseBroadcastPending} mark either.
|
|
499
|
+
* Every path that removes a watcher or consumes a mark ends here.
|
|
500
|
+
*/
|
|
501
|
+
pruneUriWatchRecord(uri) {
|
|
502
|
+
const record = this.uriWatchRecords.get(uri);
|
|
503
|
+
if (!record || record.watchers.size > 0) {
|
|
460
504
|
return;
|
|
461
505
|
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
506
|
+
if (record.releaseBroadcastPending) {
|
|
507
|
+
record.fingerprint = undefined;
|
|
508
|
+
record.fingerprintVersion = undefined;
|
|
509
|
+
}
|
|
510
|
+
else {
|
|
511
|
+
this.uriWatchRecords.delete(uri);
|
|
466
512
|
}
|
|
467
513
|
}
|
|
468
514
|
/**
|
|
469
|
-
* Canonicalise a URI string for use as a
|
|
470
|
-
*
|
|
471
|
-
*
|
|
472
|
-
*
|
|
515
|
+
* Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
|
|
516
|
+
* shared `DocumentUriPolicy`. Callers may send non-canonical URIs
|
|
517
|
+
* (drive-letter casing, percent-encoding differences, or a symlink path)
|
|
518
|
+
* over the wire; the dispatch side keys by
|
|
473
519
|
* `document.uri.toString()` from `LangiumDocuments`, so writer keys must
|
|
474
520
|
* canonicalise to the same form or events silently fail to deliver.
|
|
475
521
|
* Routing through the seam (rather than a bare `UriUtils.normalize`)
|
|
@@ -479,24 +525,22 @@ export class DataServer {
|
|
|
479
525
|
* LSP head resolves.
|
|
480
526
|
*
|
|
481
527
|
* Adopters can still override for head-specific URI policy by subclassing.
|
|
528
|
+
* The result keys watches only; a document is looked up by its own URI.
|
|
482
529
|
*/
|
|
483
530
|
canonicalKey(uri) {
|
|
484
531
|
return this.services.workspace.DocumentUriPolicy.canonicalUri(uri);
|
|
485
532
|
}
|
|
486
533
|
async getProjects() {
|
|
487
|
-
// Pass-through: `ProjectManager<TProject>` already produces `TProject`
|
|
488
|
-
// (the shared services are parameterised over the same generic).
|
|
489
534
|
// The framework reads `id` for registry identity and `dependencies`
|
|
490
535
|
// for the visibility closure; every other field rides on the
|
|
491
536
|
// JSON-RPC envelope as adopter-defined wire metadata.
|
|
492
|
-
return this.services.workspace.ProjectManager.getProjects();
|
|
537
|
+
return this.services.workspace.ProjectManager.getProjects().map(project => this.encodeProject(project));
|
|
493
538
|
}
|
|
494
539
|
async getProjectForUri(args) {
|
|
495
|
-
//
|
|
496
|
-
//
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
return this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
|
|
540
|
+
// Membership logic belongs to the adopter's `ProjectManager`; the
|
|
541
|
+
// data-server forwards the URI without interpretation.
|
|
542
|
+
const project = this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
|
|
543
|
+
return project && this.encodeProject(project);
|
|
500
544
|
}
|
|
501
545
|
/**
|
|
502
546
|
* Resolve once the data-server is ready to serve requests. Delegates
|
|
@@ -513,26 +557,56 @@ export class DataServer {
|
|
|
513
557
|
// Resolve the language's reference services from each request's source
|
|
514
558
|
// (see resolveReferenceServices) and delegate.
|
|
515
559
|
// ============================================================
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
560
|
+
/**
|
|
561
|
+
* Settle the build before a reference question is answered from the index.
|
|
562
|
+
*
|
|
563
|
+
* A query issued right after a model update otherwise races the rebuild and
|
|
564
|
+
* reads an index missing the symbols it asks about. The cost is not confined
|
|
565
|
+
* to this call: a scope built inside that window is cached, and the build's
|
|
566
|
+
* remaining documents link against it.
|
|
567
|
+
*
|
|
568
|
+
* Waits the source document specifically, but ONLY when one is loaded at
|
|
569
|
+
* that URI: a synthetic source can address a URI with no document (a
|
|
570
|
+
* directory URI, typically), where a per-URI `waitUntil` throws "No document
|
|
571
|
+
* found". Falls back to a global settle, matching the id-based
|
|
572
|
+
* `ElementSource` path.
|
|
573
|
+
*
|
|
574
|
+
* Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
575
|
+
*/
|
|
576
|
+
async awaitReferencesLinked(source) {
|
|
577
|
+
const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
|
|
525
578
|
const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
|
|
526
|
-
|
|
579
|
+
const stopwatch = this.services.Clock.stopwatch();
|
|
580
|
+
const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
|
|
581
|
+
if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
const elapsedMs = Math.round(stopwatch.elapsedMs);
|
|
585
|
+
// A per-URI wait resolves off a document-phase notification, so a
|
|
586
|
+
// missed one strands a wait on a document that HAS reached the
|
|
587
|
+
// phase. Re-read before failing; the workspace-wide wait has no
|
|
588
|
+
// equivalent reading and can only reject.
|
|
589
|
+
const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
|
|
590
|
+
if (waitUri && document && document.state >= DocumentState.Linked) {
|
|
591
|
+
this.tracer
|
|
592
|
+
.withUri(waitUri.toString())
|
|
593
|
+
.warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
throw referenceSettleTimeoutError(elapsedMs);
|
|
597
|
+
}
|
|
598
|
+
async findReferenceCandidates(ctx) {
|
|
599
|
+
await this.awaitReferencesLinked(ctx.source);
|
|
527
600
|
return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
|
|
528
601
|
}
|
|
529
602
|
async resolveReference(ref) {
|
|
603
|
+
await this.awaitReferencesLinked(ref.source);
|
|
530
604
|
const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
|
|
531
605
|
if (!resolved) {
|
|
532
606
|
return undefined;
|
|
533
607
|
}
|
|
534
|
-
|
|
535
|
-
return { ...resolved.candidate, element };
|
|
608
|
+
// `TElement` is the caller's claim about the target's type; nothing checks it.
|
|
609
|
+
return { ...resolved.candidate, element: this.encoder.toTransfer(resolved.node) };
|
|
536
610
|
}
|
|
537
611
|
async findNextName(args) {
|
|
538
612
|
const uri = UriUtils.toUri(args.uri);
|
|
@@ -541,15 +615,32 @@ export class DataServer {
|
|
|
541
615
|
// synthetic source — and the create-element flow driving this method is
|
|
542
616
|
// the one that produces directory URIs, on which a bare
|
|
543
617
|
// `getServices(uri)` throws while `findReferenceCandidates` succeeds.
|
|
544
|
-
const
|
|
618
|
+
const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
|
|
619
|
+
// Mid-rebuild the names of documents not yet re-indexed are absent from
|
|
620
|
+
// the taken set, and the caller PERSISTS what it is handed. Nothing
|
|
621
|
+
// reserves the answer either, so a name is free of the collisions the
|
|
622
|
+
// index knows about and of nothing else — two callers racing get the same
|
|
623
|
+
// proposal, which only uniqueness at the write can catch.
|
|
624
|
+
await this.awaitReferencesLinked(source);
|
|
625
|
+
const nameProvider = this.resolveReferenceServices(source).NameProvider;
|
|
545
626
|
const tier = args.tier ?? 'project';
|
|
546
627
|
if (tier === 'public') {
|
|
547
628
|
return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
|
|
548
629
|
}
|
|
549
630
|
if (tier === 'local') {
|
|
550
|
-
// Document-scoped uniqueness: the document root is the container.
|
|
551
|
-
|
|
552
|
-
|
|
631
|
+
// Document-scoped uniqueness: the document root is the container. A
|
|
632
|
+
// URI with no document has nothing to collide with, like a document
|
|
633
|
+
// with no root.
|
|
634
|
+
try {
|
|
635
|
+
const document = await this.modelService.ensureDocumentState(args.uri);
|
|
636
|
+
return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
|
|
637
|
+
}
|
|
638
|
+
catch (error) {
|
|
639
|
+
if (this.isMissingDocument(error, args.uri)) {
|
|
640
|
+
return args.proposal;
|
|
641
|
+
}
|
|
642
|
+
throw error;
|
|
643
|
+
}
|
|
553
644
|
}
|
|
554
645
|
const project = this.services.workspace.ProjectManager.getProject(uri);
|
|
555
646
|
if (!project) {
|
|
@@ -582,66 +673,30 @@ export class DataServer {
|
|
|
582
673
|
return language.references;
|
|
583
674
|
}
|
|
584
675
|
/**
|
|
585
|
-
* Pick the language that owns a reference source
|
|
676
|
+
* Pick the language that owns a reference source: the registry's
|
|
677
|
+
* `getLanguageFor` over the source's declared language, URI and AST type,
|
|
678
|
+
* with an {@link isElementSource} routed by the document that holds the
|
|
679
|
+
* element (see {@link findElementDocumentUri}) before its type, and
|
|
680
|
+
* {@link fallbackReferenceLanguage}, adopter policy, last.
|
|
586
681
|
*
|
|
587
|
-
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
590
|
-
* single-language adopters never reach the steps below, and never pay
|
|
591
|
-
* for them.
|
|
592
|
-
* 3. An {@link isElementSource} source carries no URI, so in a
|
|
593
|
-
* multi-language workspace it is routed via the document that holds the
|
|
594
|
-
* element (see {@link findElementDocumentUri}).
|
|
595
|
-
* 4. A source carrying an AST type is routed by that type when exactly one
|
|
596
|
-
* registered grammar can produce it (see
|
|
597
|
-
* {@link resolveReferenceLanguageByType}, over the registry's own type
|
|
598
|
-
* index). This is what resolves a create-element flow's synthetic source
|
|
599
|
-
* on a bare directory URI without asking the adopter.
|
|
600
|
-
* 5. Anything still unresolved falls to {@link fallbackReferenceLanguage},
|
|
601
|
-
* which is adopter policy.
|
|
682
|
+
* An unregistered declared language falls through rather than failing: the
|
|
683
|
+
* id crosses the wire, so a client built against a head with one more
|
|
684
|
+
* grammar would otherwise lose queries the other signals answer.
|
|
602
685
|
*/
|
|
603
686
|
resolveReferenceLanguage(source) {
|
|
604
687
|
const registry = this.services.ServiceRegistry;
|
|
605
|
-
// `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
|
|
606
|
-
// an extensionless / unregistered URI falls through to the steps below
|
|
607
|
-
// rather than throwing "no services for the extension ''".
|
|
608
|
-
const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
|
|
609
|
-
const byUri = uri && registry.getServicesFor(uri);
|
|
610
|
-
if (byUri) {
|
|
611
|
-
return byUri;
|
|
612
|
-
}
|
|
613
|
-
const all = registry.all;
|
|
614
|
-
if (all.length === 1) {
|
|
615
|
-
return all[0];
|
|
616
|
-
}
|
|
617
688
|
if (isElementSource(source)) {
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
}
|
|
689
|
+
// The index lookup runs only once the cheaper signals abstained.
|
|
690
|
+
return (registry.getLanguageFor({}) ??
|
|
691
|
+
registry.getLanguageFor({ target: this.findElementDocumentUri(source), type: source.type }) ??
|
|
692
|
+
this.fallbackReferenceLanguage(source));
|
|
623
693
|
}
|
|
624
|
-
const
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
* {@link isElementSource}'s optional narrowing `type`.
|
|
631
|
-
*
|
|
632
|
-
* Answers only when EXACTLY ONE registered grammar can produce the type.
|
|
633
|
-
* Several can when the type comes from a grammar both import, and then the
|
|
634
|
-
* type genuinely does not identify a language — that is a fall-through to
|
|
635
|
-
* adopter policy, not a coin toss. Note this asks which grammar can *produce*
|
|
636
|
-
* the type, not which mentions it: a grammar that merely cross-references a
|
|
637
|
-
* type can never hold a node of it.
|
|
638
|
-
*/
|
|
639
|
-
resolveReferenceLanguageByType(source) {
|
|
640
|
-
const type = isSyntheticSource(source) ? source.type : isElementSource(source) ? source.type : undefined;
|
|
641
|
-
// The registry owns the type index — it is the one place that knows when
|
|
642
|
-
// the registered set changed, so unlike a private memo here it cannot go
|
|
643
|
-
// stale on a language registered after the first lookup.
|
|
644
|
-
return type ? this.services.ServiceRegistry.soleServicesByType(type) : undefined;
|
|
694
|
+
const hint = isSyntheticSource(source)
|
|
695
|
+
? { languageId: source.language, target: source.uri, type: source.type }
|
|
696
|
+
: isDocumentSource(source)
|
|
697
|
+
? { target: source.uri }
|
|
698
|
+
: {};
|
|
699
|
+
return registry.getLanguageFor(hint) ?? this.fallbackReferenceLanguage(source);
|
|
645
700
|
}
|
|
646
701
|
/**
|
|
647
702
|
* Locate the document that holds the element an {@link ElementSource}
|
|
@@ -650,15 +705,14 @@ export class DataServer {
|
|
|
650
705
|
* disambiguates names that repeat across types (honouring grammar
|
|
651
706
|
* subtyping through `AstReflection.isSubtype`).
|
|
652
707
|
*
|
|
653
|
-
* Only reached
|
|
654
|
-
*
|
|
655
|
-
* step 2.
|
|
708
|
+
* Only reached in a multi-language workspace, once the declared language
|
|
709
|
+
* and the URI have abstained.
|
|
656
710
|
*
|
|
657
711
|
* Abstains when the name matches elements in more than one DOCUMENT — the
|
|
658
712
|
* index spans every language and is filled in build order, so "the
|
|
659
|
-
* first match" would be file-watch order rather than an answer.
|
|
660
|
-
* then falls through to the type
|
|
661
|
-
*
|
|
713
|
+
* first match" would be file-watch order rather than an answer. Routing
|
|
714
|
+
* then falls through to the element's type, which abstains on ties in the
|
|
715
|
+
* same way, and finally to adopter policy.
|
|
662
716
|
*/
|
|
663
717
|
findElementDocumentUri(source) {
|
|
664
718
|
const matches = this.services.workspace.IndexManager.getElementsByName(source.name, source.type);
|
|
@@ -690,55 +744,144 @@ export class DataServer {
|
|
|
690
744
|
// ============================================================
|
|
691
745
|
// Internal plumbing
|
|
692
746
|
// ============================================================
|
|
747
|
+
/**
|
|
748
|
+
* Whether `error`, from waiting on `uri`'s document, means that `uri` has
|
|
749
|
+
* no document: a URI with neither a file nor text builds nothing, and
|
|
750
|
+
* Langium's wait after the build rejects for want of one, with a
|
|
751
|
+
* `ServerCancelled` response error. Any other failure, such as a read
|
|
752
|
+
* that fails before a document is registered, a cancelled wait or a
|
|
753
|
+
* `ReentrantWriteLockError`, is the caller's to see.
|
|
754
|
+
*/
|
|
755
|
+
isMissingDocument(error, uri) {
|
|
756
|
+
return isResponseError(error) && error.code === SERVER_CANCELLED && this.modelService.getDocument(uri) === undefined;
|
|
757
|
+
}
|
|
693
758
|
/**
|
|
694
759
|
* Build a {@link TransferDocument} envelope from the current document state,
|
|
695
760
|
* delegating root + diagnostic encoding to {@link encoder} (see
|
|
696
|
-
* `TransferEncoder.toTransferDocument` for the walk).
|
|
697
|
-
*
|
|
698
|
-
*
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
* its wire types. The cast on the return is where that invariant — the
|
|
702
|
-
* adopter's `TTransfer` matches its encoder's overlay — is asserted, at a
|
|
703
|
-
* single boundary point rather than spread across the callers.
|
|
704
|
-
*/
|
|
705
|
-
envelope(uri) {
|
|
761
|
+
* `TransferEncoder.toTransferDocument` for the walk). `fingerprint` is the
|
|
762
|
+
* caller's {@link computeDocumentFingerprint} of that same state, which
|
|
763
|
+
* spares hashing it twice.
|
|
764
|
+
*/
|
|
765
|
+
envelope(uri, fingerprint) {
|
|
706
766
|
// Resolve through the model service's canonicalizing gateway rather than
|
|
707
767
|
// reaching into `LangiumDocuments` directly, so a divergent (symlink) URI
|
|
708
768
|
// still finds the document the build keys by its real path — and so the
|
|
709
769
|
// data-server never has to remember to canonicalize this lookup itself.
|
|
710
770
|
const document = this.modelService.getDocument(uri.toString());
|
|
711
|
-
if (!document) {
|
|
771
|
+
if (!document || this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
|
|
712
772
|
// No document — a shaped envelope rather than a throw, so the caller
|
|
713
|
-
// decides policy at its own layer; `
|
|
773
|
+
// decides policy at its own layer; `model` is optional on the envelope
|
|
714
774
|
// so the compiler forces that decision. Adopters preferring to throw
|
|
715
|
-
// override `envelope`.
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
version: 0,
|
|
719
|
-
root: undefined,
|
|
720
|
-
diagnostics: []
|
|
721
|
-
};
|
|
775
|
+
// override `envelope`. The builder's unparsed placeholder is no
|
|
776
|
+
// document either: its root parses no text.
|
|
777
|
+
return TransferDocument.absent(uri.toString());
|
|
722
778
|
}
|
|
723
|
-
|
|
779
|
+
const encoded = this.encoder.toTransferDocument(document);
|
|
780
|
+
return this.withServerState(encoded, fingerprint ?? this.computeDocumentFingerprint(document.parseResult.value, encoded));
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* The transfer document a request answers with for `astDocument`, its model
|
|
784
|
+
* hashed and the text stamped on it by {@link withServerState}. Every
|
|
785
|
+
* document a request answers with goes through here, so none goes out
|
|
786
|
+
* without them.
|
|
787
|
+
*/
|
|
788
|
+
encodeDocument(astDocument) {
|
|
789
|
+
const encoded = this.encoder.astDocumentToTransferDocument(astDocument);
|
|
790
|
+
return this.withServerState(encoded, this.computeDocumentFingerprint(astDocument.root, encoded));
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* The project a client receives for `project`, unchanged by default. Every
|
|
794
|
+
* project a request answers with or a change notification carries goes
|
|
795
|
+
* through here, so a field derived for clients cannot miss one path. The
|
|
796
|
+
* result crosses as JSON, so a value a client reads goes in a data field,
|
|
797
|
+
* not a getter.
|
|
798
|
+
*/
|
|
799
|
+
encodeProject(project) {
|
|
800
|
+
return project;
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* `encoded` with `hash` on its model and the text the server holds for it:
|
|
804
|
+
* the store's while it holds the document, the build's otherwise. The text
|
|
805
|
+
* is read when the document is sent rather than kept with the build: a save
|
|
806
|
+
* changes `text.dirty` without a rebuild, and the store's text moves on before
|
|
807
|
+
* the build that follows it.
|
|
808
|
+
*/
|
|
809
|
+
withServerState(encoded, hash) {
|
|
810
|
+
const text = this.services.workspace.TextDocuments.textState(encoded.uri) ?? this.builtTextState(encoded.uri);
|
|
811
|
+
if (text && text.version > encoded.model.version) {
|
|
812
|
+
this.tracer.withUri(encoded.uri).debug(`Send a model behind its text: model v${encoded.model.version} / text v${text.version}`);
|
|
813
|
+
}
|
|
814
|
+
return {
|
|
815
|
+
uri: encoded.uri,
|
|
816
|
+
// The encoder returns the structural base; `TTransfer` is the adopter's
|
|
817
|
+
// declaration of the roots its languages produce, and nothing checks it.
|
|
818
|
+
model: { ...encoded.model, hash },
|
|
819
|
+
...(text ? { text } : {})
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* The text a build read for a document the store never held, which is
|
|
824
|
+
* clean: the store holds every text a client gave it.
|
|
825
|
+
*/
|
|
826
|
+
builtTextState(uri) {
|
|
827
|
+
const textDocument = this.modelService.getDocument(uri)?.textDocument;
|
|
828
|
+
return textDocument && { version: textDocument.version, hash: textHash(textDocument.getText()), dirty: false };
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Follow every document at the configured
|
|
832
|
+
* {@link DataServerOptions.subscriptionPhase}, once per connection rather
|
|
833
|
+
* than once per watch, so the cost stays flat in the number of watches.
|
|
834
|
+
*/
|
|
835
|
+
subscribeToModelUpdates() {
|
|
836
|
+
const phase = this.options.subscriptionPhase;
|
|
837
|
+
this.disposables.push(this.modelService.onModelUpdated(event => this.dispatchPhaseEvent(event), { phase }));
|
|
838
|
+
// One message per build rather than one per document.
|
|
839
|
+
this.disposables.push(this.modelService.onModelsBuilt(event => this.dispatchBuiltEvent(event.uris), { phase }));
|
|
724
840
|
}
|
|
725
841
|
/**
|
|
726
|
-
*
|
|
727
|
-
*
|
|
728
|
-
*
|
|
729
|
-
*
|
|
842
|
+
* Report the documents that reached {@link DataServerOptions.subscriptionPhase}
|
|
843
|
+
* and that NOBODY on this
|
|
844
|
+
* connection is watching — the ones a client was not told about through
|
|
845
|
+
* {@link dispatchPhaseEvent}, which is gated per URI.
|
|
846
|
+
*
|
|
847
|
+
* **The gap this closes is the one no other source can observe.** A document
|
|
848
|
+
* the client watches, it hears about already. A file changed on disk, the
|
|
849
|
+
* host's own filesystem watcher reports — and on a browser host, where the
|
|
850
|
+
* workspace lives behind this head, an external change cannot happen at all.
|
|
851
|
+
* What is left, and what nothing outside the server can see, is a document
|
|
852
|
+
* rebuilt because something it DEPENDS ON changed: its file never changed, so
|
|
853
|
+
* a filesystem watcher is silent by construction, and it has no subscriber, so
|
|
854
|
+
* the update channel is silent by design. A consumer displaying data derived
|
|
855
|
+
* from that document — a tree label, a decorator — otherwise goes stale with
|
|
856
|
+
* no signal from any source, and repairs itself the moment someone opens the
|
|
857
|
+
* file to investigate, which is what makes it expensive to diagnose later.
|
|
858
|
+
*
|
|
859
|
+
* Payload-free on purpose: URIs only, so a client re-reads what it displays
|
|
860
|
+
* rather than being handed transfer documents it did not ask for. That is the
|
|
861
|
+
* property the watcher gate protects, and it is preserved here by
|
|
862
|
+
* carrying no document rather than by gating the message.
|
|
863
|
+
*
|
|
864
|
+
* Quiet in the common case. Editing a document that an editor has open leaves
|
|
865
|
+
* that URI watched and therefore out of this set, so a build with no
|
|
866
|
+
* dependents produces nothing at all, and workspace initialisation produces
|
|
867
|
+
* nothing because it does not build to this phase. The ceiling is a
|
|
868
|
+
* whole-workspace rebuild at the subscription phase: one message, URIs only.
|
|
730
869
|
*/
|
|
731
|
-
|
|
732
|
-
|
|
870
|
+
dispatchBuiltEvent(built) {
|
|
871
|
+
const uris = built.map(uri => this.canonicalKey(uri)).filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
|
|
872
|
+
if (uris.length === 0) {
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
875
|
+
this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
|
|
876
|
+
this.clientProxy.onDocumentsBuilt({ uris });
|
|
733
877
|
}
|
|
734
878
|
/**
|
|
735
|
-
*
|
|
736
|
-
*
|
|
737
|
-
*
|
|
738
|
-
*
|
|
739
|
-
* or any other client writing through `notifyDidSaveTextDocument`.
|
|
879
|
+
* Follow every save so a single `onDocumentSaved` wire notification fires
|
|
880
|
+
* for ANY save of a subscribed URI — regardless of whether the save
|
|
881
|
+
* originated from the data-server's RPC `saveModelDocument`, the LSP head's
|
|
882
|
+
* text-editor save, or any other client.
|
|
740
883
|
*
|
|
741
|
-
* Architectural symmetry with {@link
|
|
884
|
+
* Architectural symmetry with {@link subscribeToModelUpdates}: every
|
|
742
885
|
* subscribed client sees every state change to documents they care about,
|
|
743
886
|
* regardless of which client triggered it. Firing `onDocumentSaved` only
|
|
744
887
|
* from the data-server's own RPC path is a bug, not an optimisation: an
|
|
@@ -746,37 +889,108 @@ export class DataServer {
|
|
|
746
889
|
* clients, which never clear their dirty state.
|
|
747
890
|
*/
|
|
748
891
|
subscribeToTextDocumentSaves() {
|
|
749
|
-
this.disposables.push(this.
|
|
892
|
+
this.disposables.push(this.modelService.onModelSaved(event => this.dispatchSaveEvent(event)));
|
|
893
|
+
}
|
|
894
|
+
/** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
|
|
895
|
+
subscribeToDirtyChanges() {
|
|
896
|
+
this.disposables.push(this.modelService.onDirtyChanged(event => this.dispatchDirtyEvent(event)));
|
|
750
897
|
}
|
|
751
898
|
/**
|
|
752
|
-
*
|
|
753
|
-
* {@link
|
|
754
|
-
*
|
|
755
|
-
* hold, so a `false` answer means this close was the last one.
|
|
899
|
+
* Send a dirty flip to the connection, gated on the URI's watchers as
|
|
900
|
+
* {@link dispatchSaveEvent} is: the answer at any one moment travels on
|
|
901
|
+
* every document sent, so a client that watches nothing reads it there.
|
|
756
902
|
*/
|
|
757
|
-
|
|
758
|
-
const
|
|
759
|
-
this.
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
903
|
+
dispatchDirtyEvent(event) {
|
|
904
|
+
const uri = this.canonicalKey(event.uri);
|
|
905
|
+
if (this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
906
|
+
this.clientProxy.onDocumentDirtyChanged({ uri, text: event.text });
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Mark each document the store releases, so {@link dispatchPhaseEvent}
|
|
911
|
+
* broadcasts the build that follows even without a watcher. By default
|
|
912
|
+
* that build reverts the document to its disk content, discarding unsaved
|
|
913
|
+
* in-session edits, and the last close typically also
|
|
914
|
+
* removed the last watcher: without the broadcast, a consumer that only
|
|
915
|
+
* ever fetches via `getModelDocument` keeps showing the discarded state.
|
|
916
|
+
* The broadcast is de-duplicated against the fingerprint while a watcher
|
|
917
|
+
* holds one, so a close whose disk state equals the last emitted state
|
|
918
|
+
* stays silent; with no watcher there is no fingerprint, and every release
|
|
919
|
+
* build is sent. The first build after the release consumes the mark, and
|
|
920
|
+
* goes out as the release unless it is stamped past the version a client
|
|
921
|
+
* opened the document at again: a client's write or an integrity repair
|
|
922
|
+
* that rides it keeps its author.
|
|
923
|
+
*
|
|
924
|
+
* A release, not the close itself: a document whose last client lost its
|
|
925
|
+
* connection is released only once the release grace runs out, or when
|
|
926
|
+
* another client opens it meanwhile, and not at all when a client lost
|
|
927
|
+
* from it opens it again within its own grace.
|
|
928
|
+
*/
|
|
929
|
+
subscribeToModelReleases() {
|
|
930
|
+
this.disposables.push(this.modelService.onModelReleased(event => {
|
|
931
|
+
const uri = this.canonicalKey(event.uri);
|
|
932
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set() };
|
|
933
|
+
record.releaseBroadcastPending = true;
|
|
934
|
+
this.uriWatchRecords.set(uri, record);
|
|
935
|
+
this.tracer.withUri(uri).debug('Release marked: the first build after it is broadcast, watched or not');
|
|
763
936
|
}));
|
|
764
937
|
}
|
|
765
|
-
/**
|
|
938
|
+
/**
|
|
939
|
+
* Fan out a deletion for each removed URI, to EVERY client on the connection
|
|
940
|
+
* rather than only to the ones watching that URI.
|
|
941
|
+
*
|
|
942
|
+
* **Deliberately ungated, where {@link dispatchPhaseEvent} and
|
|
943
|
+
* {@link dispatchSaveEvent} are gated.** Those two carry a built document and
|
|
944
|
+
* fire on every build, so the watcher gate is what keeps bandwidth
|
|
945
|
+
* proportional to what a client asked for. A deletion is neither: it is one
|
|
946
|
+
* URI, it is rare, and it reports the workspace's STRUCTURE rather than a
|
|
947
|
+
* document's content. Gating it forces any consumer that displays the
|
|
948
|
+
* workspace — a model tree, a file decorator — to learn about disappearances
|
|
949
|
+
* from a filesystem watcher instead, which a client hosted in a browser has
|
|
950
|
+
* no way to run: its workspace lives behind the head. A client that does not
|
|
951
|
+
* care filters on the URI, which costs it a comparison.
|
|
952
|
+
*
|
|
953
|
+
* The precedent is the release broadcast (see
|
|
954
|
+
* {@link subscribeToModelReleases}), where the same judgement was already made
|
|
955
|
+
* in the other direction: a transition that matters enough is delivered
|
|
956
|
+
* without a subscription.
|
|
957
|
+
*
|
|
958
|
+
* A deletion is announced before the build that follows it, so this goes
|
|
959
|
+
* out ahead of the `'rebuilt'` events for the dependents whose references
|
|
960
|
+
* the deletion just broke.
|
|
961
|
+
*
|
|
962
|
+
* The URI's fingerprint and release mark are dropped: they describe a
|
|
963
|
+
* document that no longer exists. A kept fingerprint is adopted as the
|
|
964
|
+
* baseline and suppresses the first emit after the file returns with its
|
|
965
|
+
* previous content.
|
|
966
|
+
*
|
|
967
|
+
* The watchers SURVIVE: a recreated file resumes delivering to them with no
|
|
968
|
+
* re-subscription, and a client that answers the deletion by closing
|
|
969
|
+
* releases the watch through `closeModelDocument` anyway. A session that
|
|
970
|
+
* deleted the document has its own released by {@link deleteModelDocument}.
|
|
971
|
+
*/
|
|
972
|
+
dispatchDeleteEvent(event) {
|
|
973
|
+
const uri = this.canonicalKey(event.uri);
|
|
974
|
+
const record = this.uriWatchRecords.get(uri);
|
|
975
|
+
if (record) {
|
|
976
|
+
record.fingerprint = undefined;
|
|
977
|
+
record.fingerprintVersion = undefined;
|
|
978
|
+
record.releaseBroadcastPending = undefined;
|
|
979
|
+
record.sentVersion = undefined;
|
|
980
|
+
this.pruneUriWatchRecord(uri);
|
|
981
|
+
}
|
|
982
|
+
this.clientProxy.onDocumentDeleted({ uri, sourceClientId: event.sourceClientId });
|
|
983
|
+
}
|
|
984
|
+
/** Fan out a save event for the document's URI, gated on the URI's watchers. */
|
|
766
985
|
dispatchSaveEvent(event) {
|
|
767
|
-
// The save event arrives under the CLIENT URI the text store keys by (e.g. a
|
|
768
|
-
// symlink path S); the subscription map and `dispatchPhaseEvent` key by the
|
|
769
|
-
// CANONICAL identity R. Canonicalize before both the gate and the envelope so
|
|
770
|
-
// a save of a symlinked file isn't silently dropped (and the envelope resolves
|
|
771
|
-
// the R-keyed document rather than missing into an empty one).
|
|
772
986
|
const uri = this.canonicalKey(event.document.uri);
|
|
773
|
-
if (!this.
|
|
987
|
+
if (!this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
774
988
|
return;
|
|
775
989
|
}
|
|
776
|
-
const response = this.envelope(UriUtils.toUri(uri));
|
|
990
|
+
const response = this.envelope(UriUtils.toUri(event.document.uri));
|
|
777
991
|
const wireEvent = {
|
|
778
992
|
document: response,
|
|
779
|
-
sourceClientId: event.
|
|
993
|
+
sourceClientId: event.sourceClientId
|
|
780
994
|
};
|
|
781
995
|
this.clientProxy.onDocumentSaved(wireEvent);
|
|
782
996
|
}
|
|
@@ -789,107 +1003,106 @@ export class DataServer {
|
|
|
789
1003
|
* out to multiple local subscribers with an `Emitter<T>` — the
|
|
790
1004
|
* framework deliberately does NOT promise multi-listener semantics.
|
|
791
1005
|
*
|
|
792
|
-
*
|
|
793
|
-
*
|
|
794
|
-
*
|
|
795
|
-
*
|
|
796
|
-
*
|
|
797
|
-
*
|
|
798
|
-
*
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
1006
|
+
* An event for a URI no client watches is NOT sent over the wire, so
|
|
1007
|
+
* bandwidth scales with watched URIs rather than with phase events; a
|
|
1008
|
+
* pending release mark is the exception (see
|
|
1009
|
+
* {@link subscribeToModelReleases}).
|
|
1010
|
+
*
|
|
1011
|
+
* An event for a rebuild with no observable change since the last emit is
|
|
1012
|
+
* suppressed against the URI's fingerprint and the version it was taken at;
|
|
1013
|
+
* a new version with the same fingerprint goes out with the same
|
|
1014
|
+
* `model.hash`, so a watcher still learns the version. Such rebuilds are routine: a
|
|
1015
|
+
* second client attaching to an open document makes
|
|
1016
|
+
* `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
|
|
1017
|
+
* to re-trigger the build, and Langium rebuilds a document when a
|
|
1018
|
+
* dependency changes even if its diagnostics come out the same. Sent at a
|
|
1019
|
+
* version this head has not sent, they reach watchers as `'changed'`, and a
|
|
1020
|
+
* watcher that reads `'changed'` as another client's write and resets its
|
|
1021
|
+
* root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
|
|
1022
|
+
* fingerprint, so the first event after a watch is de-duplicated against
|
|
1023
|
+
* the state the watcher just fetched; it goes with the last watcher, so the
|
|
1024
|
+
* next first watch re-baselines rather than adopting a stale digest. A
|
|
1025
|
+
* digest keeps its memory constant in document size; see
|
|
1026
|
+
* {@link computeDocumentFingerprint} for the inputs.
|
|
1027
|
+
*/
|
|
1028
|
+
dispatchPhaseEvent(event) {
|
|
1029
|
+
const uri = this.canonicalKey(event.document.uri);
|
|
1030
|
+
const record = this.uriWatchRecords.get(uri);
|
|
1031
|
+
const afterRelease = record?.releaseBroadcastPending === true;
|
|
1032
|
+
if (!record || (record.watchers.size === 0 && !afterRelease)) {
|
|
807
1033
|
return;
|
|
808
1034
|
}
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
1035
|
+
if (afterRelease) {
|
|
1036
|
+
// Consumed even when watchers exist — the regular dispatch below
|
|
1037
|
+
// serves them, and the mark's attribution is more precise than the
|
|
1038
|
+
// post-close unknown client the manager's attribution would yield.
|
|
1039
|
+
// With no watcher the record goes now, so the fingerprint written
|
|
1040
|
+
// below lands on a detached record and the next first watch
|
|
1041
|
+
// re-baselines instead of adopting it.
|
|
1042
|
+
record.releaseBroadcastPending = undefined;
|
|
1043
|
+
this.pruneUriWatchRecord(uri);
|
|
1044
|
+
}
|
|
1045
|
+
// The encoder reads the built document, which the event's holds for this
|
|
1046
|
+
// synchronous run.
|
|
1047
|
+
const document = this.modelService.getDocument(event.document.uri);
|
|
1048
|
+
if (!document) {
|
|
816
1049
|
return;
|
|
817
1050
|
}
|
|
818
|
-
const fingerprint = this.computeDocumentFingerprint(document);
|
|
819
|
-
|
|
1051
|
+
const fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
|
|
1052
|
+
const stamped = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
|
|
1053
|
+
if (record.fingerprint === fingerprint && record.fingerprintVersion === stamped) {
|
|
820
1054
|
// A rebuild that produced no observable change since the last emit —
|
|
821
1055
|
// suppressed so RPC subscribers don't see a no-op broadcast. Logged at
|
|
822
1056
|
// debug so a *needed* re-broadcast wrongly suppressed by this dedup
|
|
823
1057
|
// (the failure mode the fingerprint strategy must avoid) is visible.
|
|
824
|
-
this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${
|
|
1058
|
+
this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${stamped}: fingerprint and version unchanged`);
|
|
825
1059
|
return;
|
|
826
1060
|
}
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
1061
|
+
record.fingerprint = fingerprint;
|
|
1062
|
+
record.fingerprintVersion = stamped;
|
|
1063
|
+
// The event's attribution, so this head names the same client as the
|
|
1064
|
+
// in-process heads do for one build, except for a version this head
|
|
1065
|
+
// already sent; see `DataServerUriWatchRecord.sentVersion`.
|
|
1066
|
+
const version = this.modelService.isOpen(event.document.uri) ? document.textDocument.version : undefined;
|
|
1067
|
+
const { reason, sourceClientId } = version !== undefined && record.sentVersion === version
|
|
1068
|
+
? { reason: 'rebuilt', sourceClientId: UNKNOWN_CLIENT_ID }
|
|
1069
|
+
: event;
|
|
1070
|
+
record.sentVersion = version;
|
|
1071
|
+
// The stamp, not the live version: a write after the build's parse moves
|
|
1072
|
+
// only the latter. At the opened version too, which a reopen with the
|
|
1073
|
+
// released text keeps.
|
|
1074
|
+
const openedVersion = afterRelease ? this.modelService.openedVersion(event.document.uri) : undefined;
|
|
1075
|
+
const releaseBuild = afterRelease && (openedVersion === undefined || stamped <= openedVersion);
|
|
1076
|
+
const wireEvent = {
|
|
1077
|
+
document: this.envelope(document.uri, fingerprint),
|
|
1078
|
+
sourceClientId: releaseBuild ? DOCUMENT_RELEASE_CLIENT_ID : sourceClientId,
|
|
1079
|
+
reason
|
|
832
1080
|
};
|
|
1081
|
+
const mark = afterRelease ? `, release mark: opened v${openedVersion ?? '-'}, attributed ${sourceClientId}` : '';
|
|
833
1082
|
this.tracer
|
|
834
1083
|
.withUri(uri)
|
|
835
|
-
.debug(`Emit onDocumentUpdated v${
|
|
836
|
-
this.clientProxy.onDocumentUpdated(
|
|
1084
|
+
.debug(`Emit onDocumentUpdated v${stamped} (reason=${wireEvent.reason}, sourceClientId=${wireEvent.sourceClientId}${mark})`);
|
|
1085
|
+
this.clientProxy.onDocumentUpdated(wireEvent);
|
|
837
1086
|
}
|
|
838
1087
|
/**
|
|
839
|
-
* Fingerprint of the
|
|
840
|
-
* `onDocumentUpdated` emissions
|
|
841
|
-
*
|
|
842
|
-
* {@link
|
|
1088
|
+
* Fingerprint of the snapshot `root` and its encoding `encoded`, used to
|
|
1089
|
+
* de-dup `onDocumentUpdated` emissions and sent as every document's
|
|
1090
|
+
* `model.hash`, so it must not depend on the version or on live state. The
|
|
1091
|
+
* {@link FingerprintStrategy} option selects what is hashed (default
|
|
1092
|
+
* `'transfer-document'` — see the type).
|
|
843
1093
|
*
|
|
844
|
-
*
|
|
845
|
-
*
|
|
846
|
-
*
|
|
847
|
-
* `envelope` share a single encode walk.
|
|
1094
|
+
* {@link TransferEncoder.toTransferDocument} is cached per build, so within
|
|
1095
|
+
* one phase event the fingerprint and the subsequently-emitted `envelope`
|
|
1096
|
+
* share a single encode walk.
|
|
848
1097
|
*
|
|
849
1098
|
* Wrapped in {@link Tracer.time} against {@link FINGERPRINT_LOG_AFTER_MS}.
|
|
850
1099
|
*/
|
|
851
|
-
computeDocumentFingerprint(
|
|
852
|
-
return this.tracer
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
return extra.length === 0 ? base : fingerprintHash([base, FINGERPRINT_SEPARATOR, ...extra.map(value => JSON.stringify(value))]);
|
|
858
|
-
}, 'debug', { logAfterMs: FINGERPRINT_LOG_AFTER_MS });
|
|
859
|
-
}
|
|
860
|
-
/**
|
|
861
|
-
* Extra inputs folded into {@link computeDocumentFingerprint} alongside the
|
|
862
|
-
* chosen {@link FingerprintStrategy}. Default: none. Override to contribute a
|
|
863
|
-
* signal that lives outside the document's text / root / diagnostics — each
|
|
864
|
-
* entry need only be stable across equivalent emissions and
|
|
865
|
-
* JSON-serialisable.
|
|
866
|
-
*/
|
|
867
|
-
additionalFingerprintInputs(_document) {
|
|
868
|
-
return [];
|
|
869
|
-
}
|
|
870
|
-
/**
|
|
871
|
-
* Discriminate the reason for a phase-event-driven update notification.
|
|
872
|
-
* Uses the most recent `DocumentBuilder.onUpdate` snapshot:
|
|
873
|
-
* - URI in the `deleted` list → `'deleted'`
|
|
874
|
-
* - URI in the `changed` list → `'changed'` (the URI was passed to
|
|
875
|
-
* `documentBuilder.update(changed, deleted)`, which spans `didChange`
|
|
876
|
-
* text-document events and programmatic `update([uri], [])` calls).
|
|
877
|
-
* - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
|
|
878
|
-
* because something it depends on changed; its own text wasn't flagged).
|
|
879
|
-
*
|
|
880
|
-
* `'saved'` is NOT emitted from this code path — saves take the dedicated
|
|
881
|
-
* `DataClientProtocol.onDocumentSaved` channel; adopters that want a
|
|
882
|
-
* unified update stream synthesise `'saved'` in their bridge layer.
|
|
883
|
-
*/
|
|
884
|
-
resolveUpdateReason(uri) {
|
|
885
|
-
const last = this.lastBuildUpdate;
|
|
886
|
-
if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
|
|
887
|
-
return 'deleted';
|
|
888
|
-
}
|
|
889
|
-
if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
|
|
890
|
-
return 'changed';
|
|
891
|
-
}
|
|
892
|
-
return 'rebuilt';
|
|
1100
|
+
computeDocumentFingerprint(root, encoded) {
|
|
1101
|
+
return this.tracer
|
|
1102
|
+
.withUri(encoded.uri)
|
|
1103
|
+
.time('Compute fingerprint', () => this.options.fingerprintStrategy === 'text-diagnostics'
|
|
1104
|
+
? textDiagnosticsFingerprint(this.services.workspace.ModelLedger.textOf(root), encoded.model)
|
|
1105
|
+
: transferDocumentFingerprint(encoded.model), 'debug', { logAfterMs: FINGERPRINT_LOG_AFTER_MS });
|
|
893
1106
|
}
|
|
894
1107
|
/**
|
|
895
1108
|
* Subscribe to the project tier's change channel and re-fan registry
|
|
@@ -913,38 +1126,38 @@ export class DataServer {
|
|
|
913
1126
|
/**
|
|
914
1127
|
* Fan one internal {@link ProjectChangeEvent} out to per-project wire
|
|
915
1128
|
* notifications. Each `removed` entry pairs the id with the pre-removal
|
|
916
|
-
* snapshot needed for the `'removed'` wire payload.
|
|
1129
|
+
* snapshot needed for the `'removed'` wire payload. A project whose
|
|
1130
|
+
* {@link encodeProject} throws is logged and skipped, so the rest of the
|
|
1131
|
+
* batch still reaches the client.
|
|
917
1132
|
*/
|
|
918
1133
|
dispatchProjectChangeEvent(event) {
|
|
1134
|
+
const send = (project, reason) => {
|
|
1135
|
+
let encoded;
|
|
1136
|
+
try {
|
|
1137
|
+
encoded = this.encodeProject(project);
|
|
1138
|
+
}
|
|
1139
|
+
catch (error) {
|
|
1140
|
+
this.tracer.error(`Project ${project.id} not sent as ${reason}: encodeProject threw: ${describeErrorWithStack(error)}`);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
this.clientProxy.onProjectsChanged({ project: encoded, reason });
|
|
1144
|
+
};
|
|
919
1145
|
for (const id of event.added) {
|
|
920
1146
|
const project = this.services.workspace.ProjectManager.getProjectById(id);
|
|
921
1147
|
if (project) {
|
|
922
|
-
|
|
1148
|
+
send(project, 'added');
|
|
923
1149
|
}
|
|
924
1150
|
}
|
|
925
1151
|
for (const id of event.updated) {
|
|
926
1152
|
const project = this.services.workspace.ProjectManager.getProjectById(id);
|
|
927
1153
|
if (project) {
|
|
928
|
-
|
|
1154
|
+
send(project, 'updated');
|
|
929
1155
|
}
|
|
930
1156
|
}
|
|
931
1157
|
for (const entry of event.removed) {
|
|
932
|
-
|
|
1158
|
+
send(entry.snapshot, 'removed');
|
|
933
1159
|
}
|
|
934
1160
|
}
|
|
935
|
-
/**
|
|
936
|
-
* Resolve the wire-level `sourceClientId` for `document`'s events — the client
|
|
937
|
-
* that authored its current version, from the version-author history on
|
|
938
|
-
* `HydraniumTextDocuments`. The protocol-level counterpart of the internal
|
|
939
|
-
* `AstDocumentManager.getAuthor`: a framework-internal rebuild has no author,
|
|
940
|
-
* so this surfaces the {@link UNKNOWN_CLIENT_ID} presentation default. Adopters
|
|
941
|
-
* that rebuild through non-text-document channels override to derive a
|
|
942
|
-
* source id of their own.
|
|
943
|
-
*/
|
|
944
|
-
resolveSourceClientId(document) {
|
|
945
|
-
const author = this.services.workspace.TextDocuments.getAuthor(document.textDocument.uri, document.textDocument.version);
|
|
946
|
-
return author ?? UNKNOWN_CLIENT_ID;
|
|
947
|
-
}
|
|
948
1161
|
// --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
|
|
949
1162
|
// Computed in THIS process: the data-server child holds the model store, so
|
|
950
1163
|
// these snapshots reflect the heap that actually carries the workspace
|
|
@@ -1002,7 +1215,7 @@ export class DataServer {
|
|
|
1002
1215
|
const builtIn = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS];
|
|
1003
1216
|
const overlap = additionalMethods.filter(name => builtIn.includes(name));
|
|
1004
1217
|
if (overlap.length > 0) {
|
|
1005
|
-
throw new Error(`
|
|
1218
|
+
throw new Error(`DataServerOptions.additionalMethods overlaps with built-in data-server methods: ${overlap.join(', ')}. ` +
|
|
1006
1219
|
'Adopter protocols must not redeclare framework method names; rename the adopter method or remove it from additionalMethods.');
|
|
1007
1220
|
}
|
|
1008
1221
|
return {
|
|
@@ -1011,7 +1224,8 @@ export class DataServer {
|
|
|
1011
1224
|
methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
|
|
1012
1225
|
additionalMethods,
|
|
1013
1226
|
excludedMethods: partial.excludedMethods ?? [],
|
|
1014
|
-
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
|
|
1227
|
+
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
|
|
1228
|
+
referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
|
|
1015
1229
|
};
|
|
1016
1230
|
}
|
|
1017
1231
|
}
|