@hydranium/data-server 1.0.0-next.39 → 1.0.0-next.390

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