@hydranium/data-server 1.0.0-next.19 → 1.0.0-next.192

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.
@@ -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, 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 { REVERT_ON_CLOSE_CLIENT_ID, UNKNOWN_CLIENT_ID } from '@hydranium/core';
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
@@ -19,47 +51,31 @@ import { DocumentState, UriUtils } from '@hydranium/langium';
19
51
  */
20
52
  const FINGERPRINT_SEPARATOR = '\0';
21
53
  /**
22
- * Portable, non-cryptographic 64-bit fingerprint hash (cyrb53), returning a
23
- * 16-char hex digest.
24
- *
25
- * **A cryptographic hash via `node:crypto` is the wrong trade**: the
26
- * fingerprint only needs a stable signal that `(text, diagnostics)` changed
27
- * between emissions, and a `node:*` import would cost
28
- * `@hydranium/data-server` its browser-portability. Parts are fed
29
- * incrementally, char by char, so multi-MB document text is never
30
- * concatenated into one string.
54
+ * `LSPErrorCodes.ServerCancelled`, with which Langium's document wait rejects
55
+ * for a URI that has no document; `vscode-languageserver-protocol` is not a
56
+ * dependency of this package.
31
57
  */
32
- function fingerprintHash(parts) {
33
- let h1 = 0xdeadbeef;
34
- let h2 = 0x41c6ce57;
35
- for (const part of parts) {
36
- for (let i = 0; i < part.length; i++) {
37
- const ch = part.charCodeAt(i);
38
- h1 = Math.imul(h1 ^ ch, 2654435761);
39
- h2 = Math.imul(h2 ^ ch, 1597334677);
40
- }
41
- }
42
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
43
- h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
44
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
45
- h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
46
- const high = (h2 >>> 0).toString(16).padStart(8, '0');
47
- const low = (h1 >>> 0).toString(16).padStart(8, '0');
48
- return high + low;
49
- }
50
- /** Hash a document's raw text + diagnostics — the `'text-diagnostics'` strategy. */
51
- function textDiagnosticsFingerprint(document) {
52
- return fingerprintHash([document.textDocument.getText(), FINGERPRINT_SEPARATOR, JSON.stringify(document.diagnostics ?? [])]);
58
+ const SERVER_CANCELLED = -32802;
59
+ const resumableByModelService = new WeakMap();
60
+ /**
61
+ * Hash `text`, the text the model was parsed from, + `model`'s diagnostics — the `'text-diagnostics'` strategy.
62
+ * The text comes from the root's ledger record or CST, as the document's own may have moved on,
63
+ * and a repair in place leaves the CST on the unrepaired text;
64
+ * a root built without a CST hashes as `'transfer-document'`.
65
+ * Absent diagnostics must hash apart from `[]`, as in {@link transferDocumentFingerprint}.
66
+ */
67
+ function textDiagnosticsFingerprint(text, model) {
68
+ return text === undefined
69
+ ? transferDocumentFingerprint(model)
70
+ : textHash([text, FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
53
71
  }
54
- /** Hash an encoded transfer document's root + diagnostics — the `'transfer-document'` strategy. */
55
- function transferDocumentFingerprint(transferDocument) {
56
- // null, not undefined: `JSON.stringify(undefined)` yields undefined rather
57
- // than a string, putting a non-string into the hash inputs.
58
- return fingerprintHash([
59
- JSON.stringify(transferDocument.root ?? null),
60
- FINGERPRINT_SEPARATOR,
61
- JSON.stringify(transferDocument.diagnostics)
62
- ]);
72
+ /**
73
+ * Hash an encoded model's root + diagnostics — the `'transfer-document'` strategy.
74
+ * Absent diagnostics must hash apart from `[]`: a client skipping a render on an
75
+ * equal hash would otherwise miss a validation that found nothing.
76
+ */
77
+ function transferDocumentFingerprint(model) {
78
+ return textHash([JSON.stringify(model.root), FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
63
79
  }
64
80
  /**
65
81
  * `logAfterMs` threshold passed to {@link Tracer.time} around
@@ -90,13 +106,19 @@ const FINGERPRINT_LOG_AFTER_MS = 5;
90
106
  * adopters subclass ONLY when they need to decorate wire returns or
91
107
  * notifications. The usual adoption path is DI rebinds alone.
92
108
  *
109
+ * **`TTransfer` is not checked.** It declares the union of the transfer roots
110
+ * the workspace's languages produce. Which root a document has is known only
111
+ * at runtime, from its language, so a `TTransfer` missing a language compiles.
112
+ *
93
113
  * Lifecycle: the constructor registers framework request handlers (plus
94
114
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
95
115
  * builds the {@link DataClientProtocol} notification proxy on the same
96
116
  * connection in one {@link createRpcProxy} call (binding `this` as its
97
- * `localTarget`) under the configured namespace, and subscribes one
98
- * `DocumentBuilder.onDocumentPhase` listener per configured phase that
99
- * dispatches subscription events via `clientProxy.onDocumentUpdated`.
117
+ * `localTarget`) under the configured namespace, and subscribes two listeners
118
+ * at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
119
+ * per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
120
+ * `DocumentBuilder.onBuildPhase` one dispatching a single
121
+ * `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
100
122
  *
101
123
  * The data-server requires the full {@link ServerSharedServices}
102
124
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -121,85 +143,25 @@ export class DataServer {
121
143
  * extending rather than restate a value the framework may change.
122
144
  */
123
145
  static DEFAULT_OPTIONS = {
124
- subscriptionPhase: DocumentState.Validated
146
+ subscriptionPhase: DocumentState.Validated,
147
+ referenceSettleTimeoutMs: 60_000
125
148
  };
126
149
  options;
127
- /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
128
- subscriptions = new Map();
150
+ /** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
151
+ uriWatchRecords = new Map();
129
152
  /**
130
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
131
- * connection.
153
+ * The client sessions this connection registered, by client id. A document
154
+ * request carrying one of these ids acts as that session; one carrying any
155
+ * other id fails.
132
156
  *
133
- * Kept because the document store releases a client's hold only from an
134
- * explicit close, and a client that dies without closing would otherwise keep
135
- * the document open forever — resident, and with its last-close revert
136
- * suppressed. The store has no notion of which connection a clientId reached
137
- * it over, so the connection-scoped set has to live here; teaching it a client
138
- * identity is the more robust and much larger alternative.
139
- */
140
- openedDocuments = new Map();
157
+ * Entries stay after {@link dispose} has ended their sessions, so a request
158
+ * still running from before the connection closed reaches the ended handle
159
+ * and fails with the session's own error.
160
+ */
161
+ clientSessions = new Map();
141
162
  /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
142
163
  clientProxy;
143
164
  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
165
  tracer;
204
166
  /** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
205
167
  activeProfile;
@@ -211,11 +173,8 @@ export class DataServer {
211
173
  encoder;
212
174
  /**
213
175
  * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
214
- * The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
215
- * carry LSP-shape diagnostics in their AstDocument (e.g. an adopter's LSP-shape diagnostic type)
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`.
176
+ * Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
177
+ * {@link encoder} converts one into the other on the way out.
219
178
  */
220
179
  modelService;
221
180
  constructor(connection, services, options = {}) {
@@ -224,8 +183,7 @@ export class DataServer {
224
183
  this.options = this.resolveOptions(options);
225
184
  this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
226
185
  // DI-bound: adopters rebind `services.model.TransferEncoder` /
227
- // `services.model.ModelService` with their own subclasses. Slot types use the
228
- // framework upper bounds; the casts below narrow to this instance's generics.
186
+ // `services.model.ModelService` with their own subclasses.
229
187
  const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
230
188
  if (!encoder || !modelService) {
231
189
  throw new Error('DataServer requires `services.model.TransferEncoder` and `services.model.ModelService` to be bound. ' +
@@ -248,35 +206,42 @@ export class DataServer {
248
206
  methodNamespace: this.options.methodNamespace,
249
207
  localTarget: this,
250
208
  localMethods: registeredMethods,
251
- latency: this.latency
209
+ latency: this.latency,
210
+ // Bound at the chokepoint rather than per handler, so an adopter's
211
+ // `additionalMethods` are rendered on the same terms as the
212
+ // framework's own rejections.
213
+ renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
252
214
  });
253
- this.disposables.push(this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
254
- this.lastBuildUpdate = { changed, deleted };
255
- }));
215
+ this.disposables.push(this.services.workspace.DocumentBuilder.onUpdate((_changed, deleted) => this.dispatchDeleteEvents(deleted)));
256
216
  this.subscribeToDocumentBuilder();
257
217
  this.subscribeToTextDocumentSaves();
218
+ this.subscribeToDirtyChanges();
258
219
  this.subscribeToTextDocumentCloses();
259
220
  this.subscribeToProjectManager();
260
221
  // Self-register teardown so an adopter that keeps no reference to the
261
222
  // server still releases per-connection state, with no lifecycle hook of
262
- // its own. See `dispose`.
263
- this.disposables.push(connection.onClose(() => this.dispose()));
223
+ // its own. The client did not close anything itself, so its sessions end
224
+ // as lost and each document it was the last to have open waits out the
225
+ // store's revert grace. See `dispose`.
226
+ this.disposables.push(connection.onClose(() => this.dispose('lost')));
264
227
  }
265
228
  /**
266
229
  * Release everything the constructor wired up — the bound protocol
267
- * handlers and every listener — and clear the subscription map and the
268
- * per-URI emission-fingerprint cache, so a long-lived shared services
269
- * bundle does not retain per-connection memory after the connection
270
- * closes. Also closes every document still open over this connection (see
271
- * {@link closeOpenDocuments}), which is the SHARED store's state rather than
272
- * this server's and so outlives the connection unless released here.
230
+ * handlers and every listener — and clear {@link uriWatchRecords}, so a
231
+ * long-lived shared services bundle does not retain per-connection memory
232
+ * after the connection closes. Also ends every session this connection registered, which closes
233
+ * every document it has open: the SHARED store's state rather than this
234
+ * server's, which outlives the connection unless released here.
273
235
  *
274
- * Idempotent: subsequent calls are no-ops. Self-fires on
275
- * `connection.onClose` so adopters who don't hold a reference still
276
- * get per-connection cleanup; adopters that DO hold a reference may
277
- * call `dispose()` directly for early teardown.
236
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
237
+ * connection closes, so adopters who don't hold a reference still get
238
+ * per-connection cleanup; adopters that DO hold a reference may call
239
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
240
+ * `'closed'` reverts every document whose last open they close at once,
241
+ * and `'lost'`, the connection's own close, lets each wait out the revert
242
+ * grace.
278
243
  */
279
- dispose() {
244
+ dispose(cause = 'closed') {
280
245
  this.disposed = true;
281
246
  // Release an in-flight interactive capture so the process-wide inspector
282
247
  // singleton is not left active after the connection closes.
@@ -285,97 +250,155 @@ export class DataServer {
285
250
  this.activeProfile = undefined;
286
251
  void capture.stop({}).catch(() => undefined);
287
252
  }
288
- // AFTER `disposables.dispose()`, deliberately: closing a document fires
289
- // `onDidClose`, and this server's own close listener would otherwise mark a
290
- // revert broadcast for a connection that is already gone.
253
+ // AFTER `disposables.dispose()`, deliberately: ending a session releases
254
+ // each document it was the last to hold, and this server's own
255
+ // `onDidCloseLastOpen` listener would otherwise mark a revert broadcast
256
+ // for a connection that is already gone.
291
257
  this.disposables.dispose();
292
- this.closeOpenDocuments();
293
- this.subscriptions.clear();
294
- this.lastEmittedFingerprint.clear();
295
- this.pendingRevertBroadcasts.clear();
258
+ for (const [clientId, session] of this.clientSessions) {
259
+ this.endSession(clientId, session, cause);
260
+ }
261
+ this.uriWatchRecords.clear();
296
262
  }
297
263
  // ============================================================
298
- // DataServerProtocol implementation — delegates to ModelService.
264
+ // DataServerProtocol implementation
299
265
  // ============================================================
300
266
  //
301
- // The lifecycle methods (`get` / `update` / `save` / `ready`) forward
302
- // straight to `ModelService` and encode the returned `AstDocument` on
303
- // the wire boundary via `encoder.astDocumentToTransferDocument`.
304
- // Adopters customising lifecycle behaviour (normalisation, supersession,
305
- // settled-phase choice, etc.) override on the ModelService subclass —
306
- // no override on DataServer is needed.
307
- async openModelDocument(args) {
308
- // Register the editor session (idempotent — `ModelService.open` refreshes
309
- // an already-open document rather than re-opening), then return the built
310
- // state at the configured target phase. The one-shot snapshot; subsequent
311
- // build-phase events arrive via `watchModelDocument`.
312
- await this.modelService.open(args);
313
- // Record the hold so `dispose` can release it for a client that never
314
- // closes. Keyed by the URI as given, because that is what `close` takes.
315
- let holders = this.openedDocuments.get(args.uri);
316
- if (!holders) {
317
- holders = new Set();
318
- this.openedDocuments.set(args.uri, holders);
319
- }
320
- holders.add(args.clientId);
321
- const document = await this.getModelDocument({ uri: args.uri });
322
- // Project the authoritative client-facing version onto the open snapshot.
323
- // `getModelDocument` encodes the freshly-built AST snapshot, whose version
324
- // is the `LangiumDocument`'s own `textDocument.version`. That lags the
325
- // multi-client synced version whenever the open seeded the synced document
326
- // with a caller-supplied version id — and the synced version is what
327
- // `ModelService.update`'s optimistic-concurrency gate compares
328
- // `baseVersion` against, so reporting the snapshot's would make the
329
- // caller's first tagged write self-conflict. A genuine concurrent edit
330
- // still trips the gate and is reconciled by the caller's replay rather
331
- // than predicted here.
332
- return { ...document, version: this.services.workspace.TextDocuments.version(args.uri) };
333
- }
334
- async closeModelDocument(args) {
335
- // Closing a session also releases its watch for (uri, clientId) — a
336
- // forgotten unwatch would otherwise leak phase-event dispatch until the
337
- // connection closes. Idempotent: a close without a prior watch is a no-op.
338
- await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
339
- this.forgetOpenDocument(args.uri, args.clientId);
340
- await this.modelService.close(args);
267
+ // Reads go to `ModelService`; a request that opens or writes a document
268
+ // goes to the session this connection registered under its `clientId`.
269
+ // Each answer is encoded on the wire boundary via
270
+ // `encoder.astDocumentToTransferDocument`. To change how documents are
271
+ // read, override on the ModelService subclass; to change how they are
272
+ // written, on the session class the bound `ClientSessionFactory` builds.
273
+ async createSession(args) {
274
+ // After teardown nothing would ever end a session registered now, and its
275
+ // id would stay taken for the life of the process.
276
+ if (this.disposed) {
277
+ throw new SessionClosedError(args.clientId);
278
+ }
279
+ const resumable = this.resumableSessions();
280
+ const previous = resumable.get(args.clientId);
281
+ if (previous && args.resumeToken !== undefined && previous.token === args.resumeToken) {
282
+ previous.end();
283
+ }
284
+ const session = this.modelService.createSession(args.label, args.clientId);
285
+ this.clientSessions.set(args.clientId, session);
286
+ if (args.resumeToken !== undefined) {
287
+ // Taken over by a client registering again after its connection
288
+ // dropped, so the old session ends as lost: the documents it was the
289
+ // last to have open wait out the grace, and the new session's opens
290
+ // find their unsaved text.
291
+ resumable.set(args.clientId, { token: args.resumeToken, end: () => this.endSession(args.clientId, session, 'lost') });
292
+ }
341
293
  }
342
294
  /**
343
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
344
- * close it a second time. Idempotent.
295
+ * End a session this connection registered. The ended handle stays in
296
+ * {@link clientSessions}, as it does after {@link dispose}, so a request for
297
+ * the id still arriving fails with the ended session's own error.
345
298
  */
346
- forgetOpenDocument(uri, clientId) {
347
- const holders = this.openedDocuments.get(uri);
348
- if (!holders) {
349
- return;
299
+ async closeSession(args) {
300
+ const session = this.clientSessions.get(args.clientId);
301
+ if (session) {
302
+ this.endSession(args.clientId, session);
350
303
  }
351
- holders.delete(clientId);
352
- if (holders.size === 0) {
353
- this.openedDocuments.delete(uri);
304
+ }
305
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
306
+ endSession(clientId, session, cause = 'closed') {
307
+ for (const [uri, record] of this.uriWatchRecords) {
308
+ if (record.watchers.delete(clientId)) {
309
+ this.pruneUriWatchRecord(uri);
310
+ }
354
311
  }
312
+ session.dispose(cause);
355
313
  }
356
314
  /**
357
- * Close every document still open over this connection, for the clients that
358
- * opened it here.
359
- *
360
- * The document store releases a per-URI hold only from an explicit close, so
361
- * without this a client that dies mid-session keeps its documents open for the
362
- * lifetime of the process: `isOpenInAnyClient` stays true, the document stays
363
- * resident, and the last-close revert never runs. A long-lived multi-client
364
- * head is the configuration where a dead client is normal rather than
365
- * exceptional, so the leak accumulates there.
315
+ * The resumable sessions of this services tree, by client id, across all of
316
+ * its data connections: a client resumes on another connection than the one
317
+ * that registered it. An entry leaves when its session ends, by any path, so
318
+ * it keeps no ended connection alive.
366
319
  *
367
- * Runs from {@link dispose}, which is synchronous, so each close is fired and
368
- * its failure swallowed — a teardown must not reject, and a URI whose close
369
- * fails is no worse off than it was before this drain existed.
370
- */
371
- closeOpenDocuments() {
372
- const held = [...this.openedDocuments];
373
- this.openedDocuments.clear();
374
- for (const [uri, clientIds] of held) {
375
- for (const clientId of clientIds) {
376
- void Promise.resolve(this.modelService.close({ uri, clientId })).catch(() => undefined);
377
- }
320
+ * A takeover by resume token ends the old session even when its connection
321
+ * is still alive, so two clients that shared an id and its token would end
322
+ * each other's sessions. And the token is a guard against colliding with a
323
+ * session the server has not yet seen end, not a secret: the wire carries no
324
+ * authentication, and a peer that learns the token can end the session.
325
+ */
326
+ resumableSessions() {
327
+ let sessions = resumableByModelService.get(this.modelService);
328
+ if (!sessions) {
329
+ const created = new Map();
330
+ // Subscribed once per services tree, and never disposed: it lives as
331
+ // long as the text store it listens to.
332
+ this.services.workspace.TextDocuments.onDidCloseSession(event => created.delete(event.clientId));
333
+ resumableByModelService.set(this.modelService, created);
334
+ sessions = created;
335
+ }
336
+ return sessions;
337
+ }
338
+ async createModelDocument(args) {
339
+ const session = this.requireSession(args.clientId);
340
+ await session.create(args.uri, args.text);
341
+ return this.openedSnapshot(args.uri, () => session.close(args.uri));
342
+ }
343
+ async updateModelDocuments(args) {
344
+ const astDocuments = await this.requireSession(args.clientId).updateAll({
345
+ updates: args.updates.map(update => this.toSessionWrite(update))
346
+ });
347
+ return astDocuments.map(astDocument => this.encodeDocument(astDocument));
348
+ }
349
+ /**
350
+ * The session write a wire write request carries. Only the fields a session
351
+ * takes: a field an adopter adds to a request reaches the session only
352
+ * through an override of this.
353
+ */
354
+ toSessionWrite(request) {
355
+ return { uri: request.uri, model: request.model, baseVersion: request.baseVersion };
356
+ }
357
+ /**
358
+ * The session this connection registered under `clientId`, which every
359
+ * document request acts as. An id that is not one fails with the
360
+ * closed-session code: opening or writing under it would leave an open that
361
+ * no session end ever closes.
362
+ */
363
+ requireSession(clientId) {
364
+ const session = this.clientSessions.get(clientId);
365
+ if (!session) {
366
+ throw new SessionClosedError(clientId, 'The client session was never registered on this connection.');
378
367
  }
368
+ return session;
369
+ }
370
+ async openModelDocument(args) {
371
+ const session = this.requireSession(args.clientId);
372
+ const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
373
+ await session.open(args.uri, args.options);
374
+ // A repeat open keeps the earlier one, which is still in use.
375
+ return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
376
+ }
377
+ /**
378
+ * The snapshot a session's open or create answers with. When the read
379
+ * fails, `rollback` undoes the open this call made before the failure is
380
+ * rethrown: the caller sees no open, so nothing on its side would ever close
381
+ * it.
382
+ */
383
+ async openedSnapshot(uri, rollback) {
384
+ try {
385
+ return await this.getModelDocument({ uri });
386
+ }
387
+ catch (error) {
388
+ // The open's failure is the one the caller needs, not the cleanup's.
389
+ await rollback?.().catch(() => undefined);
390
+ throw error;
391
+ }
392
+ }
393
+ async closeModelDocument(args) {
394
+ // Through the handle, so a close under an ended session fails as that
395
+ // session's calls do, and a session class's own close is honoured.
396
+ const session = this.requireSession(args.clientId);
397
+ // Closing also releases the watch for (uri, clientId) — a forgotten
398
+ // unwatch would otherwise leak phase-event dispatch until the connection
399
+ // closes. Idempotent: a close without a prior watch is a no-op.
400
+ await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
401
+ await session.close(args.uri);
379
402
  }
380
403
  async getModelDocument(args) {
381
404
  // Smart dispatch: a warm document (already in LangiumDocuments) is
@@ -389,72 +412,90 @@ export class DataServer {
389
412
  // unsubscribed caller that needs diagnostics inline passes
390
413
  // `includeDiagnostics: true` to settle at `Validated` instead.
391
414
  const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
392
- const astDocument = await this.modelService.ensureDocumentState(args.uri, state);
393
- return this.encoder.astDocumentToTransferDocument(astDocument);
415
+ try {
416
+ return this.encodeDocument(await this.modelService.ensureDocumentState(args.uri, state));
417
+ }
418
+ catch (error) {
419
+ // The protocol answers a read of a URI with no document with an
420
+ // envelope that has no model.
421
+ if (this.isMissingDocument(error, args.uri)) {
422
+ return this.envelope(UriUtils.toUri(args.uri));
423
+ }
424
+ throw error;
425
+ }
394
426
  }
395
427
  async updateModelDocument(args) {
396
- const astDocument = await this.modelService.update(args);
397
- return this.encoder.astDocumentToTransferDocument(astDocument);
428
+ const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
429
+ return this.encodeDocument(astDocument);
398
430
  }
399
431
  async saveModelDocument(args) {
400
- const astDocument = await this.modelService.save(args);
401
- return this.encoder.astDocumentToTransferDocument(astDocument);
432
+ const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
433
+ return this.encodeDocument(astDocument);
402
434
  }
403
435
  /**
404
436
  * Record a watch for `(uri, clientId)`. Subsequent phase events on `uri`
405
437
  * fan out to the wired `clientProxy.onDocumentUpdated`. The
406
438
  * bidirectional pattern means the event channel is the client
407
439
  * notification surface, not a returned handle — this method only
408
- * registers the URI in the dispatch table.
440
+ * registers the watcher in {@link uriWatchRecords}.
409
441
  *
410
- * Also baselines the per-URI emission fingerprint (see
411
- * {@link lastEmittedFingerprint}) to the document's current state when
412
- * the first watcher for the URI registers. This guarantees that any
413
- * phase event firing immediately after the watch with no observable
414
- * change is suppressed — watchers obtain initial state via
415
- * `getModelDocument` (or {@link openModelDocument}) and do not need a
416
- * redundant phase notification for that same state.
442
+ * Also baselines the URI's emission fingerprint (see
443
+ * {@link dispatchPhaseEvent}) to the document's current state when the
444
+ * first watcher for the URI registers. This guarantees that any phase event firing immediately after
445
+ * the watch with no observable change is suppressed — watchers obtain
446
+ * initial state via `getModelDocument` (or {@link openModelDocument}) and
447
+ * do not need a redundant phase notification for that same state.
417
448
  */
418
449
  async watchModelDocument(args) {
419
450
  const uri = this.canonicalKey(args.uri);
420
- let subscribers = this.subscriptions.get(uri);
421
- if (!subscribers) {
422
- subscribers = new Set();
423
- this.subscriptions.set(uri, subscribers);
424
- }
425
- subscribers.add(args.clientId);
426
- if (!this.lastEmittedFingerprint.has(uri)) {
451
+ const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set() };
452
+ this.uriWatchRecords.set(uri, record);
453
+ record.watchers.add(args.clientId);
454
+ if (record.fingerprint === undefined) {
427
455
  const document = this.services.workspace.LangiumDocuments.getDocument(UriUtils.toUri(uri));
428
- if (document) {
429
- this.lastEmittedFingerprint.set(uri, this.computeDocumentFingerprint(document));
456
+ if (document && !this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
457
+ record.fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
458
+ record.fingerprintVersion = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
430
459
  }
431
460
  }
432
461
  }
433
462
  /**
434
463
  * Remove a watch for `(uri, clientId)` previously created by
435
464
  * {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
436
- * Dispatch for `uri` stops once no watchers remain, at which point the
437
- * per-URI emission fingerprint is also cleared so the next first-watch
438
- * re-baselines against the then-current document state rather than a
439
- * stale snapshot from the previous watch.
465
+ * Dispatch for `uri` stops once no watchers remain, and the emission
466
+ * fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
440
467
  */
441
468
  async unwatchModelDocument(args) {
442
469
  const uri = this.canonicalKey(args.uri);
443
- const subscribers = this.subscriptions.get(uri);
444
- if (!subscribers) {
470
+ if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
471
+ this.pruneUriWatchRecord(uri);
472
+ }
473
+ }
474
+ /**
475
+ * Drop what `uri` no longer needs: the
476
+ * {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
477
+ * and the whole record once it holds no
478
+ * {@link DataServerUriWatchRecord.revertPending} mark either. Every path
479
+ * that removes a watcher or consumes a mark ends here.
480
+ */
481
+ pruneUriWatchRecord(uri) {
482
+ const record = this.uriWatchRecords.get(uri);
483
+ if (!record || record.watchers.size > 0) {
445
484
  return;
446
485
  }
447
- subscribers.delete(args.clientId);
448
- if (subscribers.size === 0) {
449
- this.subscriptions.delete(uri);
450
- this.lastEmittedFingerprint.delete(uri);
486
+ if (record.revertPending) {
487
+ record.fingerprint = undefined;
488
+ record.fingerprintVersion = undefined;
489
+ }
490
+ else {
491
+ this.uriWatchRecords.delete(uri);
451
492
  }
452
493
  }
453
494
  /**
454
- * Canonicalise a URI string for use as a subscription / fingerprint
455
- * map key, via the shared `DocumentUriPolicy`. Callers may send
456
- * non-canonical URIs (drive-letter casing, percent-encoding differences,
457
- * or a symlink path) over the wire; the dispatch side keys by
495
+ * Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
496
+ * shared `DocumentUriPolicy`. Callers may send non-canonical URIs
497
+ * (drive-letter casing, percent-encoding differences, or a symlink path)
498
+ * over the wire; the dispatch side keys by
458
499
  * `document.uri.toString()` from `LangiumDocuments`, so writer keys must
459
500
  * canonicalise to the same form or events silently fail to deliver.
460
501
  * Routing through the seam (rather than a bare `UriUtils.normalize`)
@@ -498,26 +539,56 @@ export class DataServer {
498
539
  // Resolve the language's reference services from each request's source
499
540
  // (see resolveReferenceServices) and delegate.
500
541
  // ============================================================
501
- async findReferenceCandidates(ctx) {
502
- // Candidates are derived from resolved cross-references, so the relevant document(s) must
503
- // have finished the Linked phase — otherwise a query issued right after a model update races
504
- // the asynchronous rebuild and returns stale candidates. Wait the source document
505
- // specifically, but ONLY when a document is actually loaded at that URI: a synthetic source
506
- // can address a URI with no document (a directory URI, typically), and a per-URI `waitUntil`
507
- // there throws "No document found". Fall back to a global Linked settle, matching the
508
- // id-based ElementSource (no URI) path.
509
- const uri = isDocumentSource(ctx.source) || isSyntheticSource(ctx.source) ? UriUtils.toUri(ctx.source.uri) : undefined;
542
+ /**
543
+ * Settle the build before a reference question is answered from the index.
544
+ *
545
+ * A query issued right after a model update otherwise races the rebuild and
546
+ * reads an index missing the symbols it asks about. The cost is not confined
547
+ * to this call: a scope built inside that window is cached, and the build's
548
+ * remaining documents link against it.
549
+ *
550
+ * Waits the source document specifically, but ONLY when one is loaded at
551
+ * that URI: a synthetic source can address a URI with no document (a
552
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
553
+ * found". Falls back to a global settle, matching the id-based
554
+ * `ElementSource` path.
555
+ *
556
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
557
+ */
558
+ async awaitReferencesLinked(source) {
559
+ const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
510
560
  const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
511
- await this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
561
+ const stopwatch = this.services.Clock.stopwatch();
562
+ const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
563
+ if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
564
+ return;
565
+ }
566
+ const elapsedMs = Math.round(stopwatch.elapsedMs);
567
+ // A per-URI wait resolves off a document-phase notification, so a
568
+ // missed one strands a wait on a document that HAS reached the
569
+ // phase. Re-read before failing; the workspace-wide wait has no
570
+ // equivalent reading and can only reject.
571
+ const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
572
+ if (waitUri && document && document.state >= DocumentState.Linked) {
573
+ this.tracer
574
+ .withUri(waitUri.toString())
575
+ .warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
576
+ return;
577
+ }
578
+ throw referenceSettleTimeoutError(elapsedMs);
579
+ }
580
+ async findReferenceCandidates(ctx) {
581
+ await this.awaitReferencesLinked(ctx.source);
512
582
  return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
513
583
  }
514
584
  async resolveReference(ref) {
585
+ await this.awaitReferencesLinked(ref.source);
515
586
  const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
516
587
  if (!resolved) {
517
588
  return undefined;
518
589
  }
519
- const element = this.encoder.toTransfer(resolved.node);
520
- return { ...resolved.candidate, element };
590
+ // The caller's claim about the target's type; see `ReferenceServerProtocol.resolveReference`.
591
+ return { ...resolved.candidate, element: this.encoder.toTransfer(resolved.node) };
521
592
  }
522
593
  async findNextName(args) {
523
594
  const uri = UriUtils.toUri(args.uri);
@@ -526,15 +597,32 @@ export class DataServer {
526
597
  // synthetic source — and the create-element flow driving this method is
527
598
  // the one that produces directory URIs, on which a bare
528
599
  // `getServices(uri)` throws while `findReferenceCandidates` succeeds.
529
- const nameProvider = this.resolveReferenceServices(ReferenceSource.synthetic(args.uri, args.type)).NameProvider;
600
+ const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
601
+ // Mid-rebuild the names of documents not yet re-indexed are absent from
602
+ // the taken set, and the caller PERSISTS what it is handed. Nothing
603
+ // reserves the answer either, so a name is free of the collisions the
604
+ // index knows about and of nothing else — two callers racing get the same
605
+ // proposal, which only uniqueness at the write can catch.
606
+ await this.awaitReferencesLinked(source);
607
+ const nameProvider = this.resolveReferenceServices(source).NameProvider;
530
608
  const tier = args.tier ?? 'project';
531
609
  if (tier === 'public') {
532
610
  return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
533
611
  }
534
612
  if (tier === 'local') {
535
- // Document-scoped uniqueness: the document root is the container.
536
- const document = await this.modelService.ensureDocumentState(args.uri);
537
- return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
613
+ // Document-scoped uniqueness: the document root is the container. A
614
+ // URI with no document has nothing to collide with, like a document
615
+ // with no root.
616
+ try {
617
+ const document = await this.modelService.ensureDocumentState(args.uri);
618
+ return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
619
+ }
620
+ catch (error) {
621
+ if (this.isMissingDocument(error, args.uri)) {
622
+ return args.proposal;
623
+ }
624
+ throw error;
625
+ }
538
626
  }
539
627
  const project = this.services.workspace.ProjectManager.getProject(uri);
540
628
  if (!project) {
@@ -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 ''".
@@ -675,37 +775,78 @@ export class DataServer {
675
775
  // ============================================================
676
776
  // Internal plumbing
677
777
  // ============================================================
778
+ /**
779
+ * Whether `error`, from waiting on `uri`'s document, means that `uri` has
780
+ * no document: a URI with neither a file nor text builds nothing, and
781
+ * Langium's wait after the build rejects for want of one, with a
782
+ * `ServerCancelled` response error. Any other failure, such as a read
783
+ * that fails before a document is registered, a cancelled wait or a
784
+ * `ReentrantWriteLockError`, is the caller's to see.
785
+ */
786
+ isMissingDocument(error, uri) {
787
+ return error instanceof ResponseError && error.code === SERVER_CANCELLED && this.modelService.getDocument(uri) === undefined;
788
+ }
678
789
  /**
679
790
  * Build a {@link TransferDocument} envelope from the current document state,
680
791
  * delegating root + diagnostic encoding to {@link encoder} (see
681
- * `TransferEncoder.toTransferDocument` for the walk).
682
- *
683
- * The encoder field's generic-map binding is widened to
684
- * `Record<string, TransferElement>` at the framework-default level, and an
685
- * adopter supplying a typed-overlay encoder narrows the runtime shape to
686
- * its wire types. The cast on the return is where that invariant — the
687
- * adopter's `TTransfer` matches its encoder's overlay — is asserted, at a
688
- * single boundary point rather than spread across the callers.
689
- */
690
- envelope(uri) {
792
+ * `TransferEncoder.toTransferDocument` for the walk). `fingerprint` is the
793
+ * caller's {@link computeDocumentFingerprint} of that same state, which
794
+ * spares hashing it twice.
795
+ */
796
+ envelope(uri, fingerprint) {
691
797
  // Resolve through the model service's canonicalizing gateway rather than
692
798
  // reaching into `LangiumDocuments` directly, so a divergent (symlink) URI
693
799
  // still finds the document the build keys by its real path — and so the
694
800
  // data-server never has to remember to canonicalize this lookup itself.
695
801
  const document = this.modelService.getDocument(uri.toString());
696
- if (!document) {
802
+ if (!document || this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
697
803
  // No document — a shaped envelope rather than a throw, so the caller
698
- // decides policy at its own layer; `root` is optional on the envelope
804
+ // decides policy at its own layer; `model` is optional on the envelope
699
805
  // so the compiler forces that decision. Adopters preferring to throw
700
- // override `envelope`.
701
- return {
702
- uri: uri.toString(),
703
- version: 0,
704
- root: undefined,
705
- diagnostics: []
706
- };
806
+ // override `envelope`. The builder's unparsed placeholder is no
807
+ // document either: its root parses no text.
808
+ return TransferDocument.absent(uri.toString());
707
809
  }
708
- return this.encoder.toTransferDocument(document);
810
+ const encoded = this.encoder.toTransferDocument(document);
811
+ return this.withServerState(encoded, fingerprint ?? this.computeDocumentFingerprint(document.parseResult.value, encoded));
812
+ }
813
+ /**
814
+ * The transfer document a request answers with for `astDocument`, its model
815
+ * hashed and the text stamped on it by {@link withServerState}. Every
816
+ * document a request answers with goes through here, so none goes out
817
+ * without them.
818
+ */
819
+ encodeDocument(astDocument) {
820
+ const encoded = this.encoder.astDocumentToTransferDocument(astDocument);
821
+ return this.withServerState(encoded, this.computeDocumentFingerprint(astDocument.root, encoded));
822
+ }
823
+ /**
824
+ * `encoded` with `hash` on its model and the text the server holds for it:
825
+ * the store's while it holds the document, the build's otherwise. The text
826
+ * is read when the document is sent rather than kept with the build: a save
827
+ * changes `text.dirty` without a rebuild, and the store's text moves on before
828
+ * the build that follows it.
829
+ */
830
+ withServerState(encoded, hash) {
831
+ const text = this.services.workspace.TextDocuments.textState(encoded.uri) ?? this.builtTextState(encoded.uri);
832
+ if (text && text.version > encoded.model.version) {
833
+ this.tracer.withUri(encoded.uri).debug(`Send a model behind its text: model v${encoded.model.version} / text v${text.version}`);
834
+ }
835
+ return {
836
+ uri: encoded.uri,
837
+ // The encoder returns the structural base; `TTransfer` is the adopter's
838
+ // declaration of the roots its languages produce, and nothing checks it.
839
+ model: { ...encoded.model, hash },
840
+ ...(text ? { text } : {})
841
+ };
842
+ }
843
+ /**
844
+ * The text a build read for a document the store never held, which is
845
+ * clean: the store holds every text a client gave it.
846
+ */
847
+ builtTextState(uri) {
848
+ const textDocument = this.modelService.getDocument(uri)?.textDocument;
849
+ return textDocument && { version: textDocument.version, hash: textHash(textDocument.getText()), dirty: false };
709
850
  }
710
851
  /**
711
852
  * Subscribe one listener at the configured {@link DataServerOptions.subscriptionPhase}.
@@ -715,6 +856,56 @@ export class DataServer {
715
856
  */
716
857
  subscribeToDocumentBuilder() {
717
858
  this.disposables.push(this.services.workspace.DocumentBuilder.onDocumentPhase(this.options.subscriptionPhase, (document, cancelToken) => this.dispatchPhaseEvent(document, cancelToken)));
859
+ // The BUILD-phase hook, not the per-document one: this notification is one
860
+ // message per build rather than one per document, and Langium hands the
861
+ // whole batch over here. It also does not fire for a cancelled build,
862
+ // which is what the per-document dispatch has to check by hand.
863
+ this.disposables.push(this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built)));
864
+ }
865
+ /**
866
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
867
+ * and that NOBODY on this
868
+ * connection is watching — the ones a client was not told about through
869
+ * {@link dispatchPhaseEvent}, which is gated per URI.
870
+ *
871
+ * **The gap this closes is the one no other source can observe.** A document
872
+ * the client watches, it hears about already. A file changed on disk, the
873
+ * host's own filesystem watcher reports — and on a browser host, where the
874
+ * workspace lives behind this head, an external change cannot happen at all.
875
+ * What is left, and what nothing outside the server can see, is a document
876
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
877
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
878
+ * the update channel is silent by design. A consumer displaying data derived
879
+ * from that document — a tree label, a decorator — otherwise goes stale with
880
+ * no signal from any source, and repairs itself the moment someone opens the
881
+ * file to investigate, which is what makes it expensive to diagnose later.
882
+ *
883
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
884
+ * rather than being handed transfer documents it did not ask for. That is the
885
+ * property the watcher gate protects, and it is preserved here by
886
+ * carrying no document rather than by gating the message.
887
+ *
888
+ * Quiet in the common case. Editing a document that an editor has open leaves
889
+ * that URI watched and therefore out of this set, so a build with no
890
+ * dependents produces nothing at all, and workspace initialisation produces
891
+ * nothing because it does not build to this phase. The ceiling is a
892
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
893
+ *
894
+ * The URI is canonicalised for the same reason {@link uriWatchRecords} is keyed
895
+ * that way, and is untested for the same reason as its twin in
896
+ * {@link dispatchDeleteEvents}: the builder reports URIs out of its own
897
+ * store, so a non-canonical one cannot be produced without a fixture
898
+ * asserting a shape the real system never emits.
899
+ */
900
+ dispatchBuiltEvent(built) {
901
+ const uris = built
902
+ .map(document => this.canonicalKey(document.uri.toString()))
903
+ .filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
904
+ if (uris.length === 0) {
905
+ return;
906
+ }
907
+ this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
908
+ this.clientProxy.onDocumentsBuilt({ uris });
718
909
  }
719
910
  /**
720
911
  * Subscribe to the universal save event on `HydraniumTextDocuments` so a
@@ -733,29 +924,108 @@ export class DataServer {
733
924
  subscribeToTextDocumentSaves() {
734
925
  this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
735
926
  }
927
+ /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
928
+ subscribeToDirtyChanges() {
929
+ this.disposables.push(this.services.workspace.TextDocuments.onDidChangeDirty(event => this.dispatchDirtyEvent(event)));
930
+ }
736
931
  /**
737
- * Mark the last-close transition per URI (see
738
- * {@link pendingRevertBroadcasts}). The listener consults
739
- * `isOpenInAnyClient` AFTER the store decremented the closing client's
740
- * hold, so a `false` answer means this close was the last one.
932
+ * Send a dirty flip to the connection, gated on the URI's watchers as
933
+ * {@link dispatchSaveEvent} is: the answer at any one moment travels on
934
+ * every document sent, so a client that watches nothing reads it there.
935
+ */
936
+ dispatchDirtyEvent(event) {
937
+ const uri = this.canonicalKey(event.uri);
938
+ if (this.uriWatchRecords.get(uri)?.watchers.size) {
939
+ this.clientProxy.onDocumentDirtyChanged({ uri, text: event.text });
940
+ }
941
+ }
942
+ /**
943
+ * Mark each document the store releases after its last close, so
944
+ * {@link dispatchPhaseEvent} broadcasts the following rebuild even without
945
+ * a watcher. The store rebuilds such a document from its disk content,
946
+ * discarding unsaved in-session edits, and the last close typically also
947
+ * removed the last watcher: without the broadcast, a consumer that only
948
+ * ever fetches via `getModelDocument` keeps showing the discarded state.
949
+ * The broadcast is de-duplicated against the fingerprint while a watcher
950
+ * holds one, so a close whose disk state equals the last emitted state
951
+ * stays silent; with no watcher there is no fingerprint, and every revert
952
+ * is sent.
953
+ *
954
+ * A release, not the close itself: a document whose last client lost its
955
+ * connection is released only once the revert grace runs out, or when
956
+ * another client opens it meanwhile, and not at all when a client lost
957
+ * from it opens it again within its own grace.
741
958
  */
742
959
  subscribeToTextDocumentCloses() {
743
- const textDocuments = this.services.workspace.TextDocuments;
744
- this.disposables.push(textDocuments.onDidClose(event => {
745
- if (!textDocuments.isOpenInAnyClient(event.document.uri)) {
746
- this.pendingRevertBroadcasts.add(this.canonicalKey(event.document.uri));
747
- }
960
+ this.disposables.push(this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
961
+ const uri = this.canonicalKey(event.uri);
962
+ const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set() };
963
+ record.revertPending = true;
964
+ this.uriWatchRecords.set(uri, record);
748
965
  }));
749
966
  }
750
- /** Fan out a save event for the document's URI, gated by the subscription map. */
967
+ /**
968
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
969
+ * rather than only to the ones watching that URI.
970
+ *
971
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
972
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
973
+ * fire on every build, so the watcher gate is what keeps bandwidth
974
+ * proportional to what a client asked for. A deletion is neither: it is one
975
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
976
+ * document's content. Gating it forces any consumer that displays the
977
+ * workspace — a model tree, a file decorator — to learn about disappearances
978
+ * from a filesystem watcher instead, which a client hosted in a browser has
979
+ * no way to run: its workspace lives behind the head. A client that does not
980
+ * care filters on the URI, which costs it a comparison.
981
+ *
982
+ * The precedent is the last-close revert broadcast (see
983
+ * {@link subscribeToTextDocumentCloses}), where the same judgement was already made
984
+ * in the other direction: a transition that matters enough is delivered
985
+ * without a subscription.
986
+ *
987
+ * Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
988
+ * listener, which is the only place a deletion is observable: `update`
989
+ * removes the document before deriving the rebuild set, so it is never built.
990
+ * That ordering also puts this notification ahead of the `'rebuilt'` events
991
+ * for the dependents whose references the deletion just broke.
992
+ *
993
+ * The `deleted` list arrives already expanded to concrete document URIs —
994
+ * `deleteDocuments` resolves a directory URI to the documents beneath it — so
995
+ * no caller has to handle a directory here.
996
+ *
997
+ * The URI's fingerprint and revert mark are dropped: they describe a
998
+ * document that no longer exists. A kept fingerprint is adopted as the
999
+ * baseline and suppresses the first emit after the file returns with its
1000
+ * previous content.
1001
+ *
1002
+ * The watchers SURVIVE: a recreated file resumes delivering to them with no
1003
+ * re-subscription, and a client that answers the deletion by closing
1004
+ * releases the watch through `closeModelDocument` anyway.
1005
+ */
1006
+ dispatchDeleteEvents(deleted) {
1007
+ for (const removed of deleted) {
1008
+ const uri = this.canonicalKey(removed.toString());
1009
+ const record = this.uriWatchRecords.get(uri);
1010
+ if (record) {
1011
+ record.fingerprint = undefined;
1012
+ record.fingerprintVersion = undefined;
1013
+ record.revertPending = undefined;
1014
+ record.sentVersion = undefined;
1015
+ this.pruneUriWatchRecord(uri);
1016
+ }
1017
+ this.clientProxy.onDocumentDeleted({ uri });
1018
+ }
1019
+ }
1020
+ /** Fan out a save event for the document's URI, gated on the URI's watchers. */
751
1021
  dispatchSaveEvent(event) {
752
1022
  // The save event arrives under the CLIENT URI the text store keys by (e.g. a
753
- // symlink path S); the subscription map and `dispatchPhaseEvent` key by the
1023
+ // symlink path S); `uriWatchRecords` and `dispatchPhaseEvent` key by the
754
1024
  // CANONICAL identity R. Canonicalize before both the gate and the envelope so
755
1025
  // a save of a symlinked file isn't silently dropped (and the envelope resolves
756
1026
  // the R-keyed document rather than missing into an empty one).
757
1027
  const uri = this.canonicalKey(event.document.uri);
758
- if (!this.subscriptions.has(uri)) {
1028
+ if (!this.uriWatchRecords.get(uri)?.watchers.size) {
759
1029
  return;
760
1030
  }
761
1031
  const response = this.envelope(UriUtils.toUri(uri));
@@ -774,13 +1044,27 @@ export class DataServer {
774
1044
  * out to multiple local subscribers with an `Emitter<T>` — the
775
1045
  * framework deliberately does NOT promise multi-listener semantics.
776
1046
  *
777
- * The dispatch is guarded by two filters:
778
- * 1. **Subscription map**: events for URIs no subscriber registered for
779
- * are NOT sent over the wire (bandwidth scales with subscribed URIs,
780
- * not phase events).
781
- * 2. **Emission fingerprint**: events for rebuilds that produce no
782
- * observable change since the last emit are suppressed. See
783
- * {@link lastEmittedFingerprint} for the rationale.
1047
+ * An event for a URI no client watches is NOT sent over the wire, so
1048
+ * bandwidth scales with watched URIs rather than with phase events; a
1049
+ * pending revert mark is the exception (see
1050
+ * {@link subscribeToTextDocumentCloses}).
1051
+ *
1052
+ * An event for a rebuild with no observable change since the last emit is
1053
+ * suppressed against the URI's fingerprint and the version it was taken at;
1054
+ * a new version with the same fingerprint goes out with the same
1055
+ * `model.hash`, so a watcher still learns the version. Such rebuilds are routine: a
1056
+ * second client attaching to an open document makes
1057
+ * `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
1058
+ * to re-trigger the build, and Langium rebuilds a document when a
1059
+ * dependency changes even if its diagnostics come out the same. Sent at a
1060
+ * version this head has not sent, they reach watchers as `'changed'`, and a
1061
+ * watcher that reads `'changed'` as another client's write and resets its
1062
+ * root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
1063
+ * fingerprint, so the first event after a watch is de-duplicated against
1064
+ * the state the watcher just fetched; it goes with the last watcher, so the
1065
+ * next first watch re-baselines rather than adopting a stale digest. A
1066
+ * digest keeps its memory constant in document size; see
1067
+ * {@link computeDocumentFingerprint} for the inputs.
784
1068
  */
785
1069
  dispatchPhaseEvent(document, cancelToken) {
786
1070
  if (cancelToken.isCancellationRequested) {
@@ -792,89 +1076,68 @@ export class DataServer {
792
1076
  return;
793
1077
  }
794
1078
  const uri = document.uri.toString();
795
- // Consume the last-close mark even when subscriptions exist — the
796
- // regular dispatch below serves those watchers, and the mark's author
797
- // attribution is more precise than the post-close `UNKNOWN_CLIENT_ID`
798
- // the author lookup would yield.
799
- const revertedOnClose = this.pendingRevertBroadcasts.delete(uri);
800
- if (!this.subscriptions.has(uri) && !revertedOnClose) {
1079
+ const record = this.uriWatchRecords.get(uri);
1080
+ const revertedOnClose = record?.revertPending === true;
1081
+ if (!record || (record.watchers.size === 0 && !revertedOnClose)) {
801
1082
  return;
802
1083
  }
803
- const fingerprint = this.computeDocumentFingerprint(document);
804
- if (this.lastEmittedFingerprint.get(uri) === fingerprint) {
1084
+ if (revertedOnClose) {
1085
+ // Consumed even when watchers exist — the regular dispatch below
1086
+ // serves them, and the mark's attribution is more precise than the
1087
+ // post-close unknown client the manager's attribution would yield.
1088
+ // With no watcher the record goes now, so the fingerprint written
1089
+ // below lands on a detached record and the next first watch
1090
+ // re-baselines instead of adopting it.
1091
+ record.revertPending = undefined;
1092
+ this.pruneUriWatchRecord(uri);
1093
+ }
1094
+ const fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
1095
+ const stamped = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
1096
+ if (record.fingerprint === fingerprint && record.fingerprintVersion === stamped) {
805
1097
  // A rebuild that produced no observable change since the last emit —
806
1098
  // suppressed so RPC subscribers don't see a no-op broadcast. Logged at
807
1099
  // debug so a *needed* re-broadcast wrongly suppressed by this dedup
808
1100
  // (the failure mode the fingerprint strategy must avoid) is visible.
809
- this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${document.textDocument.version}: fingerprint unchanged`);
1101
+ this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${stamped}: fingerprint and version unchanged`);
810
1102
  return;
811
1103
  }
812
- this.lastEmittedFingerprint.set(uri, fingerprint);
1104
+ record.fingerprint = fingerprint;
1105
+ record.fingerprintVersion = stamped;
1106
+ // The manager's attribution, so this head names the same client as the
1107
+ // in-process heads do for one build, except for a version this head
1108
+ // already sent; see `DataServerUriWatchRecord.sentVersion`.
1109
+ const version = this.services.workspace.AstDocumentManager.isOpen(uri) ? document.textDocument.version : undefined;
1110
+ const { reason, sourceClientId } = version !== undefined && record.sentVersion === version
1111
+ ? { reason: 'rebuilt', sourceClientId: UNKNOWN_CLIENT_ID }
1112
+ : this.services.workspace.AstDocumentManager.attributeUpdate(document);
1113
+ record.sentVersion = version;
813
1114
  const event = {
814
- document: this.envelope(document.uri),
815
- sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID : this.resolveSourceClientId(document),
816
- reason: this.resolveUpdateReason(document.uri)
1115
+ document: this.envelope(document.uri, fingerprint),
1116
+ sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID : sourceClientId,
1117
+ reason
817
1118
  };
818
- this.tracer
819
- .withUri(uri)
820
- .debug(`Emit onDocumentUpdated v${event.document.version} (reason=${event.reason}, sourceClientId=${event.sourceClientId})`);
1119
+ this.tracer.withUri(uri).debug(`Emit onDocumentUpdated v${stamped} (reason=${event.reason}, sourceClientId=${event.sourceClientId})`);
821
1120
  this.clientProxy.onDocumentUpdated(event);
822
1121
  }
823
1122
  /**
824
- * Fingerprint of the document's observable state, used to de-dup
825
- * `onDocumentUpdated` emissions. The {@link FingerprintStrategy} option
826
- * selects what is hashed (default `'transfer-document'` — see the type), and
827
- * {@link additionalFingerprintInputs} folds in any extra adopter signal.
1123
+ * Fingerprint of the snapshot `root` and its encoding `encoded`, used to
1124
+ * de-dup `onDocumentUpdated` emissions and sent as every document's
1125
+ * `model.hash`, so it must not depend on the version or on live state. The
1126
+ * {@link FingerprintStrategy} option selects what is hashed (default
1127
+ * `'transfer-document'` — see the type).
828
1128
  *
829
- * The default `'transfer-document'` strategy goes through the encoder's
830
- * {@link TransferEncoder.toTransferDocument}, which is cached per build —
831
- * so within one phase event the fingerprint and the subsequently-emitted
832
- * `envelope` share a single encode walk.
1129
+ * {@link TransferEncoder.toTransferDocument} is cached per build, so within
1130
+ * one phase event the fingerprint and the subsequently-emitted `envelope`
1131
+ * share a single encode walk.
833
1132
  *
834
1133
  * Wrapped in {@link Tracer.time} against {@link FINGERPRINT_LOG_AFTER_MS}.
835
1134
  */
836
- computeDocumentFingerprint(document) {
837
- return this.tracer.withUri(document.uri.toString()).time('Compute fingerprint', () => {
838
- const base = this.options.fingerprintStrategy === 'text-diagnostics'
839
- ? textDiagnosticsFingerprint(document)
840
- : transferDocumentFingerprint(this.encoder.toTransferDocument(document));
841
- const extra = this.additionalFingerprintInputs(document);
842
- return extra.length === 0 ? base : fingerprintHash([base, FINGERPRINT_SEPARATOR, ...extra.map(value => JSON.stringify(value))]);
843
- }, 'debug', { logAfterMs: FINGERPRINT_LOG_AFTER_MS });
844
- }
845
- /**
846
- * Extra inputs folded into {@link computeDocumentFingerprint} alongside the
847
- * chosen {@link FingerprintStrategy}. Default: none. Override to contribute a
848
- * signal that lives outside the document's text / root / diagnostics — each
849
- * entry need only be stable across equivalent emissions and
850
- * JSON-serialisable.
851
- */
852
- additionalFingerprintInputs(_document) {
853
- return [];
854
- }
855
- /**
856
- * Discriminate the reason for a phase-event-driven update notification.
857
- * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
858
- * - URI in the `deleted` list → `'deleted'`
859
- * - URI in the `changed` list → `'changed'` (the URI was passed to
860
- * `documentBuilder.update(changed, deleted)`, which spans `didChange`
861
- * text-document events and programmatic `update([uri], [])` calls).
862
- * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
863
- * because something it depends on changed; its own text wasn't flagged).
864
- *
865
- * `'saved'` is NOT emitted from this code path — saves take the dedicated
866
- * `DataClientProtocol.onDocumentSaved` channel; adopters that want a
867
- * unified update stream synthesise `'saved'` in their bridge layer.
868
- */
869
- resolveUpdateReason(uri) {
870
- const last = this.lastBuildUpdate;
871
- if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
872
- return 'deleted';
873
- }
874
- if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
875
- return 'changed';
876
- }
877
- return 'rebuilt';
1135
+ computeDocumentFingerprint(root, encoded) {
1136
+ return this.tracer
1137
+ .withUri(encoded.uri)
1138
+ .time('Compute fingerprint', () => this.options.fingerprintStrategy === 'text-diagnostics'
1139
+ ? textDiagnosticsFingerprint(this.services.workspace.ModelLedger.textOf(root), encoded.model)
1140
+ : transferDocumentFingerprint(encoded.model), 'debug', { logAfterMs: FINGERPRINT_LOG_AFTER_MS });
878
1141
  }
879
1142
  /**
880
1143
  * Subscribe to the project tier's change channel and re-fan registry
@@ -917,19 +1180,6 @@ export class DataServer {
917
1180
  this.clientProxy.onProjectsChanged({ project: entry.snapshot, reason: 'removed' });
918
1181
  }
919
1182
  }
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
1183
  // --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
934
1184
  // Computed in THIS process: the data-server child holds the model store, so
935
1185
  // these snapshots reflect the heap that actually carries the workspace
@@ -967,7 +1217,7 @@ export class DataServer {
967
1217
  }
968
1218
  async stopProfiling(args) {
969
1219
  if (!this.activeProfile) {
970
- throw new Error('No profiling capture is active; call startProfiling first.');
1220
+ throw noActiveProfileError();
971
1221
  }
972
1222
  const capture = this.activeProfile;
973
1223
  this.activeProfile = undefined;
@@ -996,7 +1246,8 @@ export class DataServer {
996
1246
  methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
997
1247
  additionalMethods,
998
1248
  excludedMethods: partial.excludedMethods ?? [],
999
- diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
1249
+ diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
1250
+ referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
1000
1251
  };
1001
1252
  }
1002
1253
  }