@hydranium/data-server 1.0.0-next.27 → 1.0.0-next.270

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