@hydranium/data-server 1.0.0-next.14 → 1.0.0-next.140
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 +14 -1
- package/lib/data-server.d.ts +363 -191
- package/lib/data-server.d.ts.map +1 -1
- package/lib/data-server.js +529 -298
- 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/testing/data-server-harness.d.ts +7 -1
- package/lib/testing/data-server-harness.d.ts.map +1 -1
- package/lib/testing/data-server-harness.js +5 -2
- package/lib/testing/data-server-harness.js.map +1 -1
- package/package.json +17 -8
- package/src/data-server.ts +665 -324
- package/src/messages/index.ts +26 -0
- package/src/testing/data-server-harness.ts +16 -1
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, isSyntheticSource, messageData, messageError, ReferenceSource, SessionClosedError, TIMED_OUT, TransferDocument, UNKNOWN_CLIENT_ID, asSnapshotVersion } from '@hydranium/protocol';
|
|
10
10
|
import { DATA_SERVER_DIAGNOSTICS_METHODS, DATA_SERVER_PROTOCOL_METHODS, DATA_SERVER_WIRE_PREFIX } from '@hydranium/protocol/data';
|
|
11
|
-
import { REVERT_ON_CLOSE_CLIENT_ID
|
|
11
|
+
import { REVERT_ON_CLOSE_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
|
|
@@ -47,6 +79,7 @@ function fingerprintHash(parts) {
|
|
|
47
79
|
const low = (h1 >>> 0).toString(16).padStart(8, '0');
|
|
48
80
|
return high + low;
|
|
49
81
|
}
|
|
82
|
+
const resumableByModelService = new WeakMap();
|
|
50
83
|
/** Hash a document's raw text + diagnostics — the `'text-diagnostics'` strategy. */
|
|
51
84
|
function textDiagnosticsFingerprint(document) {
|
|
52
85
|
return fingerprintHash([document.textDocument.getText(), FINGERPRINT_SEPARATOR, JSON.stringify(document.diagnostics ?? [])]);
|
|
@@ -94,9 +127,11 @@ const FINGERPRINT_LOG_AFTER_MS = 5;
|
|
|
94
127
|
* any names supplied via {@link DataServerOptions.additionalMethods}) and
|
|
95
128
|
* builds the {@link DataClientProtocol} notification proxy on the same
|
|
96
129
|
* connection in one {@link createRpcProxy} call (binding `this` as its
|
|
97
|
-
* `localTarget`) under the configured namespace, and subscribes
|
|
98
|
-
* `DocumentBuilder.onDocumentPhase`
|
|
99
|
-
*
|
|
130
|
+
* `localTarget`) under the configured namespace, and subscribes two listeners
|
|
131
|
+
* at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
|
|
132
|
+
* per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
|
|
133
|
+
* `DocumentBuilder.onBuildPhase` one dispatching a single
|
|
134
|
+
* `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
|
|
100
135
|
*
|
|
101
136
|
* The data-server requires the full {@link ServerSharedServices}
|
|
102
137
|
* shape — `HydraniumTextDocuments` for client-attributed updates,
|
|
@@ -121,85 +156,25 @@ export class DataServer {
|
|
|
121
156
|
* extending rather than restate a value the framework may change.
|
|
122
157
|
*/
|
|
123
158
|
static DEFAULT_OPTIONS = {
|
|
124
|
-
subscriptionPhase: DocumentState.Validated
|
|
159
|
+
subscriptionPhase: DocumentState.Validated,
|
|
160
|
+
referenceSettleTimeoutMs: 60_000
|
|
125
161
|
};
|
|
126
162
|
options;
|
|
127
|
-
/**
|
|
128
|
-
|
|
163
|
+
/** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
|
|
164
|
+
uriWatchRecords = new Map();
|
|
129
165
|
/**
|
|
130
|
-
*
|
|
131
|
-
*
|
|
166
|
+
* The client sessions this connection registered, by client id. A document
|
|
167
|
+
* request carrying one of these ids acts as that session; one carrying any
|
|
168
|
+
* other id fails.
|
|
132
169
|
*
|
|
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.
|
|
170
|
+
* Entries stay after {@link dispose} has ended their sessions, so a request
|
|
171
|
+
* still running from before the connection closed reaches the ended handle
|
|
172
|
+
* and fails with the session's own error.
|
|
139
173
|
*/
|
|
140
|
-
|
|
174
|
+
clientSessions = new Map();
|
|
141
175
|
/** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
|
|
142
176
|
clientProxy;
|
|
143
177
|
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.
|
|
151
|
-
*/
|
|
152
|
-
lastBuildUpdate;
|
|
153
|
-
/**
|
|
154
|
-
* Per-URI hash of the last emitted (text + diagnostics) state,
|
|
155
|
-
* used by {@link dispatchPhaseEvent} to suppress duplicate
|
|
156
|
-
* `onDocumentUpdated` notifications for rebuilds that produce no
|
|
157
|
-
* observable change since the last emit.
|
|
158
|
-
*
|
|
159
|
-
* Two scenarios routinely produce such rebuilds:
|
|
160
|
-
* 1. **Refresh-triggered rebuilds.** When a second client attaches to a
|
|
161
|
-
* document already open in another client,
|
|
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();
|
|
203
178
|
tracer;
|
|
204
179
|
/** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
|
|
205
180
|
activeProfile;
|
|
@@ -211,11 +186,8 @@ export class DataServer {
|
|
|
211
186
|
encoder;
|
|
212
187
|
/**
|
|
213
188
|
* 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`.
|
|
189
|
+
* Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
|
|
190
|
+
* {@link encoder} converts one into the other on the way out.
|
|
219
191
|
*/
|
|
220
192
|
modelService;
|
|
221
193
|
constructor(connection, services, options = {}) {
|
|
@@ -224,8 +196,7 @@ export class DataServer {
|
|
|
224
196
|
this.options = this.resolveOptions(options);
|
|
225
197
|
this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
|
|
226
198
|
// 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.
|
|
199
|
+
// `services.model.ModelService` with their own subclasses.
|
|
229
200
|
const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
|
|
230
201
|
if (!encoder || !modelService) {
|
|
231
202
|
throw new Error('DataServer requires `services.model.TransferEncoder` and `services.model.ModelService` to be bound. ' +
|
|
@@ -248,35 +219,42 @@ export class DataServer {
|
|
|
248
219
|
methodNamespace: this.options.methodNamespace,
|
|
249
220
|
localTarget: this,
|
|
250
221
|
localMethods: registeredMethods,
|
|
251
|
-
latency: this.latency
|
|
222
|
+
latency: this.latency,
|
|
223
|
+
// Bound at the chokepoint rather than per handler, so an adopter's
|
|
224
|
+
// `additionalMethods` are rendered on the same terms as the
|
|
225
|
+
// framework's own rejections.
|
|
226
|
+
renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
|
|
252
227
|
});
|
|
253
|
-
this.disposables.push(this.services.workspace.DocumentBuilder.onUpdate((
|
|
254
|
-
this.lastBuildUpdate = { changed, deleted };
|
|
255
|
-
}));
|
|
228
|
+
this.disposables.push(this.services.workspace.DocumentBuilder.onUpdate((_changed, deleted) => this.dispatchDeleteEvents(deleted)));
|
|
256
229
|
this.subscribeToDocumentBuilder();
|
|
257
230
|
this.subscribeToTextDocumentSaves();
|
|
231
|
+
this.subscribeToDirtyChanges();
|
|
258
232
|
this.subscribeToTextDocumentCloses();
|
|
259
233
|
this.subscribeToProjectManager();
|
|
260
234
|
// Self-register teardown so an adopter that keeps no reference to the
|
|
261
235
|
// server still releases per-connection state, with no lifecycle hook of
|
|
262
|
-
// its own.
|
|
263
|
-
|
|
236
|
+
// its own. The client did not close anything itself, so its sessions end
|
|
237
|
+
// as lost and each document it was the last to have open waits out the
|
|
238
|
+
// store's revert grace. See `dispose`.
|
|
239
|
+
this.disposables.push(connection.onClose(() => this.dispose('lost')));
|
|
264
240
|
}
|
|
265
241
|
/**
|
|
266
242
|
* Release everything the constructor wired up — the bound protocol
|
|
267
|
-
* handlers and every listener — and clear
|
|
268
|
-
*
|
|
269
|
-
*
|
|
270
|
-
*
|
|
271
|
-
*
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
|
|
279
|
-
|
|
243
|
+
* handlers and every listener — and clear {@link uriWatchRecords}, so a
|
|
244
|
+
* long-lived shared services bundle does not retain per-connection memory
|
|
245
|
+
* after the connection closes. Also ends every session this connection registered, which closes
|
|
246
|
+
* every document it has open: the SHARED store's state rather than this
|
|
247
|
+
* server's, which outlives the connection unless released here.
|
|
248
|
+
*
|
|
249
|
+
* Idempotent: subsequent calls are no-ops. Runs by itself when the
|
|
250
|
+
* connection closes, so adopters who don't hold a reference still get
|
|
251
|
+
* per-connection cleanup; adopters that DO hold a reference may call
|
|
252
|
+
* `dispose()` directly for early teardown. The sessions end with `cause`:
|
|
253
|
+
* `'closed'` reverts every document whose last open they close at once,
|
|
254
|
+
* and `'lost'`, the connection's own close, lets each wait out the revert
|
|
255
|
+
* grace.
|
|
256
|
+
*/
|
|
257
|
+
dispose(cause = 'closed') {
|
|
280
258
|
this.disposed = true;
|
|
281
259
|
// Release an in-flight interactive capture so the process-wide inspector
|
|
282
260
|
// singleton is not left active after the connection closes.
|
|
@@ -285,97 +263,163 @@ export class DataServer {
|
|
|
285
263
|
this.activeProfile = undefined;
|
|
286
264
|
void capture.stop({}).catch(() => undefined);
|
|
287
265
|
}
|
|
288
|
-
// AFTER `disposables.dispose()`, deliberately:
|
|
289
|
-
//
|
|
290
|
-
//
|
|
266
|
+
// AFTER `disposables.dispose()`, deliberately: ending a session releases
|
|
267
|
+
// each document it was the last to hold, and this server's own
|
|
268
|
+
// `onDidCloseLastOpen` listener would otherwise mark a revert broadcast
|
|
269
|
+
// for a connection that is already gone.
|
|
291
270
|
this.disposables.dispose();
|
|
292
|
-
this.
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
this.
|
|
271
|
+
for (const [clientId, session] of this.clientSessions) {
|
|
272
|
+
this.endSession(clientId, session, cause);
|
|
273
|
+
}
|
|
274
|
+
this.uriWatchRecords.clear();
|
|
296
275
|
}
|
|
297
276
|
// ============================================================
|
|
298
|
-
// DataServerProtocol implementation
|
|
277
|
+
// DataServerProtocol implementation
|
|
299
278
|
// ============================================================
|
|
300
279
|
//
|
|
301
|
-
//
|
|
302
|
-
//
|
|
303
|
-
// the wire boundary via
|
|
304
|
-
//
|
|
305
|
-
//
|
|
306
|
-
//
|
|
307
|
-
async
|
|
308
|
-
//
|
|
309
|
-
//
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
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);
|
|
280
|
+
// Reads go to `ModelService`; a request that opens or writes a document
|
|
281
|
+
// goes to the session this connection registered under its `clientId`.
|
|
282
|
+
// Each answer is encoded on the wire boundary via
|
|
283
|
+
// `encoder.astDocumentToTransferDocument`. To change how documents are
|
|
284
|
+
// read, override on the ModelService subclass; to change how they are
|
|
285
|
+
// written, on the session class the bound `ClientSessionFactory` builds.
|
|
286
|
+
async createSession(args) {
|
|
287
|
+
// After teardown nothing would ever end a session registered now, and its
|
|
288
|
+
// id would stay taken for the life of the process.
|
|
289
|
+
if (this.disposed) {
|
|
290
|
+
throw new SessionClosedError(args.clientId);
|
|
291
|
+
}
|
|
292
|
+
const resumable = this.resumableSessions();
|
|
293
|
+
const previous = resumable.get(args.clientId);
|
|
294
|
+
if (previous && args.resumeToken !== undefined && previous.token === args.resumeToken) {
|
|
295
|
+
previous.end();
|
|
296
|
+
}
|
|
297
|
+
const session = this.modelService.createSession(args.label, args.clientId);
|
|
298
|
+
this.clientSessions.set(args.clientId, session);
|
|
299
|
+
if (args.resumeToken !== undefined) {
|
|
300
|
+
// Taken over by a client registering again after its connection
|
|
301
|
+
// dropped, so the old session ends as lost: the documents it was the
|
|
302
|
+
// last to have open wait out the grace, and the new session's opens
|
|
303
|
+
// find their unsaved text.
|
|
304
|
+
resumable.set(args.clientId, { token: args.resumeToken, end: () => this.endSession(args.clientId, session, 'lost') });
|
|
305
|
+
}
|
|
341
306
|
}
|
|
342
307
|
/**
|
|
343
|
-
*
|
|
344
|
-
*
|
|
308
|
+
* End a session this connection registered. The ended handle stays in
|
|
309
|
+
* {@link clientSessions}, as it does after {@link dispose}, so a request for
|
|
310
|
+
* the id still arriving fails with the ended session's own error.
|
|
345
311
|
*/
|
|
346
|
-
|
|
347
|
-
const
|
|
348
|
-
if (
|
|
349
|
-
|
|
312
|
+
async closeSession(args) {
|
|
313
|
+
const session = this.clientSessions.get(args.clientId);
|
|
314
|
+
if (session) {
|
|
315
|
+
this.endSession(args.clientId, session);
|
|
350
316
|
}
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
317
|
+
}
|
|
318
|
+
/** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
|
|
319
|
+
endSession(clientId, session, cause = 'closed') {
|
|
320
|
+
for (const [uri, record] of this.uriWatchRecords) {
|
|
321
|
+
if (record.watchers.delete(clientId)) {
|
|
322
|
+
this.pruneUriWatchRecord(uri);
|
|
323
|
+
}
|
|
354
324
|
}
|
|
325
|
+
session.dispose(cause);
|
|
355
326
|
}
|
|
356
327
|
/**
|
|
357
|
-
*
|
|
358
|
-
*
|
|
328
|
+
* The resumable sessions of this services tree, by client id, across all of
|
|
329
|
+
* its data connections: a client resumes on another connection than the one
|
|
330
|
+
* that registered it. An entry leaves when its session ends, by any path, so
|
|
331
|
+
* it keeps no ended connection alive.
|
|
359
332
|
*
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
*
|
|
364
|
-
*
|
|
365
|
-
|
|
333
|
+
* A takeover by resume token ends the old session even when its connection
|
|
334
|
+
* is still alive, so two clients that shared an id and its token would end
|
|
335
|
+
* each other's sessions. And the token is a guard against colliding with a
|
|
336
|
+
* session the server has not yet seen end, not a secret: the wire carries no
|
|
337
|
+
* authentication, and a peer that learns the token can end the session.
|
|
338
|
+
*/
|
|
339
|
+
resumableSessions() {
|
|
340
|
+
let sessions = resumableByModelService.get(this.modelService);
|
|
341
|
+
if (!sessions) {
|
|
342
|
+
const created = new Map();
|
|
343
|
+
// Subscribed once per services tree, and never disposed: it lives as
|
|
344
|
+
// long as the text store it listens to.
|
|
345
|
+
this.services.workspace.TextDocuments.onDidCloseSession(event => created.delete(event.clientId));
|
|
346
|
+
resumableByModelService.set(this.modelService, created);
|
|
347
|
+
sessions = created;
|
|
348
|
+
}
|
|
349
|
+
return sessions;
|
|
350
|
+
}
|
|
351
|
+
async createModelDocument(args) {
|
|
352
|
+
const session = this.requireSession(args.clientId);
|
|
353
|
+
await session.create(args.uri, args.text);
|
|
354
|
+
return this.openedSnapshot(args.uri, () => session.close(args.uri));
|
|
355
|
+
}
|
|
356
|
+
async updateModelDocuments(args) {
|
|
357
|
+
const astDocuments = await this.requireSession(args.clientId).updateAll({
|
|
358
|
+
updates: args.updates.map(update => this.toSessionWrite(update))
|
|
359
|
+
});
|
|
360
|
+
return astDocuments.map(astDocument => this.encodeDocument(astDocument));
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* The session write a wire write request carries. Only the fields a session
|
|
364
|
+
* takes: a field an adopter adds to a request reaches the session only
|
|
365
|
+
* through an override of this.
|
|
366
|
+
*/
|
|
367
|
+
toSessionWrite(request) {
|
|
368
|
+
return { uri: request.uri, model: request.model, basedOn: request.basedOn };
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* The session this connection registered under `clientId`, which every
|
|
372
|
+
* document request acts as. An id that is not one fails with the
|
|
373
|
+
* closed-session code: opening or writing under it would leave an open that
|
|
374
|
+
* no session end ever closes.
|
|
375
|
+
*/
|
|
376
|
+
requireSession(clientId) {
|
|
377
|
+
const session = this.clientSessions.get(clientId);
|
|
378
|
+
if (!session) {
|
|
379
|
+
throw new SessionClosedError(clientId, 'The client session was never registered on this connection.');
|
|
380
|
+
}
|
|
381
|
+
return session;
|
|
382
|
+
}
|
|
383
|
+
async openModelDocument(args) {
|
|
384
|
+
const session = this.requireSession(args.clientId);
|
|
385
|
+
const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
|
|
386
|
+
await session.open(args.uri, args.options);
|
|
387
|
+
// A repeat open keeps the earlier one, which is still in use.
|
|
388
|
+
return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* The snapshot a session's open or create answers with. When the read
|
|
392
|
+
* fails, `rollback` undoes the open this call made before the failure is
|
|
393
|
+
* rethrown: the caller sees no open, so nothing on its side would ever close
|
|
394
|
+
* it.
|
|
366
395
|
*
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
*
|
|
396
|
+
* Versioned with the store's shared version rather than the snapshot's own:
|
|
397
|
+
* the built document's `textDocument.version` lags the store's whenever the
|
|
398
|
+
* store assigned the version, and the store's is what a write's `basedOn` is
|
|
399
|
+
* compared against, so reporting the snapshot's would make the caller's
|
|
400
|
+
* first based-on write conflict with itself.
|
|
370
401
|
*/
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
402
|
+
async openedSnapshot(uri, rollback) {
|
|
403
|
+
let document;
|
|
404
|
+
try {
|
|
405
|
+
document = await this.getModelDocument({ uri });
|
|
406
|
+
}
|
|
407
|
+
catch (error) {
|
|
408
|
+
// The open's failure is the one the caller needs, not the cleanup's.
|
|
409
|
+
await rollback?.().catch(() => undefined);
|
|
410
|
+
throw error;
|
|
378
411
|
}
|
|
412
|
+
return { ...document, version: asSnapshotVersion(this.services.workspace.TextDocuments.version(uri)) };
|
|
413
|
+
}
|
|
414
|
+
async closeModelDocument(args) {
|
|
415
|
+
// Through the handle, so a close under an ended session fails as that
|
|
416
|
+
// session's calls do, and a session class's own close is honoured.
|
|
417
|
+
const session = this.requireSession(args.clientId);
|
|
418
|
+
// Closing also releases the watch for (uri, clientId) — a forgotten
|
|
419
|
+
// unwatch would otherwise leak phase-event dispatch until the connection
|
|
420
|
+
// closes. Idempotent: a close without a prior watch is a no-op.
|
|
421
|
+
await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
|
|
422
|
+
await session.close(args.uri);
|
|
379
423
|
}
|
|
380
424
|
async getModelDocument(args) {
|
|
381
425
|
// Smart dispatch: a warm document (already in LangiumDocuments) is
|
|
@@ -390,71 +434,78 @@ export class DataServer {
|
|
|
390
434
|
// `includeDiagnostics: true` to settle at `Validated` instead.
|
|
391
435
|
const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
|
|
392
436
|
const astDocument = await this.modelService.ensureDocumentState(args.uri, state);
|
|
393
|
-
return this.
|
|
437
|
+
return this.encodeDocument(astDocument);
|
|
394
438
|
}
|
|
395
439
|
async updateModelDocument(args) {
|
|
396
|
-
const astDocument = await this.
|
|
397
|
-
return this.
|
|
440
|
+
const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
|
|
441
|
+
return this.encodeDocument(astDocument);
|
|
398
442
|
}
|
|
399
443
|
async saveModelDocument(args) {
|
|
400
|
-
const astDocument = await this.
|
|
401
|
-
return this.
|
|
444
|
+
const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
|
|
445
|
+
return this.encodeDocument(astDocument);
|
|
402
446
|
}
|
|
403
447
|
/**
|
|
404
448
|
* Record a watch for `(uri, clientId)`. Subsequent phase events on `uri`
|
|
405
449
|
* fan out to the wired `clientProxy.onDocumentUpdated`. The
|
|
406
450
|
* bidirectional pattern means the event channel is the client
|
|
407
451
|
* notification surface, not a returned handle — this method only
|
|
408
|
-
* registers the
|
|
452
|
+
* registers the watcher in {@link uriWatchRecords}.
|
|
409
453
|
*
|
|
410
|
-
* Also baselines the
|
|
411
|
-
* {@link
|
|
412
|
-
*
|
|
413
|
-
*
|
|
414
|
-
*
|
|
415
|
-
*
|
|
416
|
-
* redundant phase notification for that same state.
|
|
454
|
+
* Also baselines the URI's emission fingerprint (see
|
|
455
|
+
* {@link dispatchPhaseEvent}) to the document's current state when the
|
|
456
|
+
* first watcher for the URI registers. This guarantees that any phase event firing immediately after
|
|
457
|
+
* the watch with no observable change is suppressed — watchers obtain
|
|
458
|
+
* initial state via `getModelDocument` (or {@link openModelDocument}) and
|
|
459
|
+
* do not need a redundant phase notification for that same state.
|
|
417
460
|
*/
|
|
418
461
|
async watchModelDocument(args) {
|
|
419
462
|
const uri = this.canonicalKey(args.uri);
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
}
|
|
425
|
-
subscribers.add(args.clientId);
|
|
426
|
-
if (!this.lastEmittedFingerprint.has(uri)) {
|
|
463
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set() };
|
|
464
|
+
this.uriWatchRecords.set(uri, record);
|
|
465
|
+
record.watchers.add(args.clientId);
|
|
466
|
+
if (record.fingerprint === undefined) {
|
|
427
467
|
const document = this.services.workspace.LangiumDocuments.getDocument(UriUtils.toUri(uri));
|
|
428
468
|
if (document) {
|
|
429
|
-
|
|
469
|
+
record.fingerprint = this.computeDocumentFingerprint(document);
|
|
430
470
|
}
|
|
431
471
|
}
|
|
432
472
|
}
|
|
433
473
|
/**
|
|
434
474
|
* Remove a watch for `(uri, clientId)` previously created by
|
|
435
475
|
* {@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.
|
|
476
|
+
* Dispatch for `uri` stops once no watchers remain, and the emission
|
|
477
|
+
* fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
|
|
440
478
|
*/
|
|
441
479
|
async unwatchModelDocument(args) {
|
|
442
480
|
const uri = this.canonicalKey(args.uri);
|
|
443
|
-
|
|
444
|
-
|
|
481
|
+
if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
|
|
482
|
+
this.pruneUriWatchRecord(uri);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Drop what `uri` no longer needs: the
|
|
487
|
+
* {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
|
|
488
|
+
* and the whole record once it holds no
|
|
489
|
+
* {@link DataServerUriWatchRecord.revertPending} mark either. Every path
|
|
490
|
+
* that removes a watcher or consumes a mark ends here.
|
|
491
|
+
*/
|
|
492
|
+
pruneUriWatchRecord(uri) {
|
|
493
|
+
const record = this.uriWatchRecords.get(uri);
|
|
494
|
+
if (!record || record.watchers.size > 0) {
|
|
445
495
|
return;
|
|
446
496
|
}
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
497
|
+
if (record.revertPending) {
|
|
498
|
+
record.fingerprint = undefined;
|
|
499
|
+
}
|
|
500
|
+
else {
|
|
501
|
+
this.uriWatchRecords.delete(uri);
|
|
451
502
|
}
|
|
452
503
|
}
|
|
453
504
|
/**
|
|
454
|
-
* Canonicalise a URI string for use as a
|
|
455
|
-
*
|
|
456
|
-
*
|
|
457
|
-
*
|
|
505
|
+
* Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
|
|
506
|
+
* shared `DocumentUriPolicy`. Callers may send non-canonical URIs
|
|
507
|
+
* (drive-letter casing, percent-encoding differences, or a symlink path)
|
|
508
|
+
* over the wire; the dispatch side keys by
|
|
458
509
|
* `document.uri.toString()` from `LangiumDocuments`, so writer keys must
|
|
459
510
|
* canonicalise to the same form or events silently fail to deliver.
|
|
460
511
|
* Routing through the seam (rather than a bare `UriUtils.normalize`)
|
|
@@ -498,20 +549,50 @@ export class DataServer {
|
|
|
498
549
|
// Resolve the language's reference services from each request's source
|
|
499
550
|
// (see resolveReferenceServices) and delegate.
|
|
500
551
|
// ============================================================
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
552
|
+
/**
|
|
553
|
+
* Settle the build before a reference question is answered from the index.
|
|
554
|
+
*
|
|
555
|
+
* A query issued right after a model update otherwise races the rebuild and
|
|
556
|
+
* reads an index missing the symbols it asks about. The cost is not confined
|
|
557
|
+
* to this call: a scope built inside that window is cached, and the build's
|
|
558
|
+
* remaining documents link against it.
|
|
559
|
+
*
|
|
560
|
+
* Waits the source document specifically, but ONLY when one is loaded at
|
|
561
|
+
* that URI: a synthetic source can address a URI with no document (a
|
|
562
|
+
* directory URI, typically), where a per-URI `waitUntil` throws "No document
|
|
563
|
+
* found". Falls back to a global settle, matching the id-based
|
|
564
|
+
* `ElementSource` path.
|
|
565
|
+
*
|
|
566
|
+
* Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
567
|
+
*/
|
|
568
|
+
async awaitReferencesLinked(source) {
|
|
569
|
+
const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
|
|
510
570
|
const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
|
|
511
|
-
|
|
571
|
+
const stopwatch = this.services.Clock.stopwatch();
|
|
572
|
+
const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
|
|
573
|
+
if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const elapsedMs = Math.round(stopwatch.elapsedMs);
|
|
577
|
+
// A per-URI wait resolves off a document-phase notification, so a
|
|
578
|
+
// missed one strands a wait on a document that HAS reached the
|
|
579
|
+
// phase. Re-read before failing; the workspace-wide wait has no
|
|
580
|
+
// equivalent reading and can only reject.
|
|
581
|
+
const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
|
|
582
|
+
if (waitUri && document && document.state >= DocumentState.Linked) {
|
|
583
|
+
this.tracer
|
|
584
|
+
.withUri(waitUri.toString())
|
|
585
|
+
.warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
throw referenceSettleTimeoutError(elapsedMs);
|
|
589
|
+
}
|
|
590
|
+
async findReferenceCandidates(ctx) {
|
|
591
|
+
await this.awaitReferencesLinked(ctx.source);
|
|
512
592
|
return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
|
|
513
593
|
}
|
|
514
594
|
async resolveReference(ref) {
|
|
595
|
+
await this.awaitReferencesLinked(ref.source);
|
|
515
596
|
const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
|
|
516
597
|
if (!resolved) {
|
|
517
598
|
return undefined;
|
|
@@ -526,7 +607,14 @@ export class DataServer {
|
|
|
526
607
|
// synthetic source — and the create-element flow driving this method is
|
|
527
608
|
// the one that produces directory URIs, on which a bare
|
|
528
609
|
// `getServices(uri)` throws while `findReferenceCandidates` succeeds.
|
|
529
|
-
const
|
|
610
|
+
const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
|
|
611
|
+
// Mid-rebuild the names of documents not yet re-indexed are absent from
|
|
612
|
+
// the taken set, and the caller PERSISTS what it is handed. Nothing
|
|
613
|
+
// reserves the answer either, so a name is free of the collisions the
|
|
614
|
+
// index knows about and of nothing else — two callers racing get the same
|
|
615
|
+
// proposal, which only uniqueness at the write can catch.
|
|
616
|
+
await this.awaitReferencesLinked(source);
|
|
617
|
+
const nameProvider = this.resolveReferenceServices(source).NameProvider;
|
|
530
618
|
const tier = args.tier ?? 'project';
|
|
531
619
|
if (tier === 'public') {
|
|
532
620
|
return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
|
|
@@ -569,6 +657,9 @@ export class DataServer {
|
|
|
569
657
|
/**
|
|
570
658
|
* Pick the language that owns a reference source, in order:
|
|
571
659
|
*
|
|
660
|
+
* 0. A {@link isSyntheticSource} naming its own `language` routes there.
|
|
661
|
+
* First because every step below infers, and an inference must not
|
|
662
|
+
* override a caller that has said which grammar it means.
|
|
572
663
|
* 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
|
|
573
664
|
* whose URI resolves to a registered language routes by URI.
|
|
574
665
|
* 2. A single-language workspace always routes to that one language — so
|
|
@@ -587,6 +678,15 @@ export class DataServer {
|
|
|
587
678
|
*/
|
|
588
679
|
resolveReferenceLanguage(source) {
|
|
589
680
|
const registry = this.services.ServiceRegistry;
|
|
681
|
+
if (isSyntheticSource(source) && source.language !== undefined) {
|
|
682
|
+
const declared = registry.getServicesById(source.language);
|
|
683
|
+
if (declared) {
|
|
684
|
+
return declared;
|
|
685
|
+
}
|
|
686
|
+
// Falling through on an UNREGISTERED id rather than failing: the id
|
|
687
|
+
// crosses the wire, so a client built against a head with one more
|
|
688
|
+
// grammar would otherwise lose queries the steps below can answer.
|
|
689
|
+
}
|
|
590
690
|
// `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
|
|
591
691
|
// an extensionless / unregistered URI falls through to the steps below
|
|
592
692
|
// rather than throwing "no services for the extension ''".
|
|
@@ -698,14 +798,26 @@ export class DataServer {
|
|
|
698
798
|
// decides policy at its own layer; `root` is optional on the envelope
|
|
699
799
|
// so the compiler forces that decision. Adopters preferring to throw
|
|
700
800
|
// override `envelope`.
|
|
701
|
-
return
|
|
702
|
-
uri: uri.toString(),
|
|
703
|
-
version: 0,
|
|
704
|
-
root: undefined,
|
|
705
|
-
diagnostics: []
|
|
706
|
-
};
|
|
801
|
+
return TransferDocument.absent(uri.toString());
|
|
707
802
|
}
|
|
708
|
-
return this.encoder.toTransferDocument(document);
|
|
803
|
+
return this.withDirtyState(this.encoder.toTransferDocument(document));
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* The transfer document a request answers with for `astDocument`, the
|
|
807
|
+
* store's current `dirty` stamped on it by {@link withDirtyState}. Every
|
|
808
|
+
* document a request answers with goes through here, so none goes out
|
|
809
|
+
* without the stamp.
|
|
810
|
+
*/
|
|
811
|
+
encodeDocument(astDocument) {
|
|
812
|
+
return this.withDirtyState(this.encoder.astDocumentToTransferDocument(astDocument));
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* `document` with the store's current {@link TransferDocument.dirty}. Read
|
|
816
|
+
* when the document is sent rather than kept with the build: a save changes
|
|
817
|
+
* the answer without a rebuild.
|
|
818
|
+
*/
|
|
819
|
+
withDirtyState(document) {
|
|
820
|
+
return { ...document, dirty: this.services.workspace.TextDocuments.isDirty(document.uri) };
|
|
709
821
|
}
|
|
710
822
|
/**
|
|
711
823
|
* Subscribe one listener at the configured {@link DataServerOptions.subscriptionPhase}.
|
|
@@ -715,6 +827,56 @@ export class DataServer {
|
|
|
715
827
|
*/
|
|
716
828
|
subscribeToDocumentBuilder() {
|
|
717
829
|
this.disposables.push(this.services.workspace.DocumentBuilder.onDocumentPhase(this.options.subscriptionPhase, (document, cancelToken) => this.dispatchPhaseEvent(document, cancelToken)));
|
|
830
|
+
// The BUILD-phase hook, not the per-document one: this notification is one
|
|
831
|
+
// message per build rather than one per document, and Langium hands the
|
|
832
|
+
// whole batch over here. It also does not fire for a cancelled build,
|
|
833
|
+
// which is what the per-document dispatch has to check by hand.
|
|
834
|
+
this.disposables.push(this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built)));
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Report the documents that reached {@link DataServerOptions.subscriptionPhase}
|
|
838
|
+
* and that NOBODY on this
|
|
839
|
+
* connection is watching — the ones a client was not told about through
|
|
840
|
+
* {@link dispatchPhaseEvent}, which is gated per URI.
|
|
841
|
+
*
|
|
842
|
+
* **The gap this closes is the one no other source can observe.** A document
|
|
843
|
+
* the client watches, it hears about already. A file changed on disk, the
|
|
844
|
+
* host's own filesystem watcher reports — and on a browser host, where the
|
|
845
|
+
* workspace lives behind this head, an external change cannot happen at all.
|
|
846
|
+
* What is left, and what nothing outside the server can see, is a document
|
|
847
|
+
* rebuilt because something it DEPENDS ON changed: its file never changed, so
|
|
848
|
+
* a filesystem watcher is silent by construction, and it has no subscriber, so
|
|
849
|
+
* the update channel is silent by design. A consumer displaying data derived
|
|
850
|
+
* from that document — a tree label, a decorator — otherwise goes stale with
|
|
851
|
+
* no signal from any source, and repairs itself the moment someone opens the
|
|
852
|
+
* file to investigate, which is what makes it expensive to diagnose later.
|
|
853
|
+
*
|
|
854
|
+
* Payload-free on purpose: URIs only, so a client re-reads what it displays
|
|
855
|
+
* rather than being handed transfer documents it did not ask for. That is the
|
|
856
|
+
* property the watcher gate protects, and it is preserved here by
|
|
857
|
+
* carrying no document rather than by gating the message.
|
|
858
|
+
*
|
|
859
|
+
* Quiet in the common case. Editing a document that an editor has open leaves
|
|
860
|
+
* that URI watched and therefore out of this set, so a build with no
|
|
861
|
+
* dependents produces nothing at all, and workspace initialisation produces
|
|
862
|
+
* nothing because it does not build to this phase. The ceiling is a
|
|
863
|
+
* whole-workspace rebuild at the subscription phase: one message, URIs only.
|
|
864
|
+
*
|
|
865
|
+
* The URI is canonicalised for the same reason {@link uriWatchRecords} is keyed
|
|
866
|
+
* that way, and is untested for the same reason as its twin in
|
|
867
|
+
* {@link dispatchDeleteEvents}: the builder reports URIs out of its own
|
|
868
|
+
* store, so a non-canonical one cannot be produced without a fixture
|
|
869
|
+
* asserting a shape the real system never emits.
|
|
870
|
+
*/
|
|
871
|
+
dispatchBuiltEvent(built) {
|
|
872
|
+
const uris = built
|
|
873
|
+
.map(document => this.canonicalKey(document.uri.toString()))
|
|
874
|
+
.filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
|
|
875
|
+
if (uris.length === 0) {
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
|
|
879
|
+
this.clientProxy.onDocumentsBuilt({ uris });
|
|
718
880
|
}
|
|
719
881
|
/**
|
|
720
882
|
* Subscribe to the universal save event on `HydraniumTextDocuments` so a
|
|
@@ -733,29 +895,107 @@ export class DataServer {
|
|
|
733
895
|
subscribeToTextDocumentSaves() {
|
|
734
896
|
this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
|
|
735
897
|
}
|
|
898
|
+
/** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
|
|
899
|
+
subscribeToDirtyChanges() {
|
|
900
|
+
this.disposables.push(this.services.workspace.TextDocuments.onDidChangeDirty(event => this.dispatchDirtyEvent(event)));
|
|
901
|
+
}
|
|
736
902
|
/**
|
|
737
|
-
*
|
|
738
|
-
* {@link
|
|
739
|
-
*
|
|
740
|
-
|
|
903
|
+
* Send a dirty flip to the connection, gated on the URI's watchers as
|
|
904
|
+
* {@link dispatchSaveEvent} is: the answer at any one moment travels on
|
|
905
|
+
* every document sent, so a client that watches nothing reads it there.
|
|
906
|
+
*/
|
|
907
|
+
dispatchDirtyEvent(event) {
|
|
908
|
+
const uri = this.canonicalKey(event.uri);
|
|
909
|
+
if (this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
910
|
+
this.clientProxy.onDocumentDirtyChanged({ uri, dirty: event.dirty });
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Mark each document the store releases after its last close, so
|
|
915
|
+
* {@link dispatchPhaseEvent} broadcasts the following rebuild even without
|
|
916
|
+
* a watcher. The store rebuilds such a document from its disk content,
|
|
917
|
+
* discarding unsaved in-session edits, and the last close typically also
|
|
918
|
+
* removed the last watcher: without the broadcast, a consumer that only
|
|
919
|
+
* ever fetches via `getModelDocument` keeps showing the discarded state.
|
|
920
|
+
* The broadcast is de-duplicated against the fingerprint while a watcher
|
|
921
|
+
* holds one, so a close whose disk state equals the last emitted state
|
|
922
|
+
* stays silent; with no watcher there is no fingerprint, and every revert
|
|
923
|
+
* is sent.
|
|
924
|
+
*
|
|
925
|
+
* A release, not the close itself: a document whose last client lost its
|
|
926
|
+
* connection is released only once the revert grace runs out, or when
|
|
927
|
+
* another client opens it meanwhile, and not at all when a client lost
|
|
928
|
+
* from it opens it again within its own grace.
|
|
741
929
|
*/
|
|
742
930
|
subscribeToTextDocumentCloses() {
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
931
|
+
this.disposables.push(this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
|
|
932
|
+
const uri = this.canonicalKey(event.uri);
|
|
933
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set() };
|
|
934
|
+
record.revertPending = true;
|
|
935
|
+
this.uriWatchRecords.set(uri, record);
|
|
748
936
|
}));
|
|
749
937
|
}
|
|
750
|
-
/**
|
|
938
|
+
/**
|
|
939
|
+
* Fan out a deletion for each removed URI, to EVERY client on the connection
|
|
940
|
+
* rather than only to the ones watching that URI.
|
|
941
|
+
*
|
|
942
|
+
* **Deliberately ungated, where {@link dispatchPhaseEvent} and
|
|
943
|
+
* {@link dispatchSaveEvent} are gated.** Those two carry a built document and
|
|
944
|
+
* fire on every build, so the watcher gate is what keeps bandwidth
|
|
945
|
+
* proportional to what a client asked for. A deletion is neither: it is one
|
|
946
|
+
* URI, it is rare, and it reports the workspace's STRUCTURE rather than a
|
|
947
|
+
* document's content. Gating it forces any consumer that displays the
|
|
948
|
+
* workspace — a model tree, a file decorator — to learn about disappearances
|
|
949
|
+
* from a filesystem watcher instead, which a client hosted in a browser has
|
|
950
|
+
* no way to run: its workspace lives behind the head. A client that does not
|
|
951
|
+
* care filters on the URI, which costs it a comparison.
|
|
952
|
+
*
|
|
953
|
+
* The precedent is the last-close revert broadcast (see
|
|
954
|
+
* {@link subscribeToTextDocumentCloses}), where the same judgement was already made
|
|
955
|
+
* in the other direction: a transition that matters enough is delivered
|
|
956
|
+
* without a subscription.
|
|
957
|
+
*
|
|
958
|
+
* Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
|
|
959
|
+
* listener, which is the only place a deletion is observable: `update`
|
|
960
|
+
* removes the document before deriving the rebuild set, so it is never built.
|
|
961
|
+
* That ordering also puts this notification ahead of the `'rebuilt'` events
|
|
962
|
+
* for the dependents whose references the deletion just broke.
|
|
963
|
+
*
|
|
964
|
+
* The `deleted` list arrives already expanded to concrete document URIs —
|
|
965
|
+
* `deleteDocuments` resolves a directory URI to the documents beneath it — so
|
|
966
|
+
* no caller has to handle a directory here.
|
|
967
|
+
*
|
|
968
|
+
* The URI's fingerprint and revert mark are dropped: they describe a
|
|
969
|
+
* document that no longer exists. A kept fingerprint is adopted as the
|
|
970
|
+
* baseline and suppresses the first emit after the file returns with its
|
|
971
|
+
* previous content.
|
|
972
|
+
*
|
|
973
|
+
* The watchers SURVIVE: a recreated file resumes delivering to them with no
|
|
974
|
+
* re-subscription, and a client that answers the deletion by closing
|
|
975
|
+
* releases the watch through `closeModelDocument` anyway.
|
|
976
|
+
*/
|
|
977
|
+
dispatchDeleteEvents(deleted) {
|
|
978
|
+
for (const removed of deleted) {
|
|
979
|
+
const uri = this.canonicalKey(removed.toString());
|
|
980
|
+
const record = this.uriWatchRecords.get(uri);
|
|
981
|
+
if (record) {
|
|
982
|
+
record.fingerprint = undefined;
|
|
983
|
+
record.revertPending = undefined;
|
|
984
|
+
record.sentVersion = undefined;
|
|
985
|
+
this.pruneUriWatchRecord(uri);
|
|
986
|
+
}
|
|
987
|
+
this.clientProxy.onDocumentDeleted({ uri });
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
/** Fan out a save event for the document's URI, gated on the URI's watchers. */
|
|
751
991
|
dispatchSaveEvent(event) {
|
|
752
992
|
// The save event arrives under the CLIENT URI the text store keys by (e.g. a
|
|
753
|
-
// symlink path S);
|
|
993
|
+
// symlink path S); `uriWatchRecords` and `dispatchPhaseEvent` key by the
|
|
754
994
|
// CANONICAL identity R. Canonicalize before both the gate and the envelope so
|
|
755
995
|
// a save of a symlinked file isn't silently dropped (and the envelope resolves
|
|
756
996
|
// the R-keyed document rather than missing into an empty one).
|
|
757
997
|
const uri = this.canonicalKey(event.document.uri);
|
|
758
|
-
if (!this.
|
|
998
|
+
if (!this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
759
999
|
return;
|
|
760
1000
|
}
|
|
761
1001
|
const response = this.envelope(UriUtils.toUri(uri));
|
|
@@ -774,13 +1014,25 @@ export class DataServer {
|
|
|
774
1014
|
* out to multiple local subscribers with an `Emitter<T>` — the
|
|
775
1015
|
* framework deliberately does NOT promise multi-listener semantics.
|
|
776
1016
|
*
|
|
777
|
-
*
|
|
778
|
-
*
|
|
779
|
-
*
|
|
780
|
-
*
|
|
781
|
-
*
|
|
782
|
-
*
|
|
783
|
-
*
|
|
1017
|
+
* An event for a URI no client watches is NOT sent over the wire, so
|
|
1018
|
+
* bandwidth scales with watched URIs rather than with phase events; a
|
|
1019
|
+
* pending revert mark is the exception (see
|
|
1020
|
+
* {@link subscribeToTextDocumentCloses}).
|
|
1021
|
+
*
|
|
1022
|
+
* An event for a rebuild with no observable change since the last emit is
|
|
1023
|
+
* suppressed against the URI's fingerprint. Such rebuilds are routine: a
|
|
1024
|
+
* second client attaching to an open document makes
|
|
1025
|
+
* `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
|
|
1026
|
+
* to re-trigger the build, and Langium rebuilds a document when a
|
|
1027
|
+
* dependency changes even if its diagnostics come out the same. Sent at a
|
|
1028
|
+
* version this head has not sent, they reach watchers as `'changed'`, and a
|
|
1029
|
+
* watcher that reads `'changed'` as another client's write and resets its
|
|
1030
|
+
* root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
|
|
1031
|
+
* fingerprint, so the first event after a watch is de-duplicated against
|
|
1032
|
+
* the state the watcher just fetched; it goes with the last watcher, so the
|
|
1033
|
+
* next first watch re-baselines rather than adopting a stale digest. A
|
|
1034
|
+
* cyrb53 digest keeps its memory constant in document size; see
|
|
1035
|
+
* {@link computeDocumentFingerprint} for the inputs.
|
|
784
1036
|
*/
|
|
785
1037
|
dispatchPhaseEvent(document, cancelToken) {
|
|
786
1038
|
if (cancelToken.isCancellationRequested) {
|
|
@@ -792,16 +1044,23 @@ export class DataServer {
|
|
|
792
1044
|
return;
|
|
793
1045
|
}
|
|
794
1046
|
const uri = document.uri.toString();
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
// the author lookup would yield.
|
|
799
|
-
const revertedOnClose = this.pendingRevertBroadcasts.delete(uri);
|
|
800
|
-
if (!this.subscriptions.has(uri) && !revertedOnClose) {
|
|
1047
|
+
const record = this.uriWatchRecords.get(uri);
|
|
1048
|
+
const revertedOnClose = record?.revertPending === true;
|
|
1049
|
+
if (!record || (record.watchers.size === 0 && !revertedOnClose)) {
|
|
801
1050
|
return;
|
|
802
1051
|
}
|
|
1052
|
+
if (revertedOnClose) {
|
|
1053
|
+
// Consumed even when watchers exist — the regular dispatch below
|
|
1054
|
+
// serves them, and the mark's attribution is more precise than the
|
|
1055
|
+
// post-close unknown client the manager's attribution would yield.
|
|
1056
|
+
// With no watcher the record goes now, so the fingerprint written
|
|
1057
|
+
// below lands on a detached record and the next first watch
|
|
1058
|
+
// re-baselines instead of adopting it.
|
|
1059
|
+
record.revertPending = undefined;
|
|
1060
|
+
this.pruneUriWatchRecord(uri);
|
|
1061
|
+
}
|
|
803
1062
|
const fingerprint = this.computeDocumentFingerprint(document);
|
|
804
|
-
if (
|
|
1063
|
+
if (record.fingerprint === fingerprint) {
|
|
805
1064
|
// A rebuild that produced no observable change since the last emit —
|
|
806
1065
|
// suppressed so RPC subscribers don't see a no-op broadcast. Logged at
|
|
807
1066
|
// debug so a *needed* re-broadcast wrongly suppressed by this dedup
|
|
@@ -809,11 +1068,19 @@ export class DataServer {
|
|
|
809
1068
|
this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${document.textDocument.version}: fingerprint unchanged`);
|
|
810
1069
|
return;
|
|
811
1070
|
}
|
|
812
|
-
|
|
1071
|
+
record.fingerprint = fingerprint;
|
|
1072
|
+
// The manager's attribution, so this head names the same client as the
|
|
1073
|
+
// in-process heads do for one build, except for a version this head
|
|
1074
|
+
// already sent; see `DataServerUriWatchRecord.sentVersion`.
|
|
1075
|
+
const version = this.services.workspace.AstDocumentManager.isOpen(uri) ? document.textDocument.version : undefined;
|
|
1076
|
+
const { reason, sourceClientId } = version !== undefined && record.sentVersion === version
|
|
1077
|
+
? { reason: 'rebuilt', sourceClientId: UNKNOWN_CLIENT_ID }
|
|
1078
|
+
: this.services.workspace.AstDocumentManager.attributeUpdate(document);
|
|
1079
|
+
record.sentVersion = version;
|
|
813
1080
|
const event = {
|
|
814
1081
|
document: this.envelope(document.uri),
|
|
815
|
-
sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID :
|
|
816
|
-
reason
|
|
1082
|
+
sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID : sourceClientId,
|
|
1083
|
+
reason
|
|
817
1084
|
};
|
|
818
1085
|
this.tracer
|
|
819
1086
|
.withUri(uri)
|
|
@@ -852,30 +1119,6 @@ export class DataServer {
|
|
|
852
1119
|
additionalFingerprintInputs(_document) {
|
|
853
1120
|
return [];
|
|
854
1121
|
}
|
|
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';
|
|
878
|
-
}
|
|
879
1122
|
/**
|
|
880
1123
|
* Subscribe to the project tier's change channel and re-fan registry
|
|
881
1124
|
* diffs into per-project wire notifications. The internal
|
|
@@ -917,19 +1160,6 @@ export class DataServer {
|
|
|
917
1160
|
this.clientProxy.onProjectsChanged({ project: entry.snapshot, reason: 'removed' });
|
|
918
1161
|
}
|
|
919
1162
|
}
|
|
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
1163
|
// --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
|
|
934
1164
|
// Computed in THIS process: the data-server child holds the model store, so
|
|
935
1165
|
// these snapshots reflect the heap that actually carries the workspace
|
|
@@ -967,7 +1197,7 @@ export class DataServer {
|
|
|
967
1197
|
}
|
|
968
1198
|
async stopProfiling(args) {
|
|
969
1199
|
if (!this.activeProfile) {
|
|
970
|
-
throw
|
|
1200
|
+
throw noActiveProfileError();
|
|
971
1201
|
}
|
|
972
1202
|
const capture = this.activeProfile;
|
|
973
1203
|
this.activeProfile = undefined;
|
|
@@ -996,7 +1226,8 @@ export class DataServer {
|
|
|
996
1226
|
methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
|
|
997
1227
|
additionalMethods,
|
|
998
1228
|
excludedMethods: partial.excludedMethods ?? [],
|
|
999
|
-
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
|
|
1229
|
+
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
|
|
1230
|
+
referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
|
|
1000
1231
|
};
|
|
1001
1232
|
}
|
|
1002
1233
|
}
|