@hydranium/data-server 1.0.0-next.16 → 1.0.0-next.160

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.
@@ -9,12 +9,20 @@
9
9
 
10
10
  import {
11
11
  createRpcProxy,
12
+ defineMessage,
12
13
  DisposableCollection,
14
+ HYDRANIUM_ERROR_CODES,
13
15
  isDocumentSource,
14
16
  isElementSource,
15
17
  isSyntheticSource,
18
+ messageData,
19
+ messageError,
16
20
  ReferenceSource,
21
+ SessionClosedError,
22
+ TIMED_OUT,
17
23
  type CloseModelArgs,
24
+ type HydraniumMessageData,
25
+ type HydraniumResponseError,
18
26
  type Disposable,
19
27
  type ElementSource,
20
28
  type FindNextNameArgs,
@@ -28,8 +36,11 @@ import {
28
36
  type ReferenceTarget,
29
37
  type Tracer,
30
38
  type TransferDiagnostic,
31
- type TransferDocument,
32
- type TransferElement
39
+ TransferDocument,
40
+ type TransferElement,
41
+ UNKNOWN_CLIENT_ID,
42
+ asSnapshotVersion,
43
+ textHash
33
44
  } from '@hydranium/protocol';
34
45
  import {
35
46
  DATA_SERVER_DIAGNOSTICS_METHODS,
@@ -42,29 +53,84 @@ import {
42
53
  type StartProfilingArgs,
43
54
  type StopProfilingArgs,
44
55
  type WriteServerHeapSnapshotArgs,
56
+ type CloseSessionArgs,
57
+ type CreateModelDocumentArgs,
58
+ type CreateSessionArgs,
45
59
  type GetModelDocumentArgs,
46
60
  type GetProjectForUriArgs,
47
61
  type TransferSaveDocumentArgs,
48
62
  type WatchModelDocumentArgs,
49
63
  type TransferDocumentSavedEvent,
50
64
  type TransferDocumentUpdatedEvent,
51
- type TransferUpdateDocumentArgs
65
+ type TransferUpdateDocumentArgs,
66
+ type TransferUpdateDocumentsArgs
52
67
  } from '@hydranium/protocol/data';
53
- import { REVERT_ON_CLOSE_CLIENT_ID, UNKNOWN_CLIENT_ID } from '@hydranium/core';
68
+ import { REVERT_ON_CLOSE_CLIENT_ID } from '@hydranium/core';
54
69
  import { defaultDataServerDiagnostics } from './default-diagnostics.js';
70
+
71
+ /**
72
+ * Raised when a profiling command arrives with no capture running.
73
+ *
74
+ * A `ResponseError` rather than a plain `Error` so the identity survives to the
75
+ * response boundary, which is where the message is rendered. An unwrapped throw
76
+ * reaches the client as a generic internal error instead: no code for a caller
77
+ * to switch on, and nothing for the boundary to render from.
78
+ */
79
+ export const NO_ACTIVE_PROFILE = defineMessage(
80
+ 'hydranium/data-server/no-active-profile',
81
+ 'No profiling capture is active; call startProfiling first.'
82
+ );
83
+
84
+ /**
85
+ * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
86
+ * survives reconstruction and is what a caller switches on.
87
+ */
88
+ export const NO_ACTIVE_PROFILE_CODE = HYDRANIUM_ERROR_CODES.noActiveProfile;
89
+
90
+ export const noActiveProfileError = (): HydraniumResponseError => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
91
+
92
+ /**
93
+ * Raised when a reference question's wait for the build exceeds
94
+ * {@link DataServerOptions.referenceSettleTimeoutMs}.
95
+ *
96
+ * A `ResponseError` because a class name does not cross RPC: without the code a
97
+ * wire client cannot tell a wedged build from a reference that resolves to
98
+ * nothing, which is the distinction the wait exists to keep.
99
+ */
100
+ export const REFERENCE_SETTLE_TIMEOUT = defineMessage(
101
+ 'hydranium/data-server/reference-settle-timeout',
102
+ 'The model is still being processed; try again in a moment.'
103
+ );
104
+
105
+ /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
106
+ export const REFERENCE_SETTLE_TIMEOUT_CODE = HYDRANIUM_ERROR_CODES.referenceSettleTimeout;
107
+
108
+ /** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */
109
+ export const referenceSettleTimeoutError = (elapsedMs: number): ResponseError<HydraniumMessageData & { readonly elapsedMs: number }> =>
110
+ new ResponseError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT.format(), {
111
+ elapsedMs,
112
+ ...messageData(REFERENCE_SETTLE_TIMEOUT)
113
+ });
114
+
55
115
  import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
56
116
  import type {
117
+ ClientSession,
118
+ ClientSessionWriteArgs,
57
119
  ClientTextDocumentChangeEvent,
120
+ DocumentDirtyChangedEvent,
58
121
  HydraniumLanguageServices,
59
122
  LogNameOptions,
123
+ AstDiagnostic,
124
+ AstDocument,
60
125
  ModelService,
61
126
  ProjectChangeEvent,
62
127
  ServerSharedServices,
128
+ SessionEndCause,
63
129
  TransferEncoder
64
130
  } from '@hydranium/core';
65
131
  import type { TextDocument } from 'vscode-languageserver-textdocument';
66
132
  import { type AstNode, DocumentState, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
67
- import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
133
+ import { type CancellationToken, type MessageConnection, ResponseError } from 'vscode-jsonrpc';
68
134
 
69
135
  /**
70
136
  * Domain separator between text and diagnostics inputs of
@@ -75,35 +141,24 @@ import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
75
141
  const FINGERPRINT_SEPARATOR = '\0';
76
142
 
77
143
  /**
78
- * Portable, non-cryptographic 64-bit fingerprint hash (cyrb53), returning a
79
- * 16-char hex digest.
80
- *
81
- * **A cryptographic hash via `node:crypto` is the wrong trade**: the
82
- * fingerprint only needs a stable signal that `(text, diagnostics)` changed
83
- * between emissions, and a `node:*` import would cost
84
- * `@hydranium/data-server` its browser-portability. Parts are fed
85
- * incrementally, char by char, so multi-MB document text is never
86
- * concatenated into one string.
144
+ * `LSPErrorCodes.ServerCancelled`, with which Langium's document wait rejects
145
+ * for a URI that has no document; `vscode-languageserver-protocol` is not a
146
+ * dependency of this package.
87
147
  */
88
- function fingerprintHash(parts: readonly string[]): string {
89
- let h1 = 0xdeadbeef;
90
- let h2 = 0x41c6ce57;
91
- for (const part of parts) {
92
- for (let i = 0; i < part.length; i++) {
93
- const ch = part.charCodeAt(i);
94
- h1 = Math.imul(h1 ^ ch, 2654435761);
95
- h2 = Math.imul(h2 ^ ch, 1597334677);
96
- }
97
- }
98
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
99
- h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
100
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
101
- h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
102
- const high = (h2 >>> 0).toString(16).padStart(8, '0');
103
- const low = (h1 >>> 0).toString(16).padStart(8, '0');
104
- return high + low;
148
+ const SERVER_CANCELLED = -32802;
149
+
150
+ /**
151
+ * A session a data connection registered with a resume token, and how to end
152
+ * it from another connection. See {@link DataServer.resumableSessions}.
153
+ */
154
+ export interface ResumableSession {
155
+ readonly token: string;
156
+ /** End the session as its connection closing would. */
157
+ readonly end: () => void;
105
158
  }
106
159
 
160
+ const resumableByModelService = new WeakMap<object, Map<string, ResumableSession>>();
161
+
107
162
  /**
108
163
  * Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
109
164
  * de-dup `onDocumentUpdated` emissions.
@@ -123,18 +178,14 @@ export type FingerprintStrategy = 'transfer-document' | 'text-diagnostics';
123
178
 
124
179
  /** Hash a document's raw text + diagnostics — the `'text-diagnostics'` strategy. */
125
180
  function textDiagnosticsFingerprint(document: LangiumDocument): string {
126
- return fingerprintHash([document.textDocument.getText(), FINGERPRINT_SEPARATOR, JSON.stringify(document.diagnostics ?? [])]);
181
+ return textHash([document.textDocument.getText(), FINGERPRINT_SEPARATOR, JSON.stringify(document.diagnostics ?? [])]);
127
182
  }
128
183
 
129
184
  /** Hash an encoded transfer document's root + diagnostics — the `'transfer-document'` strategy. */
130
185
  function transferDocumentFingerprint(transferDocument: Pick<TransferDocument<TransferElement, unknown>, 'root' | 'diagnostics'>): string {
131
186
  // null, not undefined: `JSON.stringify(undefined)` yields undefined rather
132
187
  // than a string, putting a non-string into the hash inputs.
133
- return fingerprintHash([
134
- JSON.stringify(transferDocument.root ?? null),
135
- FINGERPRINT_SEPARATOR,
136
- JSON.stringify(transferDocument.diagnostics)
137
- ]);
188
+ return textHash([JSON.stringify(transferDocument.root ?? null), FINGERPRINT_SEPARATOR, JSON.stringify(transferDocument.diagnostics)]);
138
189
  }
139
190
  /**
140
191
  * `logAfterMs` threshold passed to {@link Tracer.time} around
@@ -155,12 +206,13 @@ export interface DataServerOptions extends LogNameOptions {
155
206
  * (`DataClientProtocol.onDocumentUpdated`).
156
207
  *
157
208
  * **Subscription dispatch only** — distinct from the synchronous RPC
158
- * response phase. The lifecycle reads/writes (`getModelDocument` /
159
- * `updateModelDocument` / `saveModelDocument`) settle at the
160
- * integrity-settled landmark (`IntegrityService.SettledState`); a
161
- * read additionally upgrades to `Validated` per call when
162
- * {@link GetModelDocumentArgs.includeDiagnostics} is set. This option
163
- * controls only the async notification phase.
209
+ * response phase. A read (`getModelDocument`) settles at the
210
+ * integrity-settled landmark (`IntegrityService.SettledState`), or at
211
+ * `Validated` when {@link GetModelDocumentArgs.includeDiagnostics} is set.
212
+ * A write (`updateModelDocument` / `updateModelDocuments` /
213
+ * `saveModelDocument`) answers once its document is validated, as a
214
+ * session's write does. This option controls only the async notification
215
+ * phase.
164
216
  *
165
217
  * Default: `DocumentState.Validated` — validation is the last builder
166
218
  * phase and produces the full diagnostic set, so subscription events fired
@@ -201,6 +253,22 @@ export interface DataServerOptions extends LogNameOptions {
201
253
  */
202
254
  readonly fingerprintStrategy?: FingerprintStrategy;
203
255
 
256
+ /**
257
+ * How long a reference question waits for the build to reach `Linked` before
258
+ * failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the
259
+ * wait resolves off a build-phase notification, so a build cancelled below
260
+ * `Linked` with nothing after it leaves the request unanswered for the life
261
+ * of the server.
262
+ *
263
+ * Expiry rejects rather than reading the index anyway: the unsettled index
264
+ * is what the wait keeps the caller away from, so falling through to it on a
265
+ * slow build reinstates the fault — and on a name proposal persists it.
266
+ *
267
+ * Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace
268
+ * still reaching `Linked` for the first time.
269
+ */
270
+ readonly referenceSettleTimeoutMs?: number;
271
+
204
272
  /**
205
273
  * Wire-method namespace for both inbound request handlers and the
206
274
  * outbound notification client proxy. Defaults to
@@ -258,15 +326,20 @@ export interface DataServerOptions extends LogNameOptions {
258
326
  * When supplied, every inbound data-server RPC is timed into this collector
259
327
  * (via the `createRpcProxy` binding) and exposed through
260
328
  * {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an
261
- * LSP connection can pass the SAME collector to
262
- * `instrumentLspConnection(connection, latency)` so one report covers both
263
- * heads. Absent by default (no timing overhead).
329
+ * LSP connection can pass the SAME collector through `lspLatencyOptions` to
330
+ * that connection, so one report covers both heads. Absent by default (no
331
+ * timing overhead).
264
332
  */
265
333
  readonly latency?: LatencyCollector;
266
334
  }
267
335
 
268
- /** Fully-resolved variant — every field set, used internally after merging defaults. */
269
- interface ResolvedDataServerOptions {
336
+ /**
337
+ * Fully-resolved variant of {@link DataServerOptions} — every field set, after
338
+ * merging defaults. Returned by the `protected`
339
+ * {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so
340
+ * an adopter changing how defaults resolve has to name it.
341
+ */
342
+ export interface ResolvedDataServerOptions {
270
343
  readonly subscriptionPhase: DocumentState;
271
344
  readonly fingerprintStrategy: FingerprintStrategy;
272
345
  readonly methodNamespace: string;
@@ -274,6 +347,34 @@ interface ResolvedDataServerOptions {
274
347
  readonly excludedMethods: readonly string[];
275
348
  /** Always resolved — to the caller's, or to the platform default. */
276
349
  readonly diagnostics: DataServerDiagnosticsProvider;
350
+ readonly referenceSettleTimeoutMs: number;
351
+ }
352
+
353
+ /**
354
+ * What a {@link DataServer} keeps per canonical URI, in the `protected`
355
+ * {@link DataServer.uriWatchRecords}. A record lives while it has a watcher
356
+ * or a revert mark; {@link DataServer.pruneUriWatchRecord} enforces that on
357
+ * every path that removes either, so a record with no watcher has a revert
358
+ * pending. Test the size of {@link DataServerUriWatchRecord.watchers}, not the
359
+ * record's presence, for "watched".
360
+ */
361
+ export interface DataServerUriWatchRecord {
362
+ /** The client ids watching the URI; save, dirty and phase events go out only while it is non-empty, a pending revert aside. */
363
+ readonly watchers: Set<string>;
364
+ /** Digest of the last emitted state, or of the state a first watch found; see {@link DataServer.dispatchPhaseEvent} for why it de-duplicates, {@link DataServer.computeDocumentFingerprint} for its inputs. */
365
+ fingerprint?: string;
366
+ /** Set by {@link DataServer.subscribeToTextDocumentCloses}; the next phase event broadcasts even without a watcher. */
367
+ revertPending?: boolean;
368
+ /**
369
+ * The version of an open document the last event sent was built at. The
370
+ * version sent again goes out as `'rebuilt'` from no client: the manager
371
+ * counts a version delivered only once its `Validated` listeners ran, so a
372
+ * build cancelled after the subscription phase would send it as a change
373
+ * twice. Only while the store has the document open: without it, a
374
+ * document can keep one version through changes of its file, so its events
375
+ * keep the manager's attribution.
376
+ */
377
+ sentVersion?: number;
277
378
  }
278
379
 
279
380
  /**
@@ -301,9 +402,11 @@ interface ResolvedDataServerOptions {
301
402
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
302
403
  * builds the {@link DataClientProtocol} notification proxy on the same
303
404
  * connection in one {@link createRpcProxy} call (binding `this` as its
304
- * `localTarget`) under the configured namespace, and subscribes one
305
- * `DocumentBuilder.onDocumentPhase` listener per configured phase that
306
- * dispatches subscription events via `clientProxy.onDocumentUpdated`.
405
+ * `localTarget`) under the configured namespace, and subscribes two listeners
406
+ * at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
407
+ * per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
408
+ * `DocumentBuilder.onBuildPhase` one dispatching a single
409
+ * `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
307
410
  *
308
411
  * The data-server requires the full {@link ServerSharedServices}
309
412
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -331,87 +434,27 @@ export class DataServer<
331
434
  * Framework defaults, exposed so an adopter can spread them when
332
435
  * extending rather than restate a value the framework may change.
333
436
  */
334
- static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>> = {
335
- subscriptionPhase: DocumentState.Validated
437
+ static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>> = {
438
+ subscriptionPhase: DocumentState.Validated,
439
+ referenceSettleTimeoutMs: 60_000
336
440
  };
337
441
 
338
442
  protected readonly options: ResolvedDataServerOptions;
339
- /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
340
- protected readonly subscriptions = new Map<string, Set<string>>();
443
+ /** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
444
+ protected readonly uriWatchRecords = new Map<string, DataServerUriWatchRecord>();
341
445
  /**
342
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
343
- * connection.
446
+ * The client sessions this connection registered, by client id. A document
447
+ * request carrying one of these ids acts as that session; one carrying any
448
+ * other id fails.
344
449
  *
345
- * Kept because the document store releases a client's hold only from an
346
- * explicit close, and a client that dies without closing would otherwise keep
347
- * the document open forever — resident, and with its last-close revert
348
- * suppressed. The store has no notion of which connection a clientId reached
349
- * it over, so the connection-scoped set has to live here; teaching it a client
350
- * identity is the more robust and much larger alternative.
450
+ * Entries stay after {@link dispose} has ended their sessions, so a request
451
+ * still running from before the connection closed reaches the ended handle
452
+ * and fails with the session's own error.
351
453
  */
352
- protected readonly openedDocuments = new Map<string, Set<string>>();
454
+ protected readonly clientSessions = new Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer>>();
353
455
  /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
354
456
  protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
355
457
  protected readonly disposables = new DisposableCollection();
356
- /**
357
- * Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
358
- * `reason` discrimination on outbound `onDocumentUpdated` notifications:
359
- * a URI in the `changed` list emits `'changed'`, in `deleted` emits
360
- * `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
361
- * URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
362
- * the LSP side, so reason fidelity stays consistent between heads.
363
- */
364
- protected lastBuildUpdate?: { changed: readonly URI[]; deleted: readonly URI[] };
365
- /**
366
- * Per-URI hash of the last emitted (text + diagnostics) state,
367
- * used by {@link dispatchPhaseEvent} to suppress duplicate
368
- * `onDocumentUpdated` notifications for rebuilds that produce no
369
- * observable change since the last emit.
370
- *
371
- * Two scenarios routinely produce such rebuilds:
372
- * 1. **Refresh-triggered rebuilds.** When a second client attaches to a
373
- * document already open in another client,
374
- * `HydraniumTextDocuments.refreshContent` fires `onDidChangeContent`
375
- * purely to re-trigger the build pipeline — the text and diagnostics
376
- * are identical to the prior emit.
377
- * 2. **Cascade rebuilds with no diagnostic delta.** Langium rebuilds a
378
- * document when a dependency changes; if the rebuild produces the
379
- * same diagnostics, there is nothing new to communicate to subscribers.
380
- *
381
- * Without this filter, both scenarios reach subscribers as wire-side
382
- * `'changed'` events. A subscriber that interprets `'changed'` as
383
- * "another client wrote new content" and resets its in-memory root to
384
- * the server view then misreads the spurious event as a concurrent
385
- * third-party write and loses the user's edits.
386
- *
387
- * Initialised on {@link watchModelDocument} to the current
388
- * document fingerprint so the FIRST phase event after a fresh
389
- * subscription is also de-duplicated against the state subscribers
390
- * obtained via `getModelDocument` — they do not need a redundant phase
391
- * notification for the state they just fetched.
392
- *
393
- * Cleared in {@link unwatchModelDocument} when the last
394
- * subscriber for a URI leaves so memory does not accumulate.
395
- *
396
- * Stored as a cyrb53 hex digest (16 chars per URI) rather than the raw
397
- * text + diagnostics serialisation so the memory cost is constant in
398
- * document size. See {@link computeDocumentFingerprint} for the inputs.
399
- */
400
- protected readonly lastEmittedFingerprint = new Map<string, string>();
401
- /**
402
- * URIs whose LAST client just closed. The update handler rebuilds such a
403
- * document from its disk content (discarding unsaved in-session edits),
404
- * but {@link dispatchPhaseEvent} gates on the subscription map — and the
405
- * last close typically also removed the last watcher, so consumers that
406
- * only ever fetch via `getModelDocument` would keep showing the
407
- * discarded state forever. Marked on the last-close transition (see
408
- * {@link subscribeToTextDocumentCloses}) and consumed by
409
- * {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
410
- * phase event even without a subscription — de-duplicated against
411
- * {@link lastEmittedFingerprint} where an entry survives, so a close
412
- * whose disk state equals the last emitted state stays silent.
413
- */
414
- protected readonly pendingRevertBroadcasts = new Set<string>();
415
458
  protected readonly tracer: Tracer;
416
459
  /** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
417
460
  protected activeProfile?: DataServerProfileCapture;
@@ -420,27 +463,23 @@ export class DataServer<
420
463
  /** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */
421
464
  protected readonly latency?: LatencyCollector;
422
465
  /** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */
423
- protected readonly encoder: TransferEncoder<unknown, TDiagnostic>;
466
+ protected readonly encoder: TransferEncoder<TDiagnostic>;
424
467
  /**
425
468
  * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
426
- * The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
427
- * carry LSP-shape diagnostics in their AstDocument (e.g. an adopter's LSP-shape diagnostic type)
428
- * while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
429
- * `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
430
- * to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
469
+ * Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
470
+ * {@link encoder} converts one into the other on the way out.
431
471
  */
432
- protected readonly modelService: ModelService<AstNode, unknown, TTransfer>;
472
+ protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
433
473
 
434
474
  constructor(
435
475
  protected readonly connection: MessageConnection,
436
- protected readonly services: ServerSharedServices<TProject>,
476
+ protected readonly services: ServerSharedServices<TProject, TDiagnostic>,
437
477
  options: DataServerOptions = {}
438
478
  ) {
439
479
  this.options = this.resolveOptions(options);
440
480
  this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
441
481
  // DI-bound: adopters rebind `services.model.TransferEncoder` /
442
- // `services.model.ModelService` with their own subclasses. Slot types use the
443
- // framework upper bounds; the casts below narrow to this instance's generics.
482
+ // `services.model.ModelService` with their own subclasses.
444
483
  const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
445
484
  if (!encoder || !modelService) {
446
485
  throw new Error(
@@ -448,8 +487,8 @@ export class DataServer<
448
487
  'Did you compose `createServerSharedModule(ctx)` into your shared module?'
449
488
  );
450
489
  }
451
- this.encoder = encoder as TransferEncoder<unknown, TDiagnostic>;
452
- this.modelService = modelService as ModelService<AstNode, unknown, TTransfer>;
490
+ this.encoder = encoder;
491
+ this.modelService = modelService;
453
492
  const excluded = new Set<string>(this.options.excludedMethods);
454
493
  const registeredMethods = [
455
494
  ...DATA_SERVER_PROTOCOL_METHODS,
@@ -465,38 +504,43 @@ export class DataServer<
465
504
  methodNamespace: this.options.methodNamespace,
466
505
  localTarget: this,
467
506
  localMethods: registeredMethods as readonly (keyof this & string)[],
468
- latency: this.latency
507
+ latency: this.latency,
508
+ // Bound at the chokepoint rather than per handler, so an adopter's
509
+ // `additionalMethods` are rendered on the same terms as the
510
+ // framework's own rejections.
511
+ renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
469
512
  });
470
- this.disposables.push(
471
- this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
472
- this.lastBuildUpdate = { changed, deleted };
473
- })
474
- );
513
+ this.disposables.push(this.services.workspace.DocumentBuilder.onUpdate((_changed, deleted) => this.dispatchDeleteEvents(deleted)));
475
514
  this.subscribeToDocumentBuilder();
476
515
  this.subscribeToTextDocumentSaves();
516
+ this.subscribeToDirtyChanges();
477
517
  this.subscribeToTextDocumentCloses();
478
518
  this.subscribeToProjectManager();
479
519
  // Self-register teardown so an adopter that keeps no reference to the
480
520
  // server still releases per-connection state, with no lifecycle hook of
481
- // its own. See `dispose`.
482
- this.disposables.push(connection.onClose(() => this.dispose()));
521
+ // its own. The client did not close anything itself, so its sessions end
522
+ // as lost and each document it was the last to have open waits out the
523
+ // store's revert grace. See `dispose`.
524
+ this.disposables.push(connection.onClose(() => this.dispose('lost')));
483
525
  }
484
526
 
485
527
  /**
486
528
  * Release everything the constructor wired up — the bound protocol
487
- * handlers and every listener — and clear the subscription map and the
488
- * per-URI emission-fingerprint cache, so a long-lived shared services
489
- * bundle does not retain per-connection memory after the connection
490
- * closes. Also closes every document still open over this connection (see
491
- * {@link closeOpenDocuments}), which is the SHARED store's state rather than
492
- * this server's and so outlives the connection unless released here.
529
+ * handlers and every listener — and clear {@link uriWatchRecords}, so a
530
+ * long-lived shared services bundle does not retain per-connection memory
531
+ * after the connection closes. Also ends every session this connection registered, which closes
532
+ * every document it has open: the SHARED store's state rather than this
533
+ * server's, which outlives the connection unless released here.
493
534
  *
494
- * Idempotent: subsequent calls are no-ops. Self-fires on
495
- * `connection.onClose` so adopters who don't hold a reference still
496
- * get per-connection cleanup; adopters that DO hold a reference may
497
- * call `dispose()` directly for early teardown.
535
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
536
+ * connection closes, so adopters who don't hold a reference still get
537
+ * per-connection cleanup; adopters that DO hold a reference may call
538
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
539
+ * `'closed'` reverts every document whose last open they close at once,
540
+ * and `'lost'`, the connection's own close, lets each wait out the revert
541
+ * grace.
498
542
  */
499
- dispose(): void {
543
+ dispose(cause: SessionEndCause = 'closed'): void {
500
544
  this.disposed = true;
501
545
  // Release an in-flight interactive capture so the process-wide inspector
502
546
  // singleton is not left active after the connection closes.
@@ -505,102 +549,180 @@ export class DataServer<
505
549
  this.activeProfile = undefined;
506
550
  void capture.stop({}).catch(() => undefined);
507
551
  }
508
- // AFTER `disposables.dispose()`, deliberately: closing a document fires
509
- // `onDidClose`, and this server's own close listener would otherwise mark a
510
- // revert broadcast for a connection that is already gone.
552
+ // AFTER `disposables.dispose()`, deliberately: ending a session releases
553
+ // each document it was the last to hold, and this server's own
554
+ // `onDidCloseLastOpen` listener would otherwise mark a revert broadcast
555
+ // for a connection that is already gone.
511
556
  this.disposables.dispose();
512
- this.closeOpenDocuments();
513
- this.subscriptions.clear();
514
- this.lastEmittedFingerprint.clear();
515
- this.pendingRevertBroadcasts.clear();
557
+ for (const [clientId, session] of this.clientSessions) {
558
+ this.endSession(clientId, session, cause);
559
+ }
560
+ this.uriWatchRecords.clear();
516
561
  }
517
562
 
518
563
  // ============================================================
519
- // DataServerProtocol implementation — delegates to ModelService.
564
+ // DataServerProtocol implementation
520
565
  // ============================================================
521
566
  //
522
- // The lifecycle methods (`get` / `update` / `save` / `ready`) forward
523
- // straight to `ModelService` and encode the returned `AstDocument` on
524
- // the wire boundary via `encoder.astDocumentToTransferDocument`.
525
- // Adopters customising lifecycle behaviour (normalisation, supersession,
526
- // settled-phase choice, etc.) override on the ModelService subclass —
527
- // no override on DataServer is needed.
528
-
529
- async openModelDocument(args: OpenModelArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
530
- // Register the editor session (idempotent — `ModelService.open` refreshes
531
- // an already-open document rather than re-opening), then return the built
532
- // state at the configured target phase. The one-shot snapshot; subsequent
533
- // build-phase events arrive via `watchModelDocument`.
534
- await this.modelService.open(args);
535
- // Record the hold so `dispose` can release it for a client that never
536
- // closes. Keyed by the URI as given, because that is what `close` takes.
537
- let holders = this.openedDocuments.get(args.uri);
538
- if (!holders) {
539
- holders = new Set<string>();
540
- this.openedDocuments.set(args.uri, holders);
567
+ // Reads go to `ModelService`; a request that opens or writes a document
568
+ // goes to the session this connection registered under its `clientId`.
569
+ // Each answer is encoded on the wire boundary via
570
+ // `encoder.astDocumentToTransferDocument`. To change how documents are
571
+ // read, override on the ModelService subclass; to change how they are
572
+ // written, on the session class the bound `ClientSessionFactory` builds.
573
+
574
+ async createSession(args: CreateSessionArgs): Promise<void> {
575
+ // After teardown nothing would ever end a session registered now, and its
576
+ // id would stay taken for the life of the process.
577
+ if (this.disposed) {
578
+ throw new SessionClosedError(args.clientId);
579
+ }
580
+ const resumable = this.resumableSessions();
581
+ const previous = resumable.get(args.clientId);
582
+ if (previous && args.resumeToken !== undefined && previous.token === args.resumeToken) {
583
+ previous.end();
584
+ }
585
+ const session = this.modelService.createSession(args.label, args.clientId);
586
+ this.clientSessions.set(args.clientId, session);
587
+ if (args.resumeToken !== undefined) {
588
+ // Taken over by a client registering again after its connection
589
+ // dropped, so the old session ends as lost: the documents it was the
590
+ // last to have open wait out the grace, and the new session's opens
591
+ // find their unsaved text.
592
+ resumable.set(args.clientId, { token: args.resumeToken, end: () => this.endSession(args.clientId, session, 'lost') });
541
593
  }
542
- holders.add(args.clientId);
543
- const document = await this.getModelDocument({ uri: args.uri });
544
- // Project the authoritative client-facing version onto the open snapshot.
545
- // `getModelDocument` encodes the freshly-built AST snapshot, whose version
546
- // is the `LangiumDocument`'s own `textDocument.version`. That lags the
547
- // multi-client synced version whenever the open seeded the synced document
548
- // with a caller-supplied version id — and the synced version is what
549
- // `ModelService.update`'s optimistic-concurrency gate compares
550
- // `baseVersion` against, so reporting the snapshot's would make the
551
- // caller's first tagged write self-conflict. A genuine concurrent edit
552
- // still trips the gate and is reconciled by the caller's replay rather
553
- // than predicted here.
554
- return { ...document, version: this.services.workspace.TextDocuments.version(args.uri) };
555
594
  }
556
595
 
557
- async closeModelDocument(args: CloseModelArgs): Promise<void> {
558
- // Closing a session also releases its watch for (uri, clientId) — a
559
- // forgotten unwatch would otherwise leak phase-event dispatch until the
560
- // connection closes. Idempotent: a close without a prior watch is a no-op.
561
- await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
562
- this.forgetOpenDocument(args.uri, args.clientId);
563
- await this.modelService.close(args);
596
+ /**
597
+ * End a session this connection registered. The ended handle stays in
598
+ * {@link clientSessions}, as it does after {@link dispose}, so a request for
599
+ * the id still arriving fails with the ended session's own error.
600
+ */
601
+ async closeSession(args: CloseSessionArgs): Promise<void> {
602
+ const session = this.clientSessions.get(args.clientId);
603
+ if (session) {
604
+ this.endSession(args.clientId, session);
605
+ }
606
+ }
607
+
608
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
609
+ protected endSession(
610
+ clientId: string,
611
+ session: ClientSession<AstNode, AstDiagnostic, TTransfer>,
612
+ cause: SessionEndCause = 'closed'
613
+ ): void {
614
+ for (const [uri, record] of this.uriWatchRecords) {
615
+ if (record.watchers.delete(clientId)) {
616
+ this.pruneUriWatchRecord(uri);
617
+ }
618
+ }
619
+ session.dispose(cause);
564
620
  }
565
621
 
566
622
  /**
567
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
568
- * close it a second time. Idempotent.
623
+ * The resumable sessions of this services tree, by client id, across all of
624
+ * its data connections: a client resumes on another connection than the one
625
+ * that registered it. An entry leaves when its session ends, by any path, so
626
+ * it keeps no ended connection alive.
627
+ *
628
+ * A takeover by resume token ends the old session even when its connection
629
+ * is still alive, so two clients that shared an id and its token would end
630
+ * each other's sessions. And the token is a guard against colliding with a
631
+ * session the server has not yet seen end, not a secret: the wire carries no
632
+ * authentication, and a peer that learns the token can end the session.
569
633
  */
570
- protected forgetOpenDocument(uri: string, clientId: string): void {
571
- const holders = this.openedDocuments.get(uri);
572
- if (!holders) {
573
- return;
634
+ protected resumableSessions(): Map<string, ResumableSession> {
635
+ let sessions = resumableByModelService.get(this.modelService);
636
+ if (!sessions) {
637
+ const created = new Map<string, ResumableSession>();
638
+ // Subscribed once per services tree, and never disposed: it lives as
639
+ // long as the text store it listens to.
640
+ this.services.workspace.TextDocuments.onDidCloseSession(event => created.delete(event.clientId));
641
+ resumableByModelService.set(this.modelService, created);
642
+ sessions = created;
574
643
  }
575
- holders.delete(clientId);
576
- if (holders.size === 0) {
577
- this.openedDocuments.delete(uri);
644
+ return sessions;
645
+ }
646
+
647
+ async createModelDocument(args: CreateModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
648
+ const session = this.requireSession(args.clientId);
649
+ await session.create(args.uri, args.text);
650
+ return this.openedSnapshot(args.uri, () => session.close(args.uri));
651
+ }
652
+
653
+ async updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>[]> {
654
+ const astDocuments = await this.requireSession(args.clientId).updateAll({
655
+ updates: args.updates.map(update => this.toSessionWrite(update))
656
+ });
657
+ return astDocuments.map(astDocument => this.encodeDocument(astDocument));
658
+ }
659
+
660
+ /**
661
+ * The session write a wire write request carries. Only the fields a session
662
+ * takes: a field an adopter adds to a request reaches the session only
663
+ * through an override of this.
664
+ */
665
+ protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer> {
666
+ return { uri: request.uri, model: request.model, basedOn: request.basedOn };
667
+ }
668
+
669
+ /**
670
+ * The session this connection registered under `clientId`, which every
671
+ * document request acts as. An id that is not one fails with the
672
+ * closed-session code: opening or writing under it would leave an open that
673
+ * no session end ever closes.
674
+ */
675
+ protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer> {
676
+ const session = this.clientSessions.get(clientId);
677
+ if (!session) {
678
+ throw new SessionClosedError(clientId, 'The client session was never registered on this connection.');
578
679
  }
680
+ return session;
681
+ }
682
+
683
+ async openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
684
+ const session = this.requireSession(args.clientId);
685
+ const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
686
+ await session.open(args.uri, args.options);
687
+ // A repeat open keeps the earlier one, which is still in use.
688
+ return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
579
689
  }
580
690
 
581
691
  /**
582
- * Close every document still open over this connection, for the clients that
583
- * opened it here.
584
- *
585
- * The document store releases a per-URI hold only from an explicit close, so
586
- * without this a client that dies mid-session keeps its documents open for the
587
- * lifetime of the process: `isOpenInAnyClient` stays true, the document stays
588
- * resident, and the last-close revert never runs. A long-lived multi-client
589
- * head is the configuration where a dead client is normal rather than
590
- * exceptional, so the leak accumulates there.
692
+ * The snapshot a session's open or create answers with. When the read
693
+ * fails, `rollback` undoes the open this call made before the failure is
694
+ * rethrown: the caller sees no open, so nothing on its side would ever close
695
+ * it.
591
696
  *
592
- * Runs from {@link dispose}, which is synchronous, so each close is fired and
593
- * its failure swallowed — a teardown must not reject, and a URI whose close
594
- * fails is no worse off than it was before this drain existed.
697
+ * Versioned with the store's shared version rather than the snapshot's own:
698
+ * the built document's `textDocument.version` lags the store's whenever the
699
+ * store assigned the version, and the store's is what a write's `basedOn` is
700
+ * compared against, so reporting the snapshot's would make the caller's
701
+ * first based-on write conflict with itself.
595
702
  */
596
- protected closeOpenDocuments(): void {
597
- const held = [...this.openedDocuments];
598
- this.openedDocuments.clear();
599
- for (const [uri, clientIds] of held) {
600
- for (const clientId of clientIds) {
601
- void Promise.resolve(this.modelService.close({ uri, clientId })).catch(() => undefined);
602
- }
703
+ protected async openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
704
+ let document: TransferDocument<TTransfer, TDiagnostic>;
705
+ try {
706
+ document = await this.getModelDocument({ uri });
707
+ } catch (error: unknown) {
708
+ // The open's failure is the one the caller needs, not the cleanup's.
709
+ await rollback?.().catch(() => undefined);
710
+ throw error;
603
711
  }
712
+ // Stamped again with the version, in one step: a write landing after the
713
+ // read would otherwise pair its version with the read's text hash.
714
+ return this.withServerState({ ...document, version: asSnapshotVersion(this.services.workspace.TextDocuments.version(uri)) });
715
+ }
716
+
717
+ async closeModelDocument(args: CloseModelArgs): Promise<void> {
718
+ // Through the handle, so a close under an ended session fails as that
719
+ // session's calls do, and a session class's own close is honoured.
720
+ const session = this.requireSession(args.clientId);
721
+ // Closing also releases the watch for (uri, clientId) — a forgotten
722
+ // unwatch would otherwise leak phase-event dispatch until the connection
723
+ // closes. Idempotent: a close without a prior watch is a no-op.
724
+ await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
725
+ await session.close(args.uri);
604
726
  }
605
727
 
606
728
  async getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
@@ -615,18 +737,26 @@ export class DataServer<
615
737
  // unsubscribed caller that needs diagnostics inline passes
616
738
  // `includeDiagnostics: true` to settle at `Validated` instead.
617
739
  const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
618
- const astDocument = await this.modelService.ensureDocumentState(args.uri, state);
619
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
740
+ try {
741
+ return this.encodeDocument(await this.modelService.ensureDocumentState(args.uri, state));
742
+ } catch (error: unknown) {
743
+ // The protocol answers a read of a URI with no document with an
744
+ // envelope that has no root.
745
+ if (this.isMissingDocument(error, args.uri)) {
746
+ return this.envelope(UriUtils.toUri(args.uri));
747
+ }
748
+ throw error;
749
+ }
620
750
  }
621
751
 
622
752
  async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
623
- const astDocument = await this.modelService.update(args);
624
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
753
+ const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
754
+ return this.encodeDocument(astDocument);
625
755
  }
626
756
 
627
757
  async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
628
- const astDocument = await this.modelService.save(args);
629
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
758
+ const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
759
+ return this.encodeDocument(astDocument);
630
760
  }
631
761
 
632
762
  /**
@@ -634,28 +764,24 @@ export class DataServer<
634
764
  * fan out to the wired `clientProxy.onDocumentUpdated`. The
635
765
  * bidirectional pattern means the event channel is the client
636
766
  * notification surface, not a returned handle — this method only
637
- * registers the URI in the dispatch table.
767
+ * registers the watcher in {@link uriWatchRecords}.
638
768
  *
639
- * Also baselines the per-URI emission fingerprint (see
640
- * {@link lastEmittedFingerprint}) to the document's current state when
641
- * the first watcher for the URI registers. This guarantees that any
642
- * phase event firing immediately after the watch with no observable
643
- * change is suppressed — watchers obtain initial state via
644
- * `getModelDocument` (or {@link openModelDocument}) and do not need a
645
- * redundant phase notification for that same state.
769
+ * Also baselines the URI's emission fingerprint (see
770
+ * {@link dispatchPhaseEvent}) to the document's current state when the
771
+ * first watcher for the URI registers. This guarantees that any phase event firing immediately after
772
+ * the watch with no observable change is suppressed — watchers obtain
773
+ * initial state via `getModelDocument` (or {@link openModelDocument}) and
774
+ * do not need a redundant phase notification for that same state.
646
775
  */
647
776
  async watchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
648
777
  const uri = this.canonicalKey(args.uri);
649
- let subscribers = this.subscriptions.get(uri);
650
- if (!subscribers) {
651
- subscribers = new Set();
652
- this.subscriptions.set(uri, subscribers);
653
- }
654
- subscribers.add(args.clientId);
655
- if (!this.lastEmittedFingerprint.has(uri)) {
778
+ const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
779
+ this.uriWatchRecords.set(uri, record);
780
+ record.watchers.add(args.clientId);
781
+ if (record.fingerprint === undefined) {
656
782
  const document = this.services.workspace.LangiumDocuments.getDocument(UriUtils.toUri(uri));
657
783
  if (document) {
658
- this.lastEmittedFingerprint.set(uri, this.computeDocumentFingerprint(document));
784
+ record.fingerprint = this.computeDocumentFingerprint(document);
659
785
  }
660
786
  }
661
787
  }
@@ -663,29 +789,40 @@ export class DataServer<
663
789
  /**
664
790
  * Remove a watch for `(uri, clientId)` previously created by
665
791
  * {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
666
- * Dispatch for `uri` stops once no watchers remain, at which point the
667
- * per-URI emission fingerprint is also cleared so the next first-watch
668
- * re-baselines against the then-current document state rather than a
669
- * stale snapshot from the previous watch.
792
+ * Dispatch for `uri` stops once no watchers remain, and the emission
793
+ * fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
670
794
  */
671
795
  async unwatchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
672
796
  const uri = this.canonicalKey(args.uri);
673
- const subscribers = this.subscriptions.get(uri);
674
- if (!subscribers) {
797
+ if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
798
+ this.pruneUriWatchRecord(uri);
799
+ }
800
+ }
801
+
802
+ /**
803
+ * Drop what `uri` no longer needs: the
804
+ * {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
805
+ * and the whole record once it holds no
806
+ * {@link DataServerUriWatchRecord.revertPending} mark either. Every path
807
+ * that removes a watcher or consumes a mark ends here.
808
+ */
809
+ protected pruneUriWatchRecord(uri: string): void {
810
+ const record = this.uriWatchRecords.get(uri);
811
+ if (!record || record.watchers.size > 0) {
675
812
  return;
676
813
  }
677
- subscribers.delete(args.clientId);
678
- if (subscribers.size === 0) {
679
- this.subscriptions.delete(uri);
680
- this.lastEmittedFingerprint.delete(uri);
814
+ if (record.revertPending) {
815
+ record.fingerprint = undefined;
816
+ } else {
817
+ this.uriWatchRecords.delete(uri);
681
818
  }
682
819
  }
683
820
 
684
821
  /**
685
- * Canonicalise a URI string for use as a subscription / fingerprint
686
- * map key, via the shared `DocumentUriPolicy`. Callers may send
687
- * non-canonical URIs (drive-letter casing, percent-encoding differences,
688
- * or a symlink path) over the wire; the dispatch side keys by
822
+ * Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
823
+ * shared `DocumentUriPolicy`. Callers may send non-canonical URIs
824
+ * (drive-letter casing, percent-encoding differences, or a symlink path)
825
+ * over the wire; the dispatch side keys by
689
826
  * `document.uri.toString()` from `LangiumDocuments`, so writer keys must
690
827
  * canonicalise to the same form or events silently fail to deliver.
691
828
  * Routing through the seam (rather than a bare `UriUtils.normalize`)
@@ -734,26 +871,57 @@ export class DataServer<
734
871
  // (see resolveReferenceServices) and delegate.
735
872
  // ============================================================
736
873
 
737
- async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
738
- // Candidates are derived from resolved cross-references, so the relevant document(s) must
739
- // have finished the Linked phase — otherwise a query issued right after a model update races
740
- // the asynchronous rebuild and returns stale candidates. Wait the source document
741
- // specifically, but ONLY when a document is actually loaded at that URI: a synthetic source
742
- // can address a URI with no document (a directory URI, typically), and a per-URI `waitUntil`
743
- // there throws "No document found". Fall back to a global Linked settle, matching the
744
- // id-based ElementSource (no URI) path.
745
- const uri = isDocumentSource(ctx.source) || isSyntheticSource(ctx.source) ? UriUtils.toUri(ctx.source.uri) : undefined;
874
+ /**
875
+ * Settle the build before a reference question is answered from the index.
876
+ *
877
+ * A query issued right after a model update otherwise races the rebuild and
878
+ * reads an index missing the symbols it asks about. The cost is not confined
879
+ * to this call: a scope built inside that window is cached, and the build's
880
+ * remaining documents link against it.
881
+ *
882
+ * Waits the source document specifically, but ONLY when one is loaded at
883
+ * that URI: a synthetic source can address a URI with no document (a
884
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
885
+ * found". Falls back to a global settle, matching the id-based
886
+ * `ElementSource` path.
887
+ *
888
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
889
+ */
890
+ protected async awaitReferencesLinked(source: ReferenceSource): Promise<void> {
891
+ const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
746
892
  const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
747
- await this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
893
+ const stopwatch = this.services.Clock.stopwatch();
894
+ const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
895
+ if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
896
+ return;
897
+ }
898
+ const elapsedMs = Math.round(stopwatch.elapsedMs);
899
+ // A per-URI wait resolves off a document-phase notification, so a
900
+ // missed one strands a wait on a document that HAS reached the
901
+ // phase. Re-read before failing; the workspace-wide wait has no
902
+ // equivalent reading and can only reject.
903
+ const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
904
+ if (waitUri && document && document.state >= DocumentState.Linked) {
905
+ this.tracer
906
+ .withUri(waitUri.toString())
907
+ .warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
908
+ return;
909
+ }
910
+ throw referenceSettleTimeoutError(elapsedMs);
911
+ }
912
+
913
+ async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
914
+ await this.awaitReferencesLinked(ctx.source);
748
915
  return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
749
916
  }
750
917
 
751
918
  async resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined> {
919
+ await this.awaitReferencesLinked(ref.source);
752
920
  const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
753
921
  if (!resolved) {
754
922
  return undefined;
755
923
  }
756
- const element = this.encoder.toTransfer(resolved.node) as unknown as TTransfer;
924
+ const element = this.encoder.toTransfer(resolved.node) as TTransfer;
757
925
  return { ...resolved.candidate, element };
758
926
  }
759
927
 
@@ -764,15 +932,31 @@ export class DataServer<
764
932
  // synthetic source — and the create-element flow driving this method is
765
933
  // the one that produces directory URIs, on which a bare
766
934
  // `getServices(uri)` throws while `findReferenceCandidates` succeeds.
767
- const nameProvider = this.resolveReferenceServices(ReferenceSource.synthetic(args.uri, args.type)).NameProvider;
935
+ const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
936
+ // Mid-rebuild the names of documents not yet re-indexed are absent from
937
+ // the taken set, and the caller PERSISTS what it is handed. Nothing
938
+ // reserves the answer either, so a name is free of the collisions the
939
+ // index knows about and of nothing else — two callers racing get the same
940
+ // proposal, which only uniqueness at the write can catch.
941
+ await this.awaitReferencesLinked(source);
942
+ const nameProvider = this.resolveReferenceServices(source).NameProvider;
768
943
  const tier = args.tier ?? 'project';
769
944
  if (tier === 'public') {
770
945
  return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
771
946
  }
772
947
  if (tier === 'local') {
773
- // Document-scoped uniqueness: the document root is the container.
774
- const document = await this.modelService.ensureDocumentState(args.uri);
775
- return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root as AstNode) : args.proposal;
948
+ // Document-scoped uniqueness: the document root is the container. A
949
+ // URI with no document has nothing to collide with, like a document
950
+ // with no root.
951
+ try {
952
+ const document = await this.modelService.ensureDocumentState(args.uri);
953
+ return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
954
+ } catch (error: unknown) {
955
+ if (this.isMissingDocument(error, args.uri)) {
956
+ return args.proposal;
957
+ }
958
+ throw error;
959
+ }
776
960
  }
777
961
  const project = this.services.workspace.ProjectManager.getProject(uri);
778
962
  if (!project) {
@@ -811,6 +995,9 @@ export class DataServer<
811
995
  /**
812
996
  * Pick the language that owns a reference source, in order:
813
997
  *
998
+ * 0. A {@link isSyntheticSource} naming its own `language` routes there.
999
+ * First because every step below infers, and an inference must not
1000
+ * override a caller that has said which grammar it means.
814
1001
  * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
815
1002
  * whose URI resolves to a registered language routes by URI.
816
1003
  * 2. A single-language workspace always routes to that one language — so
@@ -829,6 +1016,15 @@ export class DataServer<
829
1016
  */
830
1017
  protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined {
831
1018
  const registry = this.services.ServiceRegistry;
1019
+ if (isSyntheticSource(source) && source.language !== undefined) {
1020
+ const declared = registry.getServicesById(source.language);
1021
+ if (declared) {
1022
+ return declared;
1023
+ }
1024
+ // Falling through on an UNREGISTERED id rather than failing: the id
1025
+ // crosses the wire, so a client built against a head with one more
1026
+ // grammar would otherwise lose queries the steps below can answer.
1027
+ }
832
1028
  // `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
833
1029
  // an extensionless / unregistered URI falls through to the steps below
834
1030
  // rather than throwing "no services for the extension ''".
@@ -839,7 +1035,7 @@ export class DataServer<
839
1035
  }
840
1036
  const all = registry.all;
841
1037
  if (all.length === 1) {
842
- return all[0] as HydraniumLanguageServices;
1038
+ return all[0];
843
1039
  }
844
1040
  if (isElementSource(source)) {
845
1041
  const documentUri = this.findElementDocumentUri(source);
@@ -922,6 +1118,18 @@ export class DataServer<
922
1118
  // Internal plumbing
923
1119
  // ============================================================
924
1120
 
1121
+ /**
1122
+ * Whether `error`, from waiting on `uri`'s document, means that `uri` has
1123
+ * no document: a URI with neither a file nor text builds nothing, and
1124
+ * Langium's wait after the build rejects for want of one, with a
1125
+ * `ServerCancelled` response error. Any other failure, such as a read
1126
+ * that fails before a document is registered, a cancelled wait or a
1127
+ * `ReentrantWriteLockError`, is the caller's to see.
1128
+ */
1129
+ protected isMissingDocument(error: unknown, uri: string): boolean {
1130
+ return error instanceof ResponseError && error.code === SERVER_CANCELLED && this.modelService.getDocument(uri) === undefined;
1131
+ }
1132
+
925
1133
  /**
926
1134
  * Build a {@link TransferDocument} envelope from the current document state,
927
1135
  * delegating root + diagnostic encoding to {@link encoder} (see
@@ -945,14 +1153,38 @@ export class DataServer<
945
1153
  // decides policy at its own layer; `root` is optional on the envelope
946
1154
  // so the compiler forces that decision. Adopters preferring to throw
947
1155
  // override `envelope`.
948
- return {
949
- uri: uri.toString(),
950
- version: 0,
951
- root: undefined,
952
- diagnostics: [] as TDiagnostic[]
953
- };
1156
+ return TransferDocument.absent<TTransfer, TDiagnostic>(uri.toString());
954
1157
  }
955
- return this.encoder.toTransferDocument<AstNode>(document) as unknown as TransferDocument<TTransfer, TDiagnostic>;
1158
+ return this.withServerState(this.encoder.toTransferDocument(document) as TransferDocument<TTransfer, TDiagnostic>);
1159
+ }
1160
+
1161
+ /**
1162
+ * The transfer document a request answers with for `astDocument`, the
1163
+ * store's current `dirty` and `textHash` stamped on it by
1164
+ * {@link withServerState}. Every document a request answers with goes
1165
+ * through here, so none goes out without the stamp.
1166
+ */
1167
+ protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
1168
+ return this.withServerState(this.encoder.astDocumentToTransferDocument(astDocument) as TransferDocument<TTransfer, TDiagnostic>);
1169
+ }
1170
+
1171
+ /**
1172
+ * `document` with the store's current {@link TransferDocument.dirty} and
1173
+ * the {@link TransferDocument.textHash} of the text the server holds for
1174
+ * it: the store's text while a client has it open, the build's otherwise.
1175
+ * Both are read when the document is sent rather than kept with the build:
1176
+ * a save changes `dirty` without a rebuild, and the store's text moves on
1177
+ * before the build that follows it.
1178
+ */
1179
+ protected withServerState(document: TransferDocument<TTransfer, TDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
1180
+ const text = (
1181
+ this.services.workspace.TextDocuments.get(document.uri) ?? this.modelService.getDocument(document.uri)?.textDocument
1182
+ )?.getText();
1183
+ return {
1184
+ ...document,
1185
+ dirty: this.services.workspace.TextDocuments.isDirty(document.uri),
1186
+ ...(text === undefined ? {} : { textHash: textHash(text) })
1187
+ };
956
1188
  }
957
1189
 
958
1190
  /**
@@ -967,6 +1199,59 @@ export class DataServer<
967
1199
  this.dispatchPhaseEvent(document, cancelToken)
968
1200
  )
969
1201
  );
1202
+ // The BUILD-phase hook, not the per-document one: this notification is one
1203
+ // message per build rather than one per document, and Langium hands the
1204
+ // whole batch over here. It also does not fire for a cancelled build,
1205
+ // which is what the per-document dispatch has to check by hand.
1206
+ this.disposables.push(
1207
+ this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built))
1208
+ );
1209
+ }
1210
+
1211
+ /**
1212
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
1213
+ * and that NOBODY on this
1214
+ * connection is watching — the ones a client was not told about through
1215
+ * {@link dispatchPhaseEvent}, which is gated per URI.
1216
+ *
1217
+ * **The gap this closes is the one no other source can observe.** A document
1218
+ * the client watches, it hears about already. A file changed on disk, the
1219
+ * host's own filesystem watcher reports — and on a browser host, where the
1220
+ * workspace lives behind this head, an external change cannot happen at all.
1221
+ * What is left, and what nothing outside the server can see, is a document
1222
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
1223
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
1224
+ * the update channel is silent by design. A consumer displaying data derived
1225
+ * from that document — a tree label, a decorator — otherwise goes stale with
1226
+ * no signal from any source, and repairs itself the moment someone opens the
1227
+ * file to investigate, which is what makes it expensive to diagnose later.
1228
+ *
1229
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
1230
+ * rather than being handed transfer documents it did not ask for. That is the
1231
+ * property the watcher gate protects, and it is preserved here by
1232
+ * carrying no document rather than by gating the message.
1233
+ *
1234
+ * Quiet in the common case. Editing a document that an editor has open leaves
1235
+ * that URI watched and therefore out of this set, so a build with no
1236
+ * dependents produces nothing at all, and workspace initialisation produces
1237
+ * nothing because it does not build to this phase. The ceiling is a
1238
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
1239
+ *
1240
+ * The URI is canonicalised for the same reason {@link uriWatchRecords} is keyed
1241
+ * that way, and is untested for the same reason as its twin in
1242
+ * {@link dispatchDeleteEvents}: the builder reports URIs out of its own
1243
+ * store, so a non-canonical one cannot be produced without a fixture
1244
+ * asserting a shape the real system never emits.
1245
+ */
1246
+ protected dispatchBuiltEvent(built: readonly LangiumDocument[]): void {
1247
+ const uris = built
1248
+ .map(document => this.canonicalKey(document.uri.toString()))
1249
+ .filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
1250
+ if (uris.length === 0) {
1251
+ return;
1252
+ }
1253
+ this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
1254
+ this.clientProxy.onDocumentsBuilt({ uris });
970
1255
  }
971
1256
 
972
1257
  /**
@@ -987,32 +1272,113 @@ export class DataServer<
987
1272
  this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
988
1273
  }
989
1274
 
1275
+ /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
1276
+ protected subscribeToDirtyChanges(): void {
1277
+ this.disposables.push(this.services.workspace.TextDocuments.onDidChangeDirty(event => this.dispatchDirtyEvent(event)));
1278
+ }
1279
+
990
1280
  /**
991
- * Mark the last-close transition per URI (see
992
- * {@link pendingRevertBroadcasts}). The listener consults
993
- * `isOpenInAnyClient` AFTER the store decremented the closing client's
994
- * hold, so a `false` answer means this close was the last one.
1281
+ * Send a dirty flip to the connection, gated on the URI's watchers as
1282
+ * {@link dispatchSaveEvent} is: the answer at any one moment travels on
1283
+ * every document sent, so a client that watches nothing reads it there.
1284
+ */
1285
+ protected dispatchDirtyEvent(event: DocumentDirtyChangedEvent): void {
1286
+ const uri = this.canonicalKey(event.uri);
1287
+ if (this.uriWatchRecords.get(uri)?.watchers.size) {
1288
+ this.clientProxy.onDocumentDirtyChanged({ uri, dirty: event.dirty });
1289
+ }
1290
+ }
1291
+
1292
+ /**
1293
+ * Mark each document the store releases after its last close, so
1294
+ * {@link dispatchPhaseEvent} broadcasts the following rebuild even without
1295
+ * a watcher. The store rebuilds such a document from its disk content,
1296
+ * discarding unsaved in-session edits, and the last close typically also
1297
+ * removed the last watcher: without the broadcast, a consumer that only
1298
+ * ever fetches via `getModelDocument` keeps showing the discarded state.
1299
+ * The broadcast is de-duplicated against the fingerprint while a watcher
1300
+ * holds one, so a close whose disk state equals the last emitted state
1301
+ * stays silent; with no watcher there is no fingerprint, and every revert
1302
+ * is sent.
1303
+ *
1304
+ * A release, not the close itself: a document whose last client lost its
1305
+ * connection is released only once the revert grace runs out, or when
1306
+ * another client opens it meanwhile, and not at all when a client lost
1307
+ * from it opens it again within its own grace.
995
1308
  */
996
1309
  protected subscribeToTextDocumentCloses(): void {
997
- const textDocuments = this.services.workspace.TextDocuments;
998
1310
  this.disposables.push(
999
- textDocuments.onDidClose(event => {
1000
- if (!textDocuments.isOpenInAnyClient(event.document.uri)) {
1001
- this.pendingRevertBroadcasts.add(this.canonicalKey(event.document.uri));
1002
- }
1311
+ this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
1312
+ const uri = this.canonicalKey(event.uri);
1313
+ const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
1314
+ record.revertPending = true;
1315
+ this.uriWatchRecords.set(uri, record);
1003
1316
  })
1004
1317
  );
1005
1318
  }
1006
1319
 
1007
- /** Fan out a save event for the document's URI, gated by the subscription map. */
1320
+ /**
1321
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
1322
+ * rather than only to the ones watching that URI.
1323
+ *
1324
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
1325
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
1326
+ * fire on every build, so the watcher gate is what keeps bandwidth
1327
+ * proportional to what a client asked for. A deletion is neither: it is one
1328
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
1329
+ * document's content. Gating it forces any consumer that displays the
1330
+ * workspace — a model tree, a file decorator — to learn about disappearances
1331
+ * from a filesystem watcher instead, which a client hosted in a browser has
1332
+ * no way to run: its workspace lives behind the head. A client that does not
1333
+ * care filters on the URI, which costs it a comparison.
1334
+ *
1335
+ * The precedent is the last-close revert broadcast (see
1336
+ * {@link subscribeToTextDocumentCloses}), where the same judgement was already made
1337
+ * in the other direction: a transition that matters enough is delivered
1338
+ * without a subscription.
1339
+ *
1340
+ * Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
1341
+ * listener, which is the only place a deletion is observable: `update`
1342
+ * removes the document before deriving the rebuild set, so it is never built.
1343
+ * That ordering also puts this notification ahead of the `'rebuilt'` events
1344
+ * for the dependents whose references the deletion just broke.
1345
+ *
1346
+ * The `deleted` list arrives already expanded to concrete document URIs —
1347
+ * `deleteDocuments` resolves a directory URI to the documents beneath it — so
1348
+ * no caller has to handle a directory here.
1349
+ *
1350
+ * The URI's fingerprint and revert mark are dropped: they describe a
1351
+ * document that no longer exists. A kept fingerprint is adopted as the
1352
+ * baseline and suppresses the first emit after the file returns with its
1353
+ * previous content.
1354
+ *
1355
+ * The watchers SURVIVE: a recreated file resumes delivering to them with no
1356
+ * re-subscription, and a client that answers the deletion by closing
1357
+ * releases the watch through `closeModelDocument` anyway.
1358
+ */
1359
+ protected dispatchDeleteEvents(deleted: readonly URI[]): void {
1360
+ for (const removed of deleted) {
1361
+ const uri = this.canonicalKey(removed.toString());
1362
+ const record = this.uriWatchRecords.get(uri);
1363
+ if (record) {
1364
+ record.fingerprint = undefined;
1365
+ record.revertPending = undefined;
1366
+ record.sentVersion = undefined;
1367
+ this.pruneUriWatchRecord(uri);
1368
+ }
1369
+ this.clientProxy.onDocumentDeleted({ uri });
1370
+ }
1371
+ }
1372
+
1373
+ /** Fan out a save event for the document's URI, gated on the URI's watchers. */
1008
1374
  protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void {
1009
1375
  // The save event arrives under the CLIENT URI the text store keys by (e.g. a
1010
- // symlink path S); the subscription map and `dispatchPhaseEvent` key by the
1376
+ // symlink path S); `uriWatchRecords` and `dispatchPhaseEvent` key by the
1011
1377
  // CANONICAL identity R. Canonicalize before both the gate and the envelope so
1012
1378
  // a save of a symlinked file isn't silently dropped (and the envelope resolves
1013
1379
  // the R-keyed document rather than missing into an empty one).
1014
1380
  const uri = this.canonicalKey(event.document.uri);
1015
- if (!this.subscriptions.has(uri)) {
1381
+ if (!this.uriWatchRecords.get(uri)?.watchers.size) {
1016
1382
  return;
1017
1383
  }
1018
1384
  const response = this.envelope(UriUtils.toUri(uri));
@@ -1032,13 +1398,25 @@ export class DataServer<
1032
1398
  * out to multiple local subscribers with an `Emitter<T>` — the
1033
1399
  * framework deliberately does NOT promise multi-listener semantics.
1034
1400
  *
1035
- * The dispatch is guarded by two filters:
1036
- * 1. **Subscription map**: events for URIs no subscriber registered for
1037
- * are NOT sent over the wire (bandwidth scales with subscribed URIs,
1038
- * not phase events).
1039
- * 2. **Emission fingerprint**: events for rebuilds that produce no
1040
- * observable change since the last emit are suppressed. See
1041
- * {@link lastEmittedFingerprint} for the rationale.
1401
+ * An event for a URI no client watches is NOT sent over the wire, so
1402
+ * bandwidth scales with watched URIs rather than with phase events; a
1403
+ * pending revert mark is the exception (see
1404
+ * {@link subscribeToTextDocumentCloses}).
1405
+ *
1406
+ * An event for a rebuild with no observable change since the last emit is
1407
+ * suppressed against the URI's fingerprint. Such rebuilds are routine: a
1408
+ * second client attaching to an open document makes
1409
+ * `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
1410
+ * to re-trigger the build, and Langium rebuilds a document when a
1411
+ * dependency changes even if its diagnostics come out the same. Sent at a
1412
+ * version this head has not sent, they reach watchers as `'changed'`, and a
1413
+ * watcher that reads `'changed'` as another client's write and resets its
1414
+ * root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
1415
+ * fingerprint, so the first event after a watch is de-duplicated against
1416
+ * the state the watcher just fetched; it goes with the last watcher, so the
1417
+ * next first watch re-baselines rather than adopting a stale digest. A
1418
+ * digest keeps its memory constant in document size; see
1419
+ * {@link computeDocumentFingerprint} for the inputs.
1042
1420
  */
1043
1421
  protected dispatchPhaseEvent(document: LangiumDocument, cancelToken: CancellationToken): void {
1044
1422
  if (cancelToken.isCancellationRequested) {
@@ -1050,16 +1428,23 @@ export class DataServer<
1050
1428
  return;
1051
1429
  }
1052
1430
  const uri = document.uri.toString();
1053
- // Consume the last-close mark even when subscriptions exist — the
1054
- // regular dispatch below serves those watchers, and the mark's author
1055
- // attribution is more precise than the post-close `UNKNOWN_CLIENT_ID`
1056
- // the author lookup would yield.
1057
- const revertedOnClose = this.pendingRevertBroadcasts.delete(uri);
1058
- if (!this.subscriptions.has(uri) && !revertedOnClose) {
1431
+ const record = this.uriWatchRecords.get(uri);
1432
+ const revertedOnClose = record?.revertPending === true;
1433
+ if (!record || (record.watchers.size === 0 && !revertedOnClose)) {
1059
1434
  return;
1060
1435
  }
1436
+ if (revertedOnClose) {
1437
+ // Consumed even when watchers exist — the regular dispatch below
1438
+ // serves them, and the mark's attribution is more precise than the
1439
+ // post-close unknown client the manager's attribution would yield.
1440
+ // With no watcher the record goes now, so the fingerprint written
1441
+ // below lands on a detached record and the next first watch
1442
+ // re-baselines instead of adopting it.
1443
+ record.revertPending = undefined;
1444
+ this.pruneUriWatchRecord(uri);
1445
+ }
1061
1446
  const fingerprint = this.computeDocumentFingerprint(document);
1062
- if (this.lastEmittedFingerprint.get(uri) === fingerprint) {
1447
+ if (record.fingerprint === fingerprint) {
1063
1448
  // A rebuild that produced no observable change since the last emit —
1064
1449
  // suppressed so RPC subscribers don't see a no-op broadcast. Logged at
1065
1450
  // debug so a *needed* re-broadcast wrongly suppressed by this dedup
@@ -1067,11 +1452,20 @@ export class DataServer<
1067
1452
  this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${document.textDocument.version}: fingerprint unchanged`);
1068
1453
  return;
1069
1454
  }
1070
- this.lastEmittedFingerprint.set(uri, fingerprint);
1455
+ record.fingerprint = fingerprint;
1456
+ // The manager's attribution, so this head names the same client as the
1457
+ // in-process heads do for one build, except for a version this head
1458
+ // already sent; see `DataServerUriWatchRecord.sentVersion`.
1459
+ const version = this.services.workspace.AstDocumentManager.isOpen(uri) ? document.textDocument.version : undefined;
1460
+ const { reason, sourceClientId } =
1461
+ version !== undefined && record.sentVersion === version
1462
+ ? { reason: 'rebuilt' as const, sourceClientId: UNKNOWN_CLIENT_ID }
1463
+ : this.services.workspace.AstDocumentManager.attributeUpdate(document);
1464
+ record.sentVersion = version;
1071
1465
  const event: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> = {
1072
1466
  document: this.envelope(document.uri),
1073
- sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID : this.resolveSourceClientId(document),
1074
- reason: this.resolveUpdateReason(document.uri)
1467
+ sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID : sourceClientId,
1468
+ reason
1075
1469
  };
1076
1470
  this.tracer
1077
1471
  .withUri(uri)
@@ -1101,7 +1495,7 @@ export class DataServer<
1101
1495
  ? textDiagnosticsFingerprint(document)
1102
1496
  : transferDocumentFingerprint(this.encoder.toTransferDocument(document));
1103
1497
  const extra = this.additionalFingerprintInputs(document);
1104
- return extra.length === 0 ? base : fingerprintHash([base, FINGERPRINT_SEPARATOR, ...extra.map(value => JSON.stringify(value))]);
1498
+ return extra.length === 0 ? base : textHash([base, FINGERPRINT_SEPARATOR, ...extra.map(value => JSON.stringify(value))]);
1105
1499
  },
1106
1500
  'debug',
1107
1501
  { logAfterMs: FINGERPRINT_LOG_AFTER_MS }
@@ -1119,31 +1513,6 @@ export class DataServer<
1119
1513
  return [];
1120
1514
  }
1121
1515
 
1122
- /**
1123
- * Discriminate the reason for a phase-event-driven update notification.
1124
- * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
1125
- * - URI in the `deleted` list → `'deleted'`
1126
- * - URI in the `changed` list → `'changed'` (the URI was passed to
1127
- * `documentBuilder.update(changed, deleted)`, which spans `didChange`
1128
- * text-document events and programmatic `update([uri], [])` calls).
1129
- * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
1130
- * because something it depends on changed; its own text wasn't flagged).
1131
- *
1132
- * `'saved'` is NOT emitted from this code path — saves take the dedicated
1133
- * `DataClientProtocol.onDocumentSaved` channel; adopters that want a
1134
- * unified update stream synthesise `'saved'` in their bridge layer.
1135
- */
1136
- protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'] {
1137
- const last = this.lastBuildUpdate;
1138
- if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
1139
- return 'deleted';
1140
- }
1141
- if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
1142
- return 'changed';
1143
- }
1144
- return 'rebuilt';
1145
- }
1146
-
1147
1516
  /**
1148
1517
  * Subscribe to the project tier's change channel and re-fan registry
1149
1518
  * diffs into per-project wire notifications. The internal
@@ -1187,20 +1556,6 @@ export class DataServer<
1187
1556
  }
1188
1557
  }
1189
1558
 
1190
- /**
1191
- * Resolve the wire-level `sourceClientId` for `document`'s events — the client
1192
- * that authored its current version, from the version-author history on
1193
- * `HydraniumTextDocuments`. The protocol-level counterpart of the internal
1194
- * `AstDocumentManager.getAuthor`: a framework-internal rebuild has no author,
1195
- * so this surfaces the {@link UNKNOWN_CLIENT_ID} presentation default. Adopters
1196
- * that rebuild through non-text-document channels override to derive a
1197
- * source id of their own.
1198
- */
1199
- protected resolveSourceClientId(document: LangiumDocument): string {
1200
- const author = this.services.workspace.TextDocuments.getAuthor(document.textDocument.uri, document.textDocument.version);
1201
- return author ?? UNKNOWN_CLIENT_ID;
1202
- }
1203
-
1204
1559
  // --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
