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