@hydranium/data-server 1.0.0-next.31 → 1.0.0-next.315
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 +57 -73
- package/lib/browser/index.d.ts +10 -0
- package/lib/browser/index.d.ts.map +1 -0
- package/lib/browser/index.js +15 -0
- package/lib/browser/index.js.map +1 -0
- package/lib/browser/start-data-server-in-worker.d.ts +23 -0
- package/lib/browser/start-data-server-in-worker.d.ts.map +1 -0
- package/lib/browser/start-data-server-in-worker.js +29 -0
- package/lib/browser/start-data-server-in-worker.js.map +1 -0
- package/lib/data-server.d.ts +444 -290
- package/lib/data-server.d.ts.map +1 -1
- package/lib/data-server.js +752 -506
- 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 +35 -43
- package/src/browser/index.ts +15 -0
- package/src/browser/start-data-server-in-worker.ts +35 -0
- package/src/data-server.ts +908 -545
- 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 { asModelVersion, 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,40 @@ 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
|
-
* `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
|
|
164
|
-
* URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
|
|
165
|
-
* the LSP side, so reason fidelity stays consistent between heads.
|
|
158
|
+
* The position of the last update or deletion event sent, which each
|
|
159
|
+
* such event carries, and a watch's answer carries as of the moment it
|
|
160
|
+
* took whether its document exists: an event past it was sent after.
|
|
166
161
|
*/
|
|
167
|
-
|
|
162
|
+
eventSequence = 0;
|
|
168
163
|
/**
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
*
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
|
|
182
|
-
|
|
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();
|
|
164
|
+
* The live client sessions this connection registered, by client id. A
|
|
165
|
+
* document request carrying one of these ids acts as that session; one
|
|
166
|
+
* carrying any other id fails. A session leaves once it ends, so a
|
|
167
|
+
* connection that registers many over its life does not accumulate them.
|
|
168
|
+
*/
|
|
169
|
+
clientSessions = new Map();
|
|
170
|
+
/**
|
|
171
|
+
* Typed client proxy — sends `data-server/on*` notifications back over the same wire.
|
|
172
|
+
* The proxy sends any `on[A-Z]*` name other than `onDidOpenConnection` and
|
|
173
|
+
* `onDidCloseConnection`, for which it returns its own events, so a subclass
|
|
174
|
+
* with notifications of its own narrows only the type:
|
|
175
|
+
* `declare protected readonly clientProxy: TheirClient`.
|
|
176
|
+
*/
|
|
177
|
+
clientProxy;
|
|
178
|
+
disposables = new DisposableCollection();
|
|
218
179
|
tracer;
|
|
219
180
|
/** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
|
|
220
181
|
activeProfile;
|
|
@@ -226,11 +187,8 @@ export class DataServer {
|
|
|
226
187
|
encoder;
|
|
227
188
|
/**
|
|
228
189
|
* 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`.
|
|
190
|
+
* Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
|
|
191
|
+
* {@link encoder} converts one into the other on the way out.
|
|
234
192
|
*/
|
|
235
193
|
modelService;
|
|
236
194
|
constructor(connection, services, options = {}) {
|
|
@@ -239,8 +197,7 @@ export class DataServer {
|
|
|
239
197
|
this.options = this.resolveOptions(options);
|
|
240
198
|
this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
|
|
241
199
|
// 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.
|
|
200
|
+
// `services.model.ModelService` with their own subclasses.
|
|
244
201
|
const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
|
|
245
202
|
if (!encoder || !modelService) {
|
|
246
203
|
throw new Error('DataServer requires `services.model.TransferEncoder` and `services.model.ModelService` to be bound. ' +
|
|
@@ -263,35 +220,42 @@ export class DataServer {
|
|
|
263
220
|
methodNamespace: this.options.methodNamespace,
|
|
264
221
|
localTarget: this,
|
|
265
222
|
localMethods: registeredMethods,
|
|
266
|
-
latency: this.latency
|
|
223
|
+
latency: this.latency,
|
|
224
|
+
// Bound at the chokepoint rather than per handler, so an adopter's
|
|
225
|
+
// `additionalMethods` are rendered on the same terms as the
|
|
226
|
+
// framework's own rejections.
|
|
227
|
+
renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
|
|
267
228
|
});
|
|
268
|
-
this.disposables.push(this.
|
|
269
|
-
|
|
270
|
-
}));
|
|
271
|
-
this.subscribeToDocumentBuilder();
|
|
229
|
+
this.disposables.push(this.modelService.onModelDeleted(event => this.dispatchDeleteEvent(event)));
|
|
230
|
+
this.subscribeToModelUpdates();
|
|
272
231
|
this.subscribeToTextDocumentSaves();
|
|
273
|
-
this.
|
|
232
|
+
this.subscribeToDirtyChanges();
|
|
233
|
+
this.subscribeToModelReleases();
|
|
274
234
|
this.subscribeToProjectManager();
|
|
275
235
|
// Self-register teardown so an adopter that keeps no reference to the
|
|
276
236
|
// server still releases per-connection state, with no lifecycle hook of
|
|
277
|
-
// its own.
|
|
278
|
-
|
|
237
|
+
// its own. The client did not close anything itself, so its sessions end
|
|
238
|
+
// as lost and each document it was the last to have open waits out the
|
|
239
|
+
// store's release grace. See `dispose`.
|
|
240
|
+
this.disposables.push(connection.onClose(() => this.dispose('lost')));
|
|
279
241
|
}
|
|
280
242
|
/**
|
|
281
243
|
* 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.
|
|
244
|
+
* handlers and every listener — and clear {@link uriWatchRecords}, so a
|
|
245
|
+
* long-lived shared services bundle does not retain per-connection memory
|
|
246
|
+
* after the connection closes. Also ends every session this connection registered, which closes
|
|
247
|
+
* every document it has open: the SHARED store's state rather than this
|
|
248
|
+
* server's, which outlives the connection unless released here.
|
|
288
249
|
*
|
|
289
|
-
* Idempotent: subsequent calls are no-ops.
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
*
|
|
250
|
+
* Idempotent: subsequent calls are no-ops. Runs by itself when the
|
|
251
|
+
* connection closes, so adopters who don't hold a reference still get
|
|
252
|
+
* per-connection cleanup; adopters that DO hold a reference may call
|
|
253
|
+
* `dispose()` directly for early teardown. The sessions end with `cause`:
|
|
254
|
+
* `'closed'` releases every document whose last open they close at once,
|
|
255
|
+
* and `'lost'`, the connection's own close, lets each wait out the release
|
|
256
|
+
* grace.
|
|
293
257
|
*/
|
|
294
|
-
dispose() {
|
|
258
|
+
dispose(cause = 'closed') {
|
|
295
259
|
this.disposed = true;
|
|
296
260
|
// Release an in-flight interactive capture so the process-wide inspector
|
|
297
261
|
// singleton is not left active after the connection closes.
|
|
@@ -300,98 +264,135 @@ export class DataServer {
|
|
|
300
264
|
this.activeProfile = undefined;
|
|
301
265
|
void capture.stop({}).catch(() => undefined);
|
|
302
266
|
}
|
|
303
|
-
// AFTER `disposables.dispose()`, deliberately:
|
|
304
|
-
//
|
|
305
|
-
//
|
|
267
|
+
// AFTER `disposables.dispose()`, deliberately: ending a session releases
|
|
268
|
+
// each document it was the last to hold, and this server's own
|
|
269
|
+
// `onModelReleased` subscription would otherwise mark a release broadcast
|
|
270
|
+
// for a connection that is already gone.
|
|
306
271
|
this.disposables.dispose();
|
|
307
|
-
this.
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
this.
|
|
272
|
+
for (const [clientId, session] of this.clientSessions) {
|
|
273
|
+
this.endSession(clientId, session, cause);
|
|
274
|
+
}
|
|
275
|
+
this.uriWatchRecords.clear();
|
|
276
|
+
this.watchKeys.clear();
|
|
311
277
|
}
|
|
312
278
|
// ============================================================
|
|
313
|
-
// DataServerProtocol implementation
|
|
279
|
+
// DataServerProtocol implementation
|
|
314
280
|
// ============================================================
|
|
315
281
|
//
|
|
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) };
|
|
282
|
+
// Reads go to `ModelService`; a request that opens or writes a document
|
|
283
|
+
// goes to the session this connection registered under its `clientId`.
|
|
284
|
+
// Each answer is encoded on the wire boundary via
|
|
285
|
+
// `encoder.astDocumentToTransferDocument`. To change how documents are
|
|
286
|
+
// read, override on the ModelService subclass; to change how they are
|
|
287
|
+
// written, on the session class the bound `ClientSessionFactory` builds.
|
|
288
|
+
async createSession(args) {
|
|
289
|
+
// After teardown nothing would ever end a session registered now, and its
|
|
290
|
+
// id would stay taken for the life of the process.
|
|
291
|
+
if (this.disposed) {
|
|
292
|
+
throw new SessionClosedError(args.clientId);
|
|
293
|
+
}
|
|
294
|
+
const session = this.modelService.createSession(args.label, args.clientId, { resumeToken: args.resumeToken });
|
|
295
|
+
this.clientSessions.set(args.clientId, session);
|
|
296
|
+
// A session also ends without closeSession, as when a client registers
|
|
297
|
+
// again on another connection, and its watches and entry here would
|
|
298
|
+
// otherwise outlive it.
|
|
299
|
+
session.onDidDispose(cause => {
|
|
300
|
+
// A session class may report its end late, once a replacement holds
|
|
301
|
+
// the id here; the replacement's entry and watches stay.
|
|
302
|
+
if (this.clientSessions.get(args.clientId) !== session) {
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
this.dropWatches(args.clientId);
|
|
306
|
+
this.clientSessions.delete(args.clientId);
|
|
307
|
+
this.tracer.debug(`Forget session ${args.clientId}: it ended as ${cause}`);
|
|
308
|
+
});
|
|
348
309
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
310
|
+
/** End a session this connection registered. */
|
|
311
|
+
async closeSession(args) {
|
|
312
|
+
const session = this.clientSessions.get(args.clientId);
|
|
313
|
+
if (session) {
|
|
314
|
+
this.endSession(args.clientId, session);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
/** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
|
|
318
|
+
endSession(clientId, session, cause = 'closed') {
|
|
319
|
+
this.dropWatches(clientId);
|
|
320
|
+
session.dispose(cause);
|
|
321
|
+
}
|
|
322
|
+
dropWatches(clientId) {
|
|
323
|
+
this.watchKeys.delete(clientId);
|
|
324
|
+
for (const [uri, record] of this.uriWatchRecords) {
|
|
325
|
+
if (record.watchers.delete(clientId)) {
|
|
326
|
+
this.pruneUriWatchRecord(uri);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
async createModelDocument(args) {
|
|
331
|
+
const session = this.requireSession(args.clientId);
|
|
332
|
+
const version = await session.create(args.uri, args.text);
|
|
333
|
+
const snapshot = await this.openedSnapshot(args.uri, () => session.close(args.uri));
|
|
334
|
+
return { ...snapshot, created: { version: asModelVersion(version) } };
|
|
335
|
+
}
|
|
336
|
+
async updateModelDocuments(args) {
|
|
337
|
+
const astDocuments = await this.requireSession(args.clientId).updateAll({
|
|
338
|
+
updates: args.updates.map(update => this.toSessionWrite(update))
|
|
339
|
+
});
|
|
340
|
+
return astDocuments.map(astDocument => this.encodeDocument(astDocument));
|
|
356
341
|
}
|
|
357
342
|
/**
|
|
358
|
-
*
|
|
359
|
-
*
|
|
343
|
+
* The session write a wire write request carries. Only the fields a session
|
|
344
|
+
* takes: a field an adopter adds to a request reaches the session only
|
|
345
|
+
* through an override of this.
|
|
360
346
|
*/
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
347
|
+
toSessionWrite(request) {
|
|
348
|
+
return { uri: request.uri, model: request.model, baseVersion: request.baseVersion };
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* The session this connection registered under `clientId`, which every
|
|
352
|
+
* document request acts as. An id that is not one fails with the
|
|
353
|
+
* closed-session code: opening or writing under it would leave an open that
|
|
354
|
+
* no session end ever closes.
|
|
355
|
+
*/
|
|
356
|
+
requireSession(clientId) {
|
|
357
|
+
const session = this.clientSessions.get(clientId);
|
|
358
|
+
if (!session) {
|
|
359
|
+
throw new SessionClosedError(clientId, 'The client session is not registered on this connection.');
|
|
369
360
|
}
|
|
361
|
+
return session;
|
|
362
|
+
}
|
|
363
|
+
async openModelDocument(args) {
|
|
364
|
+
const session = this.requireSession(args.clientId);
|
|
365
|
+
const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
|
|
366
|
+
await session.open(args.uri, args.options);
|
|
367
|
+
// A repeat open keeps the earlier one, which is still in use.
|
|
368
|
+
return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
|
|
370
369
|
}
|
|
371
370
|
/**
|
|
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
|
-
}
|
|
371
|
+
* The snapshot a session's open or create answers with. When the read
|
|
372
|
+
* fails, `rollback` undoes the open this call made before the failure is
|
|
373
|
+
* rethrown: the caller sees no open, so nothing on its side would ever close
|
|
374
|
+
* it.
|
|
375
|
+
*/
|
|
376
|
+
async openedSnapshot(uri, rollback) {
|
|
377
|
+
try {
|
|
378
|
+
return await this.getModelDocument({ uri });
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
// The open's failure is the one the caller needs, not the cleanup's.
|
|
382
|
+
await rollback?.().catch(() => undefined);
|
|
383
|
+
throw error;
|
|
393
384
|
}
|
|
394
385
|
}
|
|
386
|
+
async closeModelDocument(args) {
|
|
387
|
+
// Through the handle, so a close under an ended session fails as that
|
|
388
|
+
// session's calls do, and a session class's own close is honoured.
|
|
389
|
+
const session = this.requireSession(args.clientId);
|
|
390
|
+
// Closing also releases the watch for (uri, clientId) — a forgotten
|
|
391
|
+
// unwatch would otherwise leak phase-event dispatch until the connection
|
|
392
|
+
// closes. Idempotent: a close without a prior watch is a no-op.
|
|
393
|
+
await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
|
|
394
|
+
await session.close(args.uri);
|
|
395
|
+
}
|
|
395
396
|
async getModelDocument(args) {
|
|
396
397
|
// Smart dispatch: a warm document (already in LangiumDocuments) is
|
|
397
398
|
// returned at its settle phase without a redundant build; a cold URI
|
|
@@ -404,72 +405,140 @@ export class DataServer {
|
|
|
404
405
|
// unsubscribed caller that needs diagnostics inline passes
|
|
405
406
|
// `includeDiagnostics: true` to settle at `Validated` instead.
|
|
406
407
|
const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
|
|
407
|
-
|
|
408
|
-
|
|
408
|
+
try {
|
|
409
|
+
return this.encodeDocument(await this.modelService.ensureDocumentState(args.uri, state));
|
|
410
|
+
}
|
|
411
|
+
catch (error) {
|
|
412
|
+
// The protocol answers a read of a URI with no document with an
|
|
413
|
+
// envelope that has no model.
|
|
414
|
+
if (this.isMissingDocument(error, args.uri)) {
|
|
415
|
+
return this.envelope(UriUtils.toUri(args.uri));
|
|
416
|
+
}
|
|
417
|
+
throw error;
|
|
418
|
+
}
|
|
409
419
|
}
|
|
410
420
|
async updateModelDocument(args) {
|
|
411
|
-
const astDocument = await this.
|
|
412
|
-
return this.
|
|
421
|
+
const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
|
|
422
|
+
return this.encodeDocument(astDocument);
|
|
413
423
|
}
|
|
414
424
|
async saveModelDocument(args) {
|
|
415
|
-
const astDocument = await this.
|
|
416
|
-
|
|
425
|
+
const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
|
|
426
|
+
await this.modelService.settleLanguageClient(args.uri);
|
|
427
|
+
return { ...this.encodeDocument(astDocument), persisted: astDocument.persisted };
|
|
428
|
+
}
|
|
429
|
+
async persistModelDocument(args) {
|
|
430
|
+
const version = await this.requireSession(args.clientId).persist({ uri: args.uri, baseVersion: args.baseVersion });
|
|
431
|
+
await this.modelService.settleLanguageClient(args.uri);
|
|
432
|
+
const astDocument = await this.modelService.ensureDocumentState(args.uri, this.services.workspace.DocumentBuilder.finalBuildState());
|
|
433
|
+
return { ...this.encodeDocument(astDocument), persisted: { version } };
|
|
417
434
|
}
|
|
418
435
|
/**
|
|
419
|
-
*
|
|
420
|
-
*
|
|
421
|
-
*
|
|
422
|
-
*
|
|
423
|
-
|
|
436
|
+
* Delete the document through the session, then release the session's
|
|
437
|
+
* watch of it, as {@link closeModelDocument} does. Released only after the
|
|
438
|
+
* delete: one that fails leaves the session its open and its watch. Other
|
|
439
|
+
* sessions' watches survive, as for any deletion.
|
|
440
|
+
*/
|
|
441
|
+
async deleteModelDocument(args) {
|
|
442
|
+
const session = this.requireSession(args.clientId);
|
|
443
|
+
// Keyed before the delete: once the file is gone, a symlink to it no
|
|
444
|
+
// longer resolves to the key the watch is under.
|
|
445
|
+
const uri = this.canonicalKey(args.uri);
|
|
446
|
+
await session.delete({ uri: args.uri, baseVersion: args.baseVersion });
|
|
447
|
+
await this.unwatchModelDocument({ uri, clientId: args.clientId });
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Record a watch for `(uri, clientId)` in {@link uriWatchRecords}.
|
|
451
|
+
* Subsequent phase events on `uri` fan out to the wired
|
|
452
|
+
* `clientProxy.onDocumentUpdated`. The bidirectional pattern means the
|
|
453
|
+
* event channel is the client notification surface, not a returned
|
|
454
|
+
* handle.
|
|
455
|
+
*
|
|
456
|
+
* Also baselines the URI's emission fingerprint (see
|
|
457
|
+
* {@link dispatchPhaseEvent}) to the document's current state when the
|
|
458
|
+
* first watcher for the URI registers. This guarantees that any phase event firing immediately after
|
|
459
|
+
* the watch with no observable change is suppressed — watchers obtain
|
|
460
|
+
* initial state via `getModelDocument` (or {@link openModelDocument}) and
|
|
461
|
+
* do not need a redundant phase notification for that same state.
|
|
424
462
|
*
|
|
425
|
-
*
|
|
426
|
-
*
|
|
427
|
-
*
|
|
428
|
-
* phase event firing immediately after the watch with no observable
|
|
429
|
-
* change is suppressed — watchers obtain initial state via
|
|
430
|
-
* `getModelDocument` (or {@link openModelDocument}) and do not need a
|
|
431
|
-
* redundant phase notification for that same state.
|
|
463
|
+
* Answers once the document is loaded as a read loads it, with the key
|
|
464
|
+
* events name it by and whether a document exists, taken after the watch
|
|
465
|
+
* is in place and the load, so an event sent while it loads is older.
|
|
432
466
|
*/
|
|
433
467
|
async watchModelDocument(args) {
|
|
434
468
|
const uri = this.canonicalKey(args.uri);
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
469
|
+
const keys = this.watchKeys.get(args.clientId) ?? new Map();
|
|
470
|
+
this.watchKeys.set(args.clientId, keys.set(args.uri, uri));
|
|
471
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set() };
|
|
472
|
+
this.uriWatchRecords.set(uri, record);
|
|
473
|
+
record.watchers.add(args.clientId);
|
|
474
|
+
if (record.fingerprint === undefined) {
|
|
475
|
+
const document = this.modelService.getDocument(args.uri);
|
|
476
|
+
if (document && !this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
|
|
477
|
+
record.fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
|
|
478
|
+
record.fingerprintVersion = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
|
|
445
479
|
}
|
|
446
480
|
}
|
|
481
|
+
// As for a read, only a missing document counts as none. A file briefly
|
|
482
|
+
// unreadable leaves the builder's placeholder, and is there all the same.
|
|
483
|
+
// Whether it exists, the text held and the position of the last event
|
|
484
|
+
// sent are read in one synchronous run, so an event sent after is past
|
|
485
|
+
// the position and moves the text past the state answered.
|
|
486
|
+
const answer = (exists) => {
|
|
487
|
+
const text = exists ? this.serverTextState(args.uri) : undefined;
|
|
488
|
+
return { uri, exists, sequence: this.eventSequence, ...(text ? { text } : {}) };
|
|
489
|
+
};
|
|
490
|
+
return this.modelService.ensureDocumentState(args.uri).then(() => answer(this.modelService.getDocument(args.uri) !== undefined), (error) => answer(!this.isMissingDocument(error, args.uri)));
|
|
447
491
|
}
|
|
448
492
|
/**
|
|
449
493
|
* Remove a watch for `(uri, clientId)` previously created by
|
|
450
494
|
* {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
|
|
451
|
-
* Dispatch for `uri` stops once no watchers remain,
|
|
452
|
-
*
|
|
453
|
-
*
|
|
454
|
-
*
|
|
495
|
+
* Dispatch for `uri` stops once no watchers remain, and the emission
|
|
496
|
+
* fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
|
|
497
|
+
*
|
|
498
|
+
* A URI the client watched is unwatched under the key it resolved to then,
|
|
499
|
+
* from {@link watchKeys}, which still holds once its file is gone.
|
|
455
500
|
*/
|
|
456
501
|
async unwatchModelDocument(args) {
|
|
457
|
-
const
|
|
458
|
-
const
|
|
459
|
-
|
|
502
|
+
const keys = this.watchKeys.get(args.clientId);
|
|
503
|
+
const uri = keys?.get(args.uri) ?? this.canonicalKey(args.uri);
|
|
504
|
+
// Every spelling the client watched it under was this one watch.
|
|
505
|
+
keys?.forEach((key, spelling) => {
|
|
506
|
+
if (key === uri) {
|
|
507
|
+
keys.delete(spelling);
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
if (keys?.size === 0) {
|
|
511
|
+
this.watchKeys.delete(args.clientId);
|
|
512
|
+
}
|
|
513
|
+
if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
|
|
514
|
+
this.pruneUriWatchRecord(uri);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Drop what `uri` no longer needs: the
|
|
519
|
+
* {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
|
|
520
|
+
* and the whole record once it holds no
|
|
521
|
+
* {@link DataServerUriWatchRecord.releaseBroadcastPending} mark either.
|
|
522
|
+
* Every path that removes a watcher or consumes a mark ends here.
|
|
523
|
+
*/
|
|
524
|
+
pruneUriWatchRecord(uri) {
|
|
525
|
+
const record = this.uriWatchRecords.get(uri);
|
|
526
|
+
if (!record || record.watchers.size > 0) {
|
|
460
527
|
return;
|
|
461
528
|
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
529
|
+
if (record.releaseBroadcastPending) {
|
|
530
|
+
record.fingerprint = undefined;
|
|
531
|
+
record.fingerprintVersion = undefined;
|
|
532
|
+
}
|
|
533
|
+
else {
|
|
534
|
+
this.uriWatchRecords.delete(uri);
|
|
466
535
|
}
|
|
467
536
|
}
|
|
468
537
|
/**
|
|
469
|
-
* Canonicalise a URI string for use as a
|
|
470
|
-
*
|
|
471
|
-
*
|
|
472
|
-
*
|
|
538
|
+
* Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
|
|
539
|
+
* shared `DocumentUriPolicy`. Callers may send non-canonical URIs
|
|
540
|
+
* (drive-letter casing, percent-encoding differences, or a symlink path)
|
|
541
|
+
* over the wire; the dispatch side keys by
|
|
473
542
|
* `document.uri.toString()` from `LangiumDocuments`, so writer keys must
|
|
474
543
|
* canonicalise to the same form or events silently fail to deliver.
|
|
475
544
|
* Routing through the seam (rather than a bare `UriUtils.normalize`)
|
|
@@ -479,24 +548,22 @@ export class DataServer {
|
|
|
479
548
|
* LSP head resolves.
|
|
480
549
|
*
|
|
481
550
|
* Adopters can still override for head-specific URI policy by subclassing.
|
|
551
|
+
* The result keys watches only; a document is looked up by its own URI.
|
|
482
552
|
*/
|
|
483
553
|
canonicalKey(uri) {
|
|
484
554
|
return this.services.workspace.DocumentUriPolicy.canonicalUri(uri);
|
|
485
555
|
}
|
|
486
556
|
async getProjects() {
|
|
487
|
-
// Pass-through: `ProjectManager<TProject>` already produces `TProject`
|
|
488
|
-
// (the shared services are parameterised over the same generic).
|
|
489
557
|
// The framework reads `id` for registry identity and `dependencies`
|
|
490
558
|
// for the visibility closure; every other field rides on the
|
|
491
559
|
// JSON-RPC envelope as adopter-defined wire metadata.
|
|
492
|
-
return this.services.workspace.ProjectManager.getProjects();
|
|
560
|
+
return this.services.workspace.ProjectManager.getProjects().map(project => this.encodeProject(project));
|
|
493
561
|
}
|
|
494
562
|
async getProjectForUri(args) {
|
|
495
|
-
//
|
|
496
|
-
//
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
return this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
|
|
563
|
+
// Membership logic belongs to the adopter's `ProjectManager`; the
|
|
564
|
+
// data-server forwards the URI without interpretation.
|
|
565
|
+
const project = this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
|
|
566
|
+
return project && this.encodeProject(project);
|
|
500
567
|
}
|
|
501
568
|
/**
|
|
502
569
|
* Resolve once the data-server is ready to serve requests. Delegates
|
|
@@ -513,26 +580,56 @@ export class DataServer {
|
|
|
513
580
|
// Resolve the language's reference services from each request's source
|
|
514
581
|
// (see resolveReferenceServices) and delegate.
|
|
515
582
|
// ============================================================
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
583
|
+
/**
|
|
584
|
+
* Settle the build before a reference question is answered from the index.
|
|
585
|
+
*
|
|
586
|
+
* A query issued right after a model update otherwise races the rebuild and
|
|
587
|
+
* reads an index missing the symbols it asks about. The cost is not confined
|
|
588
|
+
* to this call: a scope built inside that window is cached, and the build's
|
|
589
|
+
* remaining documents link against it.
|
|
590
|
+
*
|
|
591
|
+
* Waits the source document specifically, but ONLY when one is loaded at
|
|
592
|
+
* that URI: a synthetic source can address a URI with no document (a
|
|
593
|
+
* directory URI, typically), where a per-URI `waitUntil` throws "No document
|
|
594
|
+
* found". Falls back to a global settle, matching the id-based
|
|
595
|
+
* `ElementSource` path.
|
|
596
|
+
*
|
|
597
|
+
* Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
598
|
+
*/
|
|
599
|
+
async awaitReferencesLinked(source) {
|
|
600
|
+
const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
|
|
525
601
|
const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
|
|
526
|
-
|
|
602
|
+
const stopwatch = this.services.Clock.stopwatch();
|
|
603
|
+
const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
|
|
604
|
+
if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
const elapsedMs = Math.round(stopwatch.elapsedMs);
|
|
608
|
+
// A per-URI wait resolves off a document-phase notification, so a
|
|
609
|
+
// missed one strands a wait on a document that HAS reached the
|
|
610
|
+
// phase. Re-read before failing; the workspace-wide wait has no
|
|
611
|
+
// equivalent reading and can only reject.
|
|
612
|
+
const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
|
|
613
|
+
if (waitUri && document && document.state >= DocumentState.Linked) {
|
|
614
|
+
this.tracer
|
|
615
|
+
.withUri(waitUri.toString())
|
|
616
|
+
.warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
throw referenceSettleTimeoutError(elapsedMs);
|
|
620
|
+
}
|
|
621
|
+
async findReferenceCandidates(ctx) {
|
|
622
|
+
await this.awaitReferencesLinked(ctx.source);
|
|
527
623
|
return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
|
|
528
624
|
}
|
|
529
625
|
async resolveReference(ref) {
|
|
626
|
+
await this.awaitReferencesLinked(ref.source);
|
|
530
627
|
const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
|
|
531
628
|
if (!resolved) {
|
|
532
629
|
return undefined;
|
|
533
630
|
}
|
|
534
|
-
|
|
535
|
-
return { ...resolved.candidate, element };
|
|
631
|
+
// `TElement` is the caller's claim about the target's type; nothing checks it.
|
|
632
|
+
return { ...resolved.candidate, element: this.encoder.toTransfer(resolved.node) };
|
|
536
633
|
}
|
|
537
634
|
async findNextName(args) {
|
|
538
635
|
const uri = UriUtils.toUri(args.uri);
|
|
@@ -541,15 +638,32 @@ export class DataServer {
|
|
|
541
638
|
// synthetic source — and the create-element flow driving this method is
|
|
542
639
|
// the one that produces directory URIs, on which a bare
|
|
543
640
|
// `getServices(uri)` throws while `findReferenceCandidates` succeeds.
|
|
544
|
-
const
|
|
641
|
+
const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
|
|
642
|
+
// Mid-rebuild the names of documents not yet re-indexed are absent from
|
|
643
|
+
// the taken set, and the caller PERSISTS what it is handed. Nothing
|
|
644
|
+
// reserves the answer either, so a name is free of the collisions the
|
|
645
|
+
// index knows about and of nothing else — two callers racing get the same
|
|
646
|
+
// proposal, which only uniqueness at the write can catch.
|
|
647
|
+
await this.awaitReferencesLinked(source);
|
|
648
|
+
const nameProvider = this.resolveReferenceServices(source).NameProvider;
|
|
545
649
|
const tier = args.tier ?? 'project';
|
|
546
650
|
if (tier === 'public') {
|
|
547
651
|
return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
|
|
548
652
|
}
|
|
549
653
|
if (tier === 'local') {
|
|
550
|
-
// Document-scoped uniqueness: the document root is the container.
|
|
551
|
-
|
|
552
|
-
|
|
654
|
+
// Document-scoped uniqueness: the document root is the container. A
|
|
655
|
+
// URI with no document has nothing to collide with, like a document
|
|
656
|
+
// with no root.
|
|
657
|
+
try {
|
|
658
|
+
const document = await this.modelService.ensureDocumentState(args.uri);
|
|
659
|
+
return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
|
|
660
|
+
}
|
|
661
|
+
catch (error) {
|
|
662
|
+
if (this.isMissingDocument(error, args.uri)) {
|
|
663
|
+
return args.proposal;
|
|
664
|
+
}
|
|
665
|
+
throw error;
|
|
666
|
+
}
|
|
553
667
|
}
|
|
554
668
|
const project = this.services.workspace.ProjectManager.getProject(uri);
|
|
555
669
|
if (!project) {
|
|
@@ -582,66 +696,30 @@ export class DataServer {
|
|
|
582
696
|
return language.references;
|
|
583
697
|
}
|
|
584
698
|
/**
|
|
585
|
-
* Pick the language that owns a reference source
|
|
699
|
+
* Pick the language that owns a reference source: the registry's
|
|
700
|
+
* `getLanguageFor` over the source's declared language, URI and AST type,
|
|
701
|
+
* with an {@link isElementSource} routed by the document that holds the
|
|
702
|
+
* element (see {@link findElementDocumentUri}) before its type, and
|
|
703
|
+
* {@link fallbackReferenceLanguage}, adopter policy, last.
|
|
586
704
|
*
|
|
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.
|
|
705
|
+
* An unregistered declared language falls through rather than failing: the
|
|
706
|
+
* id crosses the wire, so a client built against a head with one more
|
|
707
|
+
* grammar would otherwise lose queries the other signals answer.
|
|
602
708
|
*/
|
|
603
709
|
resolveReferenceLanguage(source) {
|
|
604
710
|
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
711
|
if (isElementSource(source)) {
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
}
|
|
712
|
+
// The index lookup runs only once the cheaper signals abstained.
|
|
713
|
+
return (registry.getLanguageFor({}) ??
|
|
714
|
+
registry.getLanguageFor({ target: this.findElementDocumentUri(source), type: source.type }) ??
|
|
715
|
+
this.fallbackReferenceLanguage(source));
|
|
623
716
|
}
|
|
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;
|
|
717
|
+
const hint = isSyntheticSource(source)
|
|
718
|
+
? { languageId: source.language, target: source.uri, type: source.type }
|
|
719
|
+
: isDocumentSource(source)
|
|
720
|
+
? { target: source.uri }
|
|
721
|
+
: {};
|
|
722
|
+
return registry.getLanguageFor(hint) ?? this.fallbackReferenceLanguage(source);
|
|
645
723
|
}
|
|
646
724
|
/**
|
|
647
725
|
* Locate the document that holds the element an {@link ElementSource}
|
|
@@ -650,15 +728,14 @@ export class DataServer {
|
|
|
650
728
|
* disambiguates names that repeat across types (honouring grammar
|
|
651
729
|
* subtyping through `AstReflection.isSubtype`).
|
|
652
730
|
*
|
|
653
|
-
* Only reached
|
|
654
|
-
*
|
|
655
|
-
* step 2.
|
|
731
|
+
* Only reached in a multi-language workspace, once the declared language
|
|
732
|
+
* and the URI have abstained.
|
|
656
733
|
*
|
|
657
734
|
* Abstains when the name matches elements in more than one DOCUMENT — the
|
|
658
735
|
* 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
|
-
*
|
|
736
|
+
* first match" would be file-watch order rather than an answer. Routing
|
|
737
|
+
* then falls through to the element's type, which abstains on ties in the
|
|
738
|
+
* same way, and finally to adopter policy.
|
|
662
739
|
*/
|
|
663
740
|
findElementDocumentUri(source) {
|
|
664
741
|
const matches = this.services.workspace.IndexManager.getElementsByName(source.name, source.type);
|
|
@@ -690,55 +767,152 @@ export class DataServer {
|
|
|
690
767
|
// ============================================================
|
|
691
768
|
// Internal plumbing
|
|
692
769
|
// ============================================================
|
|
770
|
+
/**
|
|
771
|
+
* Whether `error`, from waiting on `uri`'s document, means that `uri` has
|
|
772
|
+
* no document: a URI with neither a file nor text builds nothing, and
|
|
773
|
+
* Langium's wait after the build rejects for want of one, with a
|
|
774
|
+
* `ServerCancelled` response error. Any other failure, such as a read
|
|
775
|
+
* that fails before a document is registered, a cancelled wait or a
|
|
776
|
+
* `ReentrantWriteLockError`, is the caller's to see.
|
|
777
|
+
*/
|
|
778
|
+
isMissingDocument(error, uri) {
|
|
779
|
+
return isResponseError(error) && error.code === SERVER_CANCELLED && this.modelService.getDocument(uri) === undefined;
|
|
780
|
+
}
|
|
693
781
|
/**
|
|
694
782
|
* Build a {@link TransferDocument} envelope from the current document state,
|
|
695
783
|
* 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) {
|
|
784
|
+
* `TransferEncoder.toTransferDocument` for the walk). `fingerprint` is the
|
|
785
|
+
* caller's {@link computeDocumentFingerprint} of that same state, which
|
|
786
|
+
* spares hashing it twice.
|
|
787
|
+
*/
|
|
788
|
+
envelope(uri, fingerprint) {
|
|
706
789
|
// Resolve through the model service's canonicalizing gateway rather than
|
|
707
790
|
// reaching into `LangiumDocuments` directly, so a divergent (symlink) URI
|
|
708
791
|
// still finds the document the build keys by its real path — and so the
|
|
709
792
|
// data-server never has to remember to canonicalize this lookup itself.
|
|
710
793
|
const document = this.modelService.getDocument(uri.toString());
|
|
711
|
-
if (!document) {
|
|
794
|
+
if (!document || this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
|
|
712
795
|
// No document — a shaped envelope rather than a throw, so the caller
|
|
713
|
-
// decides policy at its own layer; `
|
|
796
|
+
// decides policy at its own layer; `model` is optional on the envelope
|
|
714
797
|
// so the compiler forces that decision. Adopters preferring to throw
|
|
715
|
-
// override `envelope`.
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
798
|
+
// override `envelope`. The builder's unparsed placeholder is no
|
|
799
|
+
// document either: its root parses no text.
|
|
800
|
+
return TransferDocument.absent(uri.toString());
|
|
801
|
+
}
|
|
802
|
+
const encoded = this.encoder.toTransferDocument(document);
|
|
803
|
+
return this.withServerState(encoded, fingerprint ?? this.computeDocumentFingerprint(document.parseResult.value, encoded));
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* The transfer document a request answers with for `astDocument`, its model
|
|
807
|
+
* hashed and the text stamped on it by {@link withServerState}. Every
|
|
808
|
+
* document a request answers with goes through here, so none goes out
|
|
809
|
+
* without them.
|
|
810
|
+
*/
|
|
811
|
+
encodeDocument(astDocument) {
|
|
812
|
+
const encoded = this.encoder.astDocumentToTransferDocument(astDocument);
|
|
813
|
+
return this.withServerState(encoded, this.computeDocumentFingerprint(astDocument.root, encoded));
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* The project a client receives for `project`, unchanged by default. Every
|
|
817
|
+
* project a request answers with or a change notification carries goes
|
|
818
|
+
* through here, so a field derived for clients cannot miss one path. The
|
|
819
|
+
* result crosses as JSON, so a value a client reads goes in a data field,
|
|
820
|
+
* not a getter.
|
|
821
|
+
*/
|
|
822
|
+
encodeProject(project) {
|
|
823
|
+
return project;
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* `encoded` with `hash` on its model and the text the server holds for it:
|
|
827
|
+
* the store's while it holds the document, the build's otherwise. The text
|
|
828
|
+
* is read when the document is sent rather than kept with the build: a save
|
|
829
|
+
* changes `text.dirty` without a rebuild, and the store's text moves on before
|
|
830
|
+
* the build that follows it.
|
|
831
|
+
*/
|
|
832
|
+
withServerState(encoded, hash) {
|
|
833
|
+
const text = this.serverTextState(encoded.uri);
|
|
834
|
+
if (text && text.version > encoded.model.version) {
|
|
835
|
+
this.tracer.withUri(encoded.uri).debug(`Send a model behind its text: model v${encoded.model.version} / text v${text.version}`);
|
|
722
836
|
}
|
|
723
|
-
return
|
|
837
|
+
return {
|
|
838
|
+
uri: encoded.uri,
|
|
839
|
+
// The encoder returns the structural base; `TTransfer` is the adopter's
|
|
840
|
+
// declaration of the roots its languages produce, and nothing checks it.
|
|
841
|
+
model: { ...encoded.model, hash },
|
|
842
|
+
...(text ? { text } : {})
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* The text the server holds for `uri`, as every envelope and a watch's
|
|
847
|
+
* answer carry it: the store's while it holds the document, the build's
|
|
848
|
+
* otherwise, and none for a document it has neither of.
|
|
849
|
+
*/
|
|
850
|
+
serverTextState(uri) {
|
|
851
|
+
return this.services.workspace.TextDocuments.textState(uri) ?? this.builtTextState(uri);
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* The text a build read for a document the store never held, which is
|
|
855
|
+
* clean: the store holds every text a client gave it.
|
|
856
|
+
*/
|
|
857
|
+
builtTextState(uri) {
|
|
858
|
+
const textDocument = this.modelService.getDocument(uri)?.textDocument;
|
|
859
|
+
return textDocument && { version: textDocument.version, hash: textHash(textDocument.getText()), dirty: false };
|
|
724
860
|
}
|
|
725
861
|
/**
|
|
726
|
-
*
|
|
727
|
-
*
|
|
728
|
-
*
|
|
729
|
-
* regardless of subscriber count.
|
|
862
|
+
* Follow every document at the configured
|
|
863
|
+
* {@link DataServerOptions.subscriptionPhase}, once per connection rather
|
|
864
|
+
* than once per watch, so the cost stays flat in the number of watches.
|
|
730
865
|
*/
|
|
731
|
-
|
|
732
|
-
this.
|
|
866
|
+
subscribeToModelUpdates() {
|
|
867
|
+
const phase = this.options.subscriptionPhase;
|
|
868
|
+
this.disposables.push(this.modelService.onModelUpdated(event => this.dispatchPhaseEvent(event), { phase }));
|
|
869
|
+
// One message per build rather than one per document.
|
|
870
|
+
this.disposables.push(this.modelService.onModelsBuilt(event => this.dispatchBuiltEvent(event.uris), { phase }));
|
|
733
871
|
}
|
|
734
872
|
/**
|
|
735
|
-
*
|
|
736
|
-
*
|
|
737
|
-
*
|
|
738
|
-
*
|
|
739
|
-
* or any other client writing through `notifyDidSaveTextDocument`.
|
|
873
|
+
* Report the documents that reached {@link DataServerOptions.subscriptionPhase}
|
|
874
|
+
* and that NOBODY on this
|
|
875
|
+
* connection is watching — the ones a client was not told about through
|
|
876
|
+
* {@link dispatchPhaseEvent}, which is gated per URI.
|
|
740
877
|
*
|
|
741
|
-
*
|
|
878
|
+
* **The gap this closes is the one no other source can observe.** A document
|
|
879
|
+
* the client watches, it hears about already. A file changed on disk, the
|
|
880
|
+
* host's own filesystem watcher reports — and on a browser host, where the
|
|
881
|
+
* workspace lives behind this head, an external change cannot happen at all.
|
|
882
|
+
* What is left, and what nothing outside the server can see, is a document
|
|
883
|
+
* rebuilt because something it DEPENDS ON changed: its file never changed, so
|
|
884
|
+
* a filesystem watcher is silent by construction, and it has no subscriber, so
|
|
885
|
+
* the update channel is silent by design. A consumer displaying data derived
|
|
886
|
+
* from that document — a tree label, a decorator — otherwise goes stale with
|
|
887
|
+
* no signal from any source, and repairs itself the moment someone opens the
|
|
888
|
+
* file to investigate, which is what makes it expensive to diagnose later.
|
|
889
|
+
*
|
|
890
|
+
* Payload-free on purpose: URIs only, so a client re-reads what it displays
|
|
891
|
+
* rather than being handed transfer documents it did not ask for. That is the
|
|
892
|
+
* property the watcher gate protects, and it is preserved here by
|
|
893
|
+
* carrying no document rather than by gating the message.
|
|
894
|
+
*
|
|
895
|
+
* Quiet in the common case. Editing a document that an editor has open leaves
|
|
896
|
+
* that URI watched and therefore out of this set, so a build with no
|
|
897
|
+
* dependents produces nothing at all, and workspace initialisation produces
|
|
898
|
+
* nothing because it does not build to this phase. The ceiling is a
|
|
899
|
+
* whole-workspace rebuild at the subscription phase: one message, URIs only.
|
|
900
|
+
*/
|
|
901
|
+
dispatchBuiltEvent(built) {
|
|
902
|
+
const uris = built.map(uri => this.canonicalKey(uri)).filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
|
|
903
|
+
if (uris.length === 0) {
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
|
|
907
|
+
this.clientProxy.onDocumentsBuilt({ uris });
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Follow every save so a single `onDocumentSaved` wire notification fires
|
|
911
|
+
* for ANY save of a subscribed URI — regardless of whether the save
|
|
912
|
+
* originated from the data-server's RPC `saveModelDocument`, the LSP head's
|
|
913
|
+
* text-editor save, or any other client.
|
|
914
|
+
*
|
|
915
|
+
* Architectural symmetry with {@link subscribeToModelUpdates}: every
|
|
742
916
|
* subscribed client sees every state change to documents they care about,
|
|
743
917
|
* regardless of which client triggered it. Firing `onDocumentSaved` only
|
|
744
918
|
* from the data-server's own RPC path is a bug, not an optimisation: an
|
|
@@ -746,37 +920,108 @@ export class DataServer {
|
|
|
746
920
|
* clients, which never clear their dirty state.
|
|
747
921
|
*/
|
|
748
922
|
subscribeToTextDocumentSaves() {
|
|
749
|
-
this.disposables.push(this.
|
|
923
|
+
this.disposables.push(this.modelService.onModelSaved(event => this.dispatchSaveEvent(event)));
|
|
924
|
+
}
|
|
925
|
+
/** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
|
|
926
|
+
subscribeToDirtyChanges() {
|
|
927
|
+
this.disposables.push(this.modelService.onDirtyChanged(event => this.dispatchDirtyEvent(event)));
|
|
750
928
|
}
|
|
751
929
|
/**
|
|
752
|
-
*
|
|
753
|
-
* {@link
|
|
754
|
-
*
|
|
755
|
-
* hold, so a `false` answer means this close was the last one.
|
|
930
|
+
* Send a dirty flip to the connection, gated on the URI's watchers as
|
|
931
|
+
* {@link dispatchSaveEvent} is: the answer at any one moment travels on
|
|
932
|
+
* every document sent, so a client that watches nothing reads it there.
|
|
756
933
|
*/
|
|
757
|
-
|
|
758
|
-
const
|
|
759
|
-
this.
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
934
|
+
dispatchDirtyEvent(event) {
|
|
935
|
+
const uri = this.canonicalKey(event.uri);
|
|
936
|
+
if (this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
937
|
+
this.clientProxy.onDocumentDirtyChanged({ uri, text: event.text });
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
/**
|
|
941
|
+
* Mark each document the store releases, so {@link dispatchPhaseEvent}
|
|
942
|
+
* broadcasts the build that follows even without a watcher. By default
|
|
943
|
+
* that build reverts the document to its disk content, discarding unsaved
|
|
944
|
+
* in-session edits, and the last close typically also
|
|
945
|
+
* removed the last watcher: without the broadcast, a consumer that only
|
|
946
|
+
* ever fetches via `getModelDocument` keeps showing the discarded state.
|
|
947
|
+
* The broadcast is de-duplicated against the fingerprint while a watcher
|
|
948
|
+
* holds one, so a close whose disk state equals the last emitted state
|
|
949
|
+
* stays silent; with no watcher there is no fingerprint, and every release
|
|
950
|
+
* build is sent. The first build after the release consumes the mark, and
|
|
951
|
+
* goes out as the release unless it is stamped past the version a client
|
|
952
|
+
* opened the document at again: a client's write or an integrity repair
|
|
953
|
+
* that rides it keeps its author.
|
|
954
|
+
*
|
|
955
|
+
* A release, not the close itself: a document whose last client lost its
|
|
956
|
+
* connection is released only once the release grace runs out, or when
|
|
957
|
+
* another client opens it meanwhile, and not at all when a client lost
|
|
958
|
+
* from it opens it again within its own grace.
|
|
959
|
+
*/
|
|
960
|
+
subscribeToModelReleases() {
|
|
961
|
+
this.disposables.push(this.modelService.onModelReleased(event => {
|
|
962
|
+
const uri = this.canonicalKey(event.uri);
|
|
963
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set() };
|
|
964
|
+
record.releaseBroadcastPending = true;
|
|
965
|
+
this.uriWatchRecords.set(uri, record);
|
|
966
|
+
this.tracer.withUri(uri).debug('Release marked: the first build after it is broadcast, watched or not');
|
|
763
967
|
}));
|
|
764
968
|
}
|
|
765
|
-
/**
|
|
969
|
+
/**
|
|
970
|
+
* Fan out a deletion for each removed URI, to EVERY client on the connection
|
|
971
|
+
* rather than only to the ones watching that URI.
|
|
972
|
+
*
|
|
973
|
+
* **Deliberately ungated, where {@link dispatchPhaseEvent} and
|
|
974
|
+
* {@link dispatchSaveEvent} are gated.** Those two carry a built document and
|
|
975
|
+
* fire on every build, so the watcher gate is what keeps bandwidth
|
|
976
|
+
* proportional to what a client asked for. A deletion is neither: it is one
|
|
977
|
+
* URI, it is rare, and it reports the workspace's STRUCTURE rather than a
|
|
978
|
+
* document's content. Gating it forces any consumer that displays the
|
|
979
|
+
* workspace — a model tree, a file decorator — to learn about disappearances
|
|
980
|
+
* from a filesystem watcher instead, which a client hosted in a browser has
|
|
981
|
+
* no way to run: its workspace lives behind the head. A client that does not
|
|
982
|
+
* care filters on the URI, which costs it a comparison.
|
|
983
|
+
*
|
|
984
|
+
* The precedent is the release broadcast (see
|
|
985
|
+
* {@link subscribeToModelReleases}), where the same judgement was already made
|
|
986
|
+
* in the other direction: a transition that matters enough is delivered
|
|
987
|
+
* without a subscription.
|
|
988
|
+
*
|
|
989
|
+
* A deletion is announced before the build that follows it, so this goes
|
|
990
|
+
* out ahead of the `'rebuilt'` events for the dependents whose references
|
|
991
|
+
* the deletion just broke.
|
|
992
|
+
*
|
|
993
|
+
* The URI's fingerprint and release mark are dropped: they describe a
|
|
994
|
+
* document that no longer exists. A kept fingerprint is adopted as the
|
|
995
|
+
* baseline and suppresses the first emit after the file returns with its
|
|
996
|
+
* previous content.
|
|
997
|
+
*
|
|
998
|
+
* The watchers SURVIVE: a recreated file resumes delivering to them with no
|
|
999
|
+
* re-subscription, and a client that answers the deletion by closing
|
|
1000
|
+
* releases the watch through `closeModelDocument` anyway. A session that
|
|
1001
|
+
* deleted the document has its own released by {@link deleteModelDocument}.
|
|
1002
|
+
*/
|
|
1003
|
+
dispatchDeleteEvent(event) {
|
|
1004
|
+
const uri = this.canonicalKey(event.uri);
|
|
1005
|
+
const record = this.uriWatchRecords.get(uri);
|
|
1006
|
+
if (record) {
|
|
1007
|
+
record.fingerprint = undefined;
|
|
1008
|
+
record.fingerprintVersion = undefined;
|
|
1009
|
+
record.releaseBroadcastPending = undefined;
|
|
1010
|
+
record.sentVersion = undefined;
|
|
1011
|
+
this.pruneUriWatchRecord(uri);
|
|
1012
|
+
}
|
|
1013
|
+
this.clientProxy.onDocumentDeleted({ uri, sourceClientId: event.sourceClientId, sequence: ++this.eventSequence });
|
|
1014
|
+
}
|
|
1015
|
+
/** Fan out a save event for the document's URI, gated on the URI's watchers. */
|
|
766
1016
|
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
1017
|
const uri = this.canonicalKey(event.document.uri);
|
|
773
|
-
if (!this.
|
|
1018
|
+
if (!this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
774
1019
|
return;
|
|
775
1020
|
}
|
|
776
|
-
const response = this.envelope(UriUtils.toUri(uri));
|
|
1021
|
+
const response = this.envelope(UriUtils.toUri(event.document.uri));
|
|
777
1022
|
const wireEvent = {
|
|
778
1023
|
document: response,
|
|
779
|
-
sourceClientId: event.
|
|
1024
|
+
sourceClientId: event.sourceClientId
|
|
780
1025
|
};
|
|
781
1026
|
this.clientProxy.onDocumentSaved(wireEvent);
|
|
782
1027
|
}
|
|
@@ -789,107 +1034,107 @@ export class DataServer {
|
|
|
789
1034
|
* out to multiple local subscribers with an `Emitter<T>` — the
|
|
790
1035
|
* framework deliberately does NOT promise multi-listener semantics.
|
|
791
1036
|
*
|
|
792
|
-
*
|
|
793
|
-
*
|
|
794
|
-
*
|
|
795
|
-
*
|
|
796
|
-
*
|
|
797
|
-
*
|
|
798
|
-
*
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
1037
|
+
* An event for a URI no client watches is NOT sent over the wire, so
|
|
1038
|
+
* bandwidth scales with watched URIs rather than with phase events; a
|
|
1039
|
+
* pending release mark is the exception (see
|
|
1040
|
+
* {@link subscribeToModelReleases}).
|
|
1041
|
+
*
|
|
1042
|
+
* An event for a rebuild with no observable change since the last emit is
|
|
1043
|
+
* suppressed against the URI's fingerprint and the version it was taken at;
|
|
1044
|
+
* a new version with the same fingerprint goes out with the same
|
|
1045
|
+
* `model.hash`, so a watcher still learns the version. Such rebuilds are routine: a
|
|
1046
|
+
* second client attaching to an open document makes
|
|
1047
|
+
* `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
|
|
1048
|
+
* to re-trigger the build, and Langium rebuilds a document when a
|
|
1049
|
+
* dependency changes even if its diagnostics come out the same. Sent at a
|
|
1050
|
+
* version this head has not sent, they reach watchers as `'changed'`, and a
|
|
1051
|
+
* watcher that reads `'changed'` as another client's write and resets its
|
|
1052
|
+
* root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
|
|
1053
|
+
* fingerprint, so the first event after a watch is de-duplicated against
|
|
1054
|
+
* the state the watcher just fetched; it goes with the last watcher, so the
|
|
1055
|
+
* next first watch re-baselines rather than adopting a stale digest. A
|
|
1056
|
+
* digest keeps its memory constant in document size; see
|
|
1057
|
+
* {@link computeDocumentFingerprint} for the inputs.
|
|
1058
|
+
*/
|
|
1059
|
+
dispatchPhaseEvent(event) {
|
|
1060
|
+
const uri = this.canonicalKey(event.document.uri);
|
|
1061
|
+
const record = this.uriWatchRecords.get(uri);
|
|
1062
|
+
const afterRelease = record?.releaseBroadcastPending === true;
|
|
1063
|
+
if (!record || (record.watchers.size === 0 && !afterRelease)) {
|
|
807
1064
|
return;
|
|
808
1065
|
}
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
1066
|
+
if (afterRelease) {
|
|
1067
|
+
// Consumed even when watchers exist — the regular dispatch below
|
|
1068
|
+
// serves them, and the mark's attribution is more precise than the
|
|
1069
|
+
// post-close unknown client the manager's attribution would yield.
|
|
1070
|
+
// With no watcher the record goes now, so the fingerprint written
|
|
1071
|
+
// below lands on a detached record and the next first watch
|
|
1072
|
+
// re-baselines instead of adopting it.
|
|
1073
|
+
record.releaseBroadcastPending = undefined;
|
|
1074
|
+
this.pruneUriWatchRecord(uri);
|
|
1075
|
+
}
|
|
1076
|
+
// The encoder reads the built document, which the event's holds for this
|
|
1077
|
+
// synchronous run.
|
|
1078
|
+
const document = this.modelService.getDocument(event.document.uri);
|
|
1079
|
+
if (!document) {
|
|
816
1080
|
return;
|
|
817
1081
|
}
|
|
818
|
-
const fingerprint = this.computeDocumentFingerprint(document);
|
|
819
|
-
|
|
1082
|
+
const fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
|
|
1083
|
+
const stamped = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
|
|
1084
|
+
if (record.fingerprint === fingerprint && record.fingerprintVersion === stamped) {
|
|
820
1085
|
// A rebuild that produced no observable change since the last emit —
|
|
821
1086
|
// suppressed so RPC subscribers don't see a no-op broadcast. Logged at
|
|
822
1087
|
// debug so a *needed* re-broadcast wrongly suppressed by this dedup
|
|
823
1088
|
// (the failure mode the fingerprint strategy must avoid) is visible.
|
|
824
|
-
this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${
|
|
1089
|
+
this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${stamped}: fingerprint and version unchanged`);
|
|
825
1090
|
return;
|
|
826
1091
|
}
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
1092
|
+
record.fingerprint = fingerprint;
|
|
1093
|
+
record.fingerprintVersion = stamped;
|
|
1094
|
+
// The event's attribution, so this head names the same client as the
|
|
1095
|
+
// in-process heads do for one build, except for a version this head
|
|
1096
|
+
// already sent; see `DataServerUriWatchRecord.sentVersion`.
|
|
1097
|
+
const version = this.modelService.isOpen(event.document.uri) ? document.textDocument.version : undefined;
|
|
1098
|
+
const { reason, sourceClientId } = version !== undefined && record.sentVersion === version
|
|
1099
|
+
? { reason: 'rebuilt', sourceClientId: UNKNOWN_CLIENT_ID }
|
|
1100
|
+
: event;
|
|
1101
|
+
record.sentVersion = version;
|
|
1102
|
+
// The stamp, not the live version: a write after the build's parse moves
|
|
1103
|
+
// only the latter. At the opened version too, which a reopen with the
|
|
1104
|
+
// released text keeps.
|
|
1105
|
+
const openedVersion = afterRelease ? this.modelService.openedVersion(event.document.uri) : undefined;
|
|
1106
|
+
const releaseBuild = afterRelease && (openedVersion === undefined || stamped <= openedVersion);
|
|
1107
|
+
const wireEvent = {
|
|
1108
|
+
document: this.envelope(document.uri, fingerprint),
|
|
1109
|
+
sourceClientId: releaseBuild ? DOCUMENT_RELEASE_CLIENT_ID : sourceClientId,
|
|
1110
|
+
reason,
|
|
1111
|
+
sequence: ++this.eventSequence
|
|
832
1112
|
};
|
|
1113
|
+
const mark = afterRelease ? `, release mark: opened v${openedVersion ?? '-'}, attributed ${sourceClientId}` : '';
|
|
833
1114
|
this.tracer
|
|
834
1115
|
.withUri(uri)
|
|
835
|
-
.debug(`Emit onDocumentUpdated v${
|
|
836
|
-
this.clientProxy.onDocumentUpdated(
|
|
1116
|
+
.debug(`Emit onDocumentUpdated v${stamped} (reason=${wireEvent.reason}, sourceClientId=${wireEvent.sourceClientId}${mark})`);
|
|
1117
|
+
this.clientProxy.onDocumentUpdated(wireEvent);
|
|
837
1118
|
}
|
|
838
1119
|
/**
|
|
839
|
-
* Fingerprint of the
|
|
840
|
-
* `onDocumentUpdated` emissions
|
|
841
|
-
*
|
|
842
|
-
* {@link
|
|
1120
|
+
* Fingerprint of the snapshot `root` and its encoding `encoded`, used to
|
|
1121
|
+
* de-dup `onDocumentUpdated` emissions and sent as every document's
|
|
1122
|
+
* `model.hash`, so it must not depend on the version or on live state. The
|
|
1123
|
+
* {@link FingerprintStrategy} option selects what is hashed (default
|
|
1124
|
+
* `'transfer-document'` — see the type).
|
|
843
1125
|
*
|
|
844
|
-
*
|
|
845
|
-
*
|
|
846
|
-
*
|
|
847
|
-
* `envelope` share a single encode walk.
|
|
1126
|
+
* {@link TransferEncoder.toTransferDocument} is cached per build, so within
|
|
1127
|
+
* one phase event the fingerprint and the subsequently-emitted `envelope`
|
|
1128
|
+
* share a single encode walk.
|
|
848
1129
|
*
|
|
849
1130
|
* Wrapped in {@link Tracer.time} against {@link FINGERPRINT_LOG_AFTER_MS}.
|
|
850
1131
|
*/
|
|
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';
|
|
1132
|
+
computeDocumentFingerprint(root, encoded) {
|
|
1133
|
+
return this.tracer
|
|
1134
|
+
.withUri(encoded.uri)
|
|
1135
|
+
.time('Compute fingerprint', () => this.options.fingerprintStrategy === 'text-diagnostics'
|
|
1136
|
+
? textDiagnosticsFingerprint(this.services.workspace.ModelLedger.textOf(root), encoded.model)
|
|
1137
|
+
: transferDocumentFingerprint(encoded.model), 'debug', { logAfterMs: FINGERPRINT_LOG_AFTER_MS });
|
|
893
1138
|
}
|
|
894
1139
|
/**
|
|
895
1140
|
* Subscribe to the project tier's change channel and re-fan registry
|
|
@@ -913,38 +1158,38 @@ export class DataServer {
|
|
|
913
1158
|
/**
|
|
914
1159
|
* Fan one internal {@link ProjectChangeEvent} out to per-project wire
|
|
915
1160
|
* notifications. Each `removed` entry pairs the id with the pre-removal
|
|
916
|
-
* snapshot needed for the `'removed'` wire payload.
|
|
1161
|
+
* snapshot needed for the `'removed'` wire payload. A project whose
|
|
1162
|
+
* {@link encodeProject} throws is logged and skipped, so the rest of the
|
|
1163
|
+
* batch still reaches the client.
|
|
917
1164
|
*/
|
|
918
1165
|
dispatchProjectChangeEvent(event) {
|
|
1166
|
+
const send = (project, reason) => {
|
|
1167
|
+
let encoded;
|
|
1168
|
+
try {
|
|
1169
|
+
encoded = this.encodeProject(project);
|
|
1170
|
+
}
|
|
1171
|
+
catch (error) {
|
|
1172
|
+
this.tracer.error(`Project ${project.id} not sent as ${reason}: encodeProject threw: ${describeErrorWithStack(error)}`);
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
this.clientProxy.onProjectsChanged({ project: encoded, reason });
|
|
1176
|
+
};
|
|
919
1177
|
for (const id of event.added) {
|
|
920
1178
|
const project = this.services.workspace.ProjectManager.getProjectById(id);
|
|
921
1179
|
if (project) {
|
|
922
|
-
|
|
1180
|
+
send(project, 'added');
|
|
923
1181
|
}
|
|
924
1182
|
}
|
|
925
1183
|
for (const id of event.updated) {
|
|
926
1184
|
const project = this.services.workspace.ProjectManager.getProjectById(id);
|
|
927
1185
|
if (project) {
|
|
928
|
-
|
|
1186
|
+
send(project, 'updated');
|
|
929
1187
|
}
|
|
930
1188
|
}
|
|
931
1189
|
for (const entry of event.removed) {
|
|
932
|
-
|
|
1190
|
+
send(entry.snapshot, 'removed');
|
|
933
1191
|
}
|
|
934
1192
|
}
|
|
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
1193
|
// --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
|
|
949
1194
|
// Computed in THIS process: the data-server child holds the model store, so
|
|
950
1195
|
// these snapshots reflect the heap that actually carries the workspace
|
|
@@ -1002,7 +1247,7 @@ export class DataServer {
|
|
|
1002
1247
|
const builtIn = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS];
|
|
1003
1248
|
const overlap = additionalMethods.filter(name => builtIn.includes(name));
|
|
1004
1249
|
if (overlap.length > 0) {
|
|
1005
|
-
throw new Error(`
|
|
1250
|
+
throw new Error(`DataServerOptions.additionalMethods overlaps with built-in data-server methods: ${overlap.join(', ')}. ` +
|
|
1006
1251
|
'Adopter protocols must not redeclare framework method names; rename the adopter method or remove it from additionalMethods.');
|
|
1007
1252
|
}
|
|
1008
1253
|
return {
|
|
@@ -1011,7 +1256,8 @@ export class DataServer {
|
|
|
1011
1256
|
methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
|
|
1012
1257
|
additionalMethods,
|
|
1013
1258
|
excludedMethods: partial.excludedMethods ?? [],
|
|
1014
|
-
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
|
|
1259
|
+
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
|
|
1260
|
+
referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
|
|
1015
1261
|
};
|
|
1016
1262
|
}
|
|
1017
1263
|
}
|