1205
1560
  // Computed in THIS process: the data-server child holds the model store, so
1206
1561
  // these snapshots reflect the heap that actually carries the workspace
@@ -1243,7 +1598,7 @@ export class DataServer<
1243
1598
 
1244
1599
  async stopProfiling(args: StopProfilingArgs): Promise<string> {
1245
1600
  if (!this.activeProfile) {
1246
- throw new Error('No profiling capture is active; call startProfiling first.');
1601
+ throw noActiveProfileError();
1247
1602
  }
1248
1603
  const capture = this.activeProfile;
1249
1604
  this.activeProfile = undefined;
@@ -1262,7 +1617,7 @@ export class DataServer<
1262
1617
  /** Resolve a partial options object into a fully-defaulted form. */
1263
1618
  protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions {
1264
1619
  const additionalMethods = partial.additionalMethods ?? [];
1265
- const builtIn = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS] as readonly string[];
1620
+ const builtIn: readonly string[] = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS];
1266
1621
  const overlap = additionalMethods.filter(name => builtIn.includes(name));
1267
1622
  if (overlap.length > 0) {
1268
1623
  throw new Error(
@@ -1276,7 +1631,8 @@ export class DataServer<
1276
1631
  methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
1277
1632
  additionalMethods,
1278
1633
  excludedMethods: partial.excludedMethods ?? [],
1279
- diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
1634
+ diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
1635
+ referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
1280
1636
  };
1281
1637
  }
1282
1638
  }