@hydranium/data-server 1.0.0-next.32 → 1.0.0-next.321

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