@hydranium/data-server 1.0.0-next.28 → 1.0.0-next.281

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.
@@ -10,14 +10,22 @@
10
10
  import {
11
11
  createRpcProxy,
12
12
  defineMessage,
13
+ describeErrorWithStack,
13
14
  DisposableCollection,
15
+ HYDRANIUM_ERROR_CODES,
14
16
  isDocumentSource,
15
17
  isElementSource,
18
+ isResponseError,
16
19
  isSyntheticSource,
20
+ messageData,
17
21
  messageError,
18
22
  ReferenceSource,
23
+ SessionClosedError,
24
+ TIMED_OUT,
19
25
  type CloseModelArgs,
26
+ type HydraniumMessageData,
20
27
  type HydraniumResponseError,
28
+ type CanonicalUri,
21
29
  type Disposable,
22
30
  type ElementSource,
23
31
  type FindNextNameArgs,
@@ -29,10 +37,16 @@ import {
29
37
  type ReferenceContext,
30
38
  type ReferenceRequest,
31
39
  type ReferenceTarget,
40
+ type TransferModelSnapshot,
41
+ type ModelVersion,
42
+ type TextState,
32
43
  type Tracer,
33
44
  type TransferDiagnostic,
34
- type TransferDocument,
35
- type TransferElement
45
+ TransferDocument,
46
+ type TransferSavedDocument,
47
+ type TransferElement,
48
+ UNKNOWN_CLIENT_ID,
49
+ textHash
36
50
  } from '@hydranium/protocol';
37
51
  import {
38
52
  DATA_SERVER_DIAGNOSTICS_METHODS,
@@ -45,24 +59,31 @@ import {
45
59
  type StartProfilingArgs,
46
60
  type StopProfilingArgs,
47
61
  type WriteServerHeapSnapshotArgs,
62
+ type CloseSessionArgs,
63
+ type CreateModelDocumentArgs,
64
+ type CreateSessionArgs,
48
65
  type GetModelDocumentArgs,
49
66
  type GetProjectForUriArgs,
67
+ type ProjectChangeReason,
68
+ type TransferDeleteDocumentArgs,
69
+ type TransferPersistDocumentArgs,
50
70
  type TransferSaveDocumentArgs,
51
71
  type WatchModelDocumentArgs,
52
72
  type TransferDocumentSavedEvent,
53
73
  type TransferDocumentUpdatedEvent,
54
- type TransferUpdateDocumentArgs
74
+ type TransferUpdateDocumentArgs,
75
+ type TransferUpdateDocumentsArgs
55
76
  } from '@hydranium/protocol/data';
56
- import { REVERT_ON_CLOSE_CLIENT_ID, UNKNOWN_CLIENT_ID } from '@hydranium/core';
77
+ import { DOCUMENT_RELEASE_CLIENT_ID } from '@hydranium/core';
57
78
  import { defaultDataServerDiagnostics } from './default-diagnostics.js';
58
79
 
59
80
  /**
60
81
  * Raised when a profiling command arrives with no capture running.
61
82
  *
62
- * A `ResponseError` rather than a plain `Error` so the identity survives the
63
- * hop: an unwrapped throw inside an RPC handler reaches the client as a generic
64
- * internal error, which carries no code for a caller to switch on and no
65
- * envelope for a translating host to read.
83
+ * A `ResponseError` rather than a plain `Error` so the identity survives to the
84
+ * response boundary, which is where the message is rendered. An unwrapped throw
85
+ * reaches the client as a generic internal error instead: no code for a caller
86
+ * to switch on, and nothing for the boundary to render from.
66
87
  */
67
88
  export const NO_ACTIVE_PROFILE = defineMessage(
68
89
  'hydranium/data-server/no-active-profile',
@@ -73,23 +94,54 @@ export const NO_ACTIVE_PROFILE = defineMessage(
73
94
  * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
74
95
  * survives reconstruction and is what a caller switches on.
75
96
  */
76
- export const NO_ACTIVE_PROFILE_CODE = 1002;
97
+ export const NO_ACTIVE_PROFILE_CODE = HYDRANIUM_ERROR_CODES.noActiveProfile;
77
98
 
78
99
  export const noActiveProfileError = (): HydraniumResponseError => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
79
100
 
101
+ /**
102
+ * Raised when a reference question's wait for the build exceeds
103
+ * {@link DataServerOptions.referenceSettleTimeoutMs}.
104
+ *
105
+ * A `ResponseError` because a class name does not cross RPC: without the code a
106
+ * wire client cannot tell a wedged build from a reference that resolves to
107
+ * nothing, which is the distinction the wait exists to keep.
108
+ */
109
+ export const REFERENCE_SETTLE_TIMEOUT = defineMessage(
110
+ 'hydranium/data-server/reference-settle-timeout',
111
+ 'The model is still being processed; try again in a moment.'
112
+ );
113
+
114
+ /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
115
+ export const REFERENCE_SETTLE_TIMEOUT_CODE = HYDRANIUM_ERROR_CODES.referenceSettleTimeout;
116
+
117
+ /** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */
118
+ export const referenceSettleTimeoutError = (elapsedMs: number): ResponseError<HydraniumMessageData & { readonly elapsedMs: number }> =>
119
+ new ResponseError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT.format(), {
120
+ elapsedMs,
121
+ ...messageData(REFERENCE_SETTLE_TIMEOUT)
122
+ });
123
+
80
124
  import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
81
125
  import type {
82
- ClientTextDocumentChangeEvent,
126
+ ClientSession,
127
+ ClientSessionWriteArgs,
83
128
  HydraniumLanguageServices,
84
129
  LogNameOptions,
130
+ AstDiagnostic,
131
+ AstDocument,
132
+ AstDocumentSavedEvent,
133
+ EncodedTransferDocument,
134
+ ModelDeletedEvent,
135
+ ModelDirtyChangedEvent,
85
136
  ModelService,
137
+ ModelUpdatedEvent,
86
138
  ProjectChangeEvent,
87
139
  ServerSharedServices,
140
+ SessionEndCause,
88
141
  TransferEncoder
89
142
  } from '@hydranium/core';
90
- import type { TextDocument } from 'vscode-languageserver-textdocument';
91
- import { type AstNode, DocumentState, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
92
- import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
143
+ import { type AstNode, DocumentState, UriUtils, type URI } from '@hydranium/langium';
144
+ import { type MessageConnection, ResponseError } from 'vscode-jsonrpc';
93
145
 
94
146
  /**
95
147
  * Domain separator between text and diagnostics inputs of
@@ -100,34 +152,11 @@ import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
100
152
  const FINGERPRINT_SEPARATOR = '\0';
101
153
 
102
154
  /**
103
- * Portable, non-cryptographic 64-bit fingerprint hash (cyrb53), returning a
104
- * 16-char hex digest.
105
- *
106
- * **A cryptographic hash via `node:crypto` is the wrong trade**: the
107
- * fingerprint only needs a stable signal that `(text, diagnostics)` changed
108
- * between emissions, and a `node:*` import would cost
109
- * `@hydranium/data-server` its browser-portability. Parts are fed
110
- * incrementally, char by char, so multi-MB document text is never
111
- * concatenated into one string.
155
+ * `LSPErrorCodes.ServerCancelled`, with which Langium's document wait rejects
156
+ * for a URI that has no document; `vscode-languageserver-protocol` is not a
157
+ * dependency of this package.
112
158
  */
113
- function fingerprintHash(parts: readonly string[]): string {
114
- let h1 = 0xdeadbeef;
115
- let h2 = 0x41c6ce57;
116
- for (const part of parts) {
117
- for (let i = 0; i < part.length; i++) {
118
- const ch = part.charCodeAt(i);
119
- h1 = Math.imul(h1 ^ ch, 2654435761);
120
- h2 = Math.imul(h2 ^ ch, 1597334677);
121
- }
122
- }
123
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
124
- h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
125
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
126
- h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
127
- const high = (h2 >>> 0).toString(16).padStart(8, '0');
128
- const low = (h1 >>> 0).toString(16).padStart(8, '0');
129
- return high + low;
130
- }
159
+ const SERVER_CANCELLED = -32802;
131
160
 
132
161
  /**
133
162
  * Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
@@ -140,26 +169,32 @@ function fingerprintHash(parts: readonly string[]): string {
140
169
  * folded in on a cascade rebuild that leaves the document's own text
141
170
  * untouched. Safe for any adopter whose AST extensions fold derived state
142
171
  * into the transfer projection (the framework norm).
143
- * - `'text-diagnostics'` — the cheaper `getText()` + diagnostics hash. An
144
- * opt-DOWN for adopters that fold no derived state and want to avoid the
145
- * transfer-encode per phase event.
172
+ * - `'text-diagnostics'` — the cheaper parsed-text + diagnostics hash. An
173
+ * opt-DOWN for adopters that fold no derived state and want to avoid
174
+ * stringifying the transfer root per phase event.
146
175
  */
147
176
  export type FingerprintStrategy = 'transfer-document' | 'text-diagnostics';
148
177
 
149
- /** Hash a document's raw text + diagnostics — the `'text-diagnostics'` strategy. */
150
- function textDiagnosticsFingerprint(document: LangiumDocument): string {
151
- return fingerprintHash([document.textDocument.getText(), FINGERPRINT_SEPARATOR, JSON.stringify(document.diagnostics ?? [])]);
178
+ /**
179
+ * Hash `text`, the text the model was parsed from, + `model`'s diagnostics — the `'text-diagnostics'` strategy.
180
+ * The text comes from the root's ledger record or CST, as the document's own may have moved on,
181
+ * and a repair in place leaves the CST on the unrepaired text;
182
+ * a root built without a CST hashes as `'transfer-document'`.
183
+ * Absent diagnostics must hash apart from `[]`, as in {@link transferDocumentFingerprint}.
184
+ */
185
+ function textDiagnosticsFingerprint(text: string | undefined, model: EncodedTransferDocument<TransferElement, unknown>['model']): string {
186
+ return text === undefined
187
+ ? transferDocumentFingerprint(model)
188
+ : textHash([text, FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
152
189
  }
153
190
 
154
- /** Hash an encoded transfer document's root + diagnostics — the `'transfer-document'` strategy. */
155
- function transferDocumentFingerprint(transferDocument: Pick<TransferDocument<TransferElement, unknown>, 'root' | 'diagnostics'>): string {
156
- // null, not undefined: `JSON.stringify(undefined)` yields undefined rather
157
- // than a string, putting a non-string into the hash inputs.
158
- return fingerprintHash([
159
- JSON.stringify(transferDocument.root ?? null),
160
- FINGERPRINT_SEPARATOR,
161
- JSON.stringify(transferDocument.diagnostics)
162
- ]);
191
+ /**
192
+ * Hash an encoded model's root + diagnostics — the `'transfer-document'` strategy.
193
+ * Absent diagnostics must hash apart from `[]`: a client skipping a render on an
194
+ * equal hash would otherwise miss a validation that found nothing.
195
+ */
196
+ function transferDocumentFingerprint(model: EncodedTransferDocument<TransferElement, unknown>['model']): string {
197
+ return textHash([JSON.stringify(model.root), FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
163
198
  }
164
199
  /**
165
200
  * `logAfterMs` threshold passed to {@link Tracer.time} around
@@ -180,12 +215,13 @@ export interface DataServerOptions extends LogNameOptions {
180
215
  * (`DataClientProtocol.onDocumentUpdated`).
181
216
  *
182
217
  * **Subscription dispatch only** — distinct from the synchronous RPC
183
- * response phase. The lifecycle reads/writes (`getModelDocument` /
184
- * `updateModelDocument` / `saveModelDocument`) settle at the
185
- * integrity-settled landmark (`IntegrityService.SettledState`); a
186
- * read additionally upgrades to `Validated` per call when
187
- * {@link GetModelDocumentArgs.includeDiagnostics} is set. This option
188
- * controls only the async notification phase.
218
+ * response phase. A read (`getModelDocument`) settles at the
219
+ * integrity-settled landmark (`IntegrityService.SettledState`), or at
220
+ * `Validated` when {@link GetModelDocumentArgs.includeDiagnostics} is set.
221
+ * A write (`updateModelDocument` / `updateModelDocuments` /
222
+ * `saveModelDocument`) answers once its document is validated, as a
223
+ * session's write does. This option controls only the async notification
224
+ * phase.
189
225
  *
190
226
  * Default: `DocumentState.Validated` — validation is the last builder
191
227
  * phase and produces the full diagnostic set, so subscription events fired
@@ -226,6 +262,22 @@ export interface DataServerOptions extends LogNameOptions {
226
262
  */
227
263
  readonly fingerprintStrategy?: FingerprintStrategy;
228
264
 
265
+ /**
266
+ * How long a reference question waits for the build to reach `Linked` before
267
+ * failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the
268
+ * wait resolves off a build-phase notification, so a build cancelled below
269
+ * `Linked` with nothing after it leaves the request unanswered for the life
270
+ * of the server.
271
+ *
272
+ * Expiry rejects rather than reading the index anyway: the unsettled index
273
+ * is what the wait keeps the caller away from, so falling through to it on a
274
+ * slow build reinstates the fault — and on a name proposal persists it.
275
+ *
276
+ * Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace
277
+ * still reaching `Linked` for the first time.
278
+ */
279
+ readonly referenceSettleTimeoutMs?: number;
280
+
229
281
  /**
230
282
  * Wire-method namespace for both inbound request handlers and the
231
283
  * outbound notification client proxy. Defaults to
@@ -283,15 +335,20 @@ export interface DataServerOptions extends LogNameOptions {
283
335
  * When supplied, every inbound data-server RPC is timed into this collector
284
336
  * (via the `createRpcProxy` binding) and exposed through
285
337
  * {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an
286
- * LSP connection can pass the SAME collector to
287
- * `instrumentLspConnection(connection, latency)` so one report covers both
288
- * heads. Absent by default (no timing overhead).
338
+ * LSP connection can pass the SAME collector through `lspLatencyOptions` to
339
+ * that connection, so one report covers both heads. Absent by default (no
340
+ * timing overhead).
289
341
  */
290
342
  readonly latency?: LatencyCollector;
291
343
  }
292
344
 
293
- /** Fully-resolved variant — every field set, used internally after merging defaults. */
294
- interface ResolvedDataServerOptions {
345
+ /**
346
+ * Fully-resolved variant of {@link DataServerOptions} — every field set, after
347
+ * merging defaults. Returned by the `protected`
348
+ * {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so
349
+ * an adopter changing how defaults resolve has to name it.
350
+ */
351
+ export interface ResolvedDataServerOptions {
295
352
  readonly subscriptionPhase: DocumentState;
296
353
  readonly fingerprintStrategy: FingerprintStrategy;
297
354
  readonly methodNamespace: string;
@@ -299,6 +356,41 @@ interface ResolvedDataServerOptions {
299
356
  readonly excludedMethods: readonly string[];
300
357
  /** Always resolved — to the caller's, or to the platform default. */
301
358
  readonly diagnostics: DataServerDiagnosticsProvider;
359
+ readonly referenceSettleTimeoutMs: number;
360
+ }
361
+
362
+ /**
363
+ * What a {@link DataServer} keeps per canonical URI, in the `protected`
364
+ * {@link DataServer.uriWatchRecords}. A record lives while it has a watcher
365
+ * or a release mark; {@link DataServer.pruneUriWatchRecord} enforces that on
366
+ * every path that removes either, so a record with no watcher has a release
367
+ * broadcast pending. Test the size of {@link DataServerUriWatchRecord.watchers}, not the
368
+ * record's presence, for "watched".
369
+ */
370
+ export interface DataServerUriWatchRecord {
371
+ /** The client ids watching the URI; save, dirty and phase events go out only while it is non-empty, a pending release mark aside. */
372
+ readonly watchers: Set<string>;
373
+ /** 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. */
374
+ fingerprint?: string;
375
+ /**
376
+ * The version {@link DataServerUriWatchRecord.fingerprint} was taken at; an
377
+ * event goes out when either moves. Not {@link DataServerUriWatchRecord.sentVersion}:
378
+ * a first watch sets this and sends nothing, so the next event at its
379
+ * version still carries the manager's attribution.
380
+ */
381
+ fingerprintVersion?: ModelVersion;
382
+ /** Set by {@link DataServer.subscribeToModelReleases} once a release happened: its broadcast, the next phase event, goes out even without a watcher. */
383
+ releaseBroadcastPending?: boolean;
384
+ /**
385
+ * The version of an open document the last event sent was built at. The
386
+ * version sent again goes out as `'rebuilt'` from no client: the manager
387
+ * counts a version delivered only once its `Validated` listeners ran, so a
388
+ * build cancelled after the subscription phase would send it as a change
389
+ * twice. Only while the store has the document open: without it, a
390
+ * document can keep one version through changes of its file, so its events
391
+ * keep the manager's attribution.
392
+ */
393
+ sentVersion?: number;
302
394
  }
303
395
 
304
396
  /**
@@ -322,13 +414,19 @@ interface ResolvedDataServerOptions {
322
414
  * adopters subclass ONLY when they need to decorate wire returns or
323
415
  * notifications. The usual adoption path is DI rebinds alone.
324
416
  *
417
+ * **`TTransfer` is not checked.** It declares the union of the transfer roots
418
+ * the workspace's languages produce. Which root a document has is known only
419
+ * at runtime, from its language, so a `TTransfer` missing a language compiles.
420
+ *
325
421
  * Lifecycle: the constructor registers framework request handlers (plus
326
422
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
327
423
  * builds the {@link DataClientProtocol} notification proxy on the same
328
424
  * connection in one {@link createRpcProxy} call (binding `this` as its
329
- * `localTarget`) under the configured namespace, and subscribes one
330
- * `DocumentBuilder.onDocumentPhase` listener per configured phase that
331
- * dispatches subscription events via `clientProxy.onDocumentUpdated`.
425
+ * `localTarget`) under the configured namespace, and follows documents
426
+ * through `ModelService`'s events: at the configured phase, `onModelUpdated`
427
+ * dispatches per-document `clientProxy.onDocumentUpdated` for watched URIs and
428
+ * `onModelsBuilt` a single `clientProxy.onDocumentsBuilt` naming the batch's
429
+ * unwatched documents.
332
430
  *
333
431
  * The data-server requires the full {@link ServerSharedServices}
334
432
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -356,87 +454,36 @@ export class DataServer<
356
454
  * Framework defaults, exposed so an adopter can spread them when
357
455
  * extending rather than restate a value the framework may change.
358
456
  */
359
- static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>> = {
360
- subscriptionPhase: DocumentState.Validated
457
+ static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>> = {
458
+ subscriptionPhase: DocumentState.Validated,
459
+ referenceSettleTimeoutMs: 60_000
361
460
  };
362
461
 
363
462
  protected readonly options: ResolvedDataServerOptions;
364
- /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
365
- protected readonly subscriptions = new Map<string, Set<string>>();
463
+ /** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
464
+ protected readonly uriWatchRecords = new Map<string, DataServerUriWatchRecord>();
366
465
  /**
367
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
368
- * connection.
369
- *
370
- * Kept because the document store releases a client's hold only from an
371
- * explicit close, and a client that dies without closing would otherwise keep
372
- * the document open forever — resident, and with its last-close revert
373
- * suppressed. The store has no notion of which connection a clientId reached
374
- * it over, so the connection-scoped set has to live here; teaching it a client
375
- * identity is the more robust and much larger alternative.
466
+ * Per client id, the key each URI it watched resolved to when it watched.
467
+ * An unwatch looks the key up here: once a file is gone, a symlink to it
468
+ * no longer resolves to the key the watch is under.
376
469
  */
377
- protected readonly openedDocuments = new Map<string, Set<string>>();
378
- /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
379
- protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
380
- protected readonly disposables = new DisposableCollection();
470
+ protected readonly watchKeys = new Map<string, Map<string, string>>();
381
471
  /**
382
- * Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
383
- * `reason` discrimination on outbound `onDocumentUpdated` notifications:
384
- * a URI in the `changed` list emits `'changed'`, in `deleted` emits
385
- * `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
386
- * URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
387
- * the LSP side, so reason fidelity stays consistent between heads.
472
+ * The live client sessions this connection registered, by client id. A
473
+ * document request carrying one of these ids acts as that session; one
474
+ * carrying any other id fails. A session leaves once it ends, so a
475
+ * connection that registers many over its life does not accumulate them.
388
476
  */
389
- protected lastBuildUpdate?: { changed: readonly URI[]; deleted: readonly URI[] };
477
+ protected readonly clientSessions = new Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer>>();
390
478
  /**
391
- * Per-URI hash of the last emitted (text + diagnostics) state,
392
- * used by {@link dispatchPhaseEvent} to suppress duplicate
393
- * `onDocumentUpdated` notifications for rebuilds that produce no
394
- * observable change since the last emit.
395
- *
396
- * Two scenarios routinely produce such rebuilds:
397
- * 1. **Refresh-triggered rebuilds.** When a second client attaches to a
398
- * document already open in another client,
399
- * `HydraniumTextDocuments.refreshContent` fires `onDidChangeContent`
400
- * purely to re-trigger the build pipeline — the text and diagnostics
401
- * are identical to the prior emit.
402
- * 2. **Cascade rebuilds with no diagnostic delta.** Langium rebuilds a
403
- * document when a dependency changes; if the rebuild produces the
404
- * same diagnostics, there is nothing new to communicate to subscribers.
405
- *
406
- * Without this filter, both scenarios reach subscribers as wire-side
407
- * `'changed'` events. A subscriber that interprets `'changed'` as
408
- * "another client wrote new content" and resets its in-memory root to
409
- * the server view then misreads the spurious event as a concurrent
410
- * third-party write and loses the user's edits.
411
- *
412
- * Initialised on {@link watchModelDocument} to the current
413
- * document fingerprint so the FIRST phase event after a fresh
414
- * subscription is also de-duplicated against the state subscribers
415
- * obtained via `getModelDocument` — they do not need a redundant phase
416
- * notification for the state they just fetched.
417
- *
418
- * Cleared in {@link unwatchModelDocument} when the last
419
- * subscriber for a URI leaves so memory does not accumulate.
420
- *
421
- * Stored as a cyrb53 hex digest (16 chars per URI) rather than the raw
422
- * text + diagnostics serialisation so the memory cost is constant in
423
- * document size. See {@link computeDocumentFingerprint} for the inputs.
479
+ * Typed client proxy — sends `data-server/on*` notifications back over the same wire.
480
+ * The proxy sends any `on[A-Z]*` name other than `onDidOpenConnection` and
481
+ * `onDidCloseConnection`, for which it returns its own events, so a subclass
482
+ * with notifications of its own narrows only the type:
483
+ * `declare protected readonly clientProxy: TheirClient`.
424
484
  */
425
- protected readonly lastEmittedFingerprint = new Map<string, string>();
426
- /**
427
- * URIs whose LAST client just closed. The update handler rebuilds such a
428
- * document from its disk content (discarding unsaved in-session edits),
429
- * but {@link dispatchPhaseEvent} gates on the subscription map — and the
430
- * last close typically also removed the last watcher, so consumers that
431
- * only ever fetch via `getModelDocument` would keep showing the
432
- * discarded state forever. Marked on the last-close transition (see
433
- * {@link subscribeToTextDocumentCloses}) and consumed by
434
- * {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
435
- * phase event even without a subscription — de-duplicated against
436
- * {@link lastEmittedFingerprint} where an entry survives, so a close
437
- * whose disk state equals the last emitted state stays silent.
438
- */
439
- protected readonly pendingRevertBroadcasts = new Set<string>();
485
+ protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
486
+ protected readonly disposables = new DisposableCollection();
440
487
  protected readonly tracer: Tracer;
441
488
  /** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
442
489
  protected activeProfile?: DataServerProfileCapture;
@@ -445,27 +492,23 @@ export class DataServer<
445
492
  /** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */
446
493
  protected readonly latency?: LatencyCollector;
447
494
  /** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */
448
- protected readonly encoder: TransferEncoder<unknown, TDiagnostic>;
495
+ protected readonly encoder: TransferEncoder<TDiagnostic>;
449
496
  /**
450
497
  * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
451
- * The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
452
- * carry LSP-shape diagnostics in their AstDocument (e.g. an adopter's LSP-shape diagnostic type)
453
- * while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
454
- * `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
455
- * to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
498
+ * Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
499
+ * {@link encoder} converts one into the other on the way out.
456
500
  */
457
- protected readonly modelService: ModelService<AstNode, unknown, TTransfer>;
501
+ protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
458
502
 
459
503
  constructor(
460
504
  protected readonly connection: MessageConnection,
461
- protected readonly services: ServerSharedServices<TProject>,
505
+ protected readonly services: ServerSharedServices<TProject, TDiagnostic>,
462
506
  options: DataServerOptions = {}
463
507
  ) {
464
508
  this.options = this.resolveOptions(options);
465
509
  this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
466
510
  // DI-bound: adopters rebind `services.model.TransferEncoder` /
467
- // `services.model.ModelService` with their own subclasses. Slot types use the
468
- // framework upper bounds; the casts below narrow to this instance's generics.
511
+ // `services.model.ModelService` with their own subclasses.
469
512
  const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
470
513
  if (!encoder || !modelService) {
471
514
  throw new Error(
@@ -473,8 +516,8 @@ export class DataServer<
473
516
  'Did you compose `createServerSharedModule(ctx)` into your shared module?'
474
517
  );
475
518
  }
476
- this.encoder = encoder as TransferEncoder<unknown, TDiagnostic>;
477
- this.modelService = modelService as ModelService<AstNode, unknown, TTransfer>;
519
+ this.encoder = encoder;
520
+ this.modelService = modelService;
478
521
  const excluded = new Set<string>(this.options.excludedMethods);
479
522
  const registeredMethods = [
480
523
  ...DATA_SERVER_PROTOCOL_METHODS,
@@ -490,38 +533,43 @@ export class DataServer<
490
533
  methodNamespace: this.options.methodNamespace,
491
534
  localTarget: this,
492
535
  localMethods: registeredMethods as readonly (keyof this & string)[],
493
- latency: this.latency
536
+ latency: this.latency,
537
+ // Bound at the chokepoint rather than per handler, so an adopter's
538
+ // `additionalMethods` are rendered on the same terms as the
539
+ // framework's own rejections.
540
+ renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
494
541
  });
495
- this.disposables.push(
496
- this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
497
- this.lastBuildUpdate = { changed, deleted };
498
- })
499
- );
500
- this.subscribeToDocumentBuilder();
542
+ this.disposables.push(this.modelService.onModelDeleted(event => this.dispatchDeleteEvent(event)));
543
+ this.subscribeToModelUpdates();
501
544
  this.subscribeToTextDocumentSaves();
502
- this.subscribeToTextDocumentCloses();
545
+ this.subscribeToDirtyChanges();
546
+ this.subscribeToModelReleases();
503
547
  this.subscribeToProjectManager();
504
548
  // Self-register teardown so an adopter that keeps no reference to the
505
549
  // server still releases per-connection state, with no lifecycle hook of
506
- // its own. See `dispose`.
507
- this.disposables.push(connection.onClose(() => this.dispose()));
550
+ // its own. The client did not close anything itself, so its sessions end
551
+ // as lost and each document it was the last to have open waits out the
552
+ // store's release grace. See `dispose`.
553
+ this.disposables.push(connection.onClose(() => this.dispose('lost')));
508
554
  }
509
555
 
510
556
  /**
511
557
  * Release everything the constructor wired up — the bound protocol
512
- * handlers and every listener — and clear the subscription map and the
513
- * per-URI emission-fingerprint cache, so a long-lived shared services
514
- * bundle does not retain per-connection memory after the connection
515
- * closes. Also closes every document still open over this connection (see
516
- * {@link closeOpenDocuments}), which is the SHARED store's state rather than
517
- * this server's and so outlives the connection unless released here.
558
+ * handlers and every listener — and clear {@link uriWatchRecords}, so a
559
+ * long-lived shared services bundle does not retain per-connection memory
560
+ * after the connection closes. Also ends every session this connection registered, which closes
561
+ * every document it has open: the SHARED store's state rather than this
562
+ * server's, which outlives the connection unless released here.
518
563
  *
519
- * Idempotent: subsequent calls are no-ops. Self-fires on
520
- * `connection.onClose` so adopters who don't hold a reference still
521
- * get per-connection cleanup; adopters that DO hold a reference may
522
- * call `dispose()` directly for early teardown.
564
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
565
+ * connection closes, so adopters who don't hold a reference still get
566
+ * per-connection cleanup; adopters that DO hold a reference may call
567
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
568
+ * `'closed'` releases every document whose last open they close at once,
569
+ * and `'lost'`, the connection's own close, lets each wait out the release
570
+ * grace.
523
571
  */
524
- dispose(): void {
572
+ dispose(cause: SessionEndCause = 'closed'): void {
525
573
  this.disposed = true;
526
574
  // Release an in-flight interactive capture so the process-wide inspector
527
575
  // singleton is not left active after the connection closes.
@@ -530,104 +578,150 @@ export class DataServer<
530
578
  this.activeProfile = undefined;
531
579
  void capture.stop({}).catch(() => undefined);
532
580
  }
533
- // AFTER `disposables.dispose()`, deliberately: closing a document fires
534
- // `onDidClose`, and this server's own close listener would otherwise mark a
535
- // revert broadcast for a connection that is already gone.
581
+ // AFTER `disposables.dispose()`, deliberately: ending a session releases
582
+ // each document it was the last to hold, and this server's own
583
+ // `onModelReleased` subscription would otherwise mark a release broadcast
584
+ // for a connection that is already gone.
536
585
  this.disposables.dispose();
537
- this.closeOpenDocuments();
538
- this.subscriptions.clear();
539
- this.lastEmittedFingerprint.clear();
540
- this.pendingRevertBroadcasts.clear();
586
+ for (const [clientId, session] of this.clientSessions) {
587
+ this.endSession(clientId, session, cause);
588
+ }
589
+ this.uriWatchRecords.clear();
590
+ this.watchKeys.clear();
541
591
  }
542
592
 
543
593
  // ============================================================
544
- // DataServerProtocol implementation — delegates to ModelService.
594
+ // DataServerProtocol implementation
545
595
  // ============================================================
546
596
  //
547
- // The lifecycle methods (`get` / `update` / `save` / `ready`) forward
548
- // straight to `ModelService` and encode the returned `AstDocument` on
549
- // the wire boundary via `encoder.astDocumentToTransferDocument`.
550
- // Adopters customising lifecycle behaviour (normalisation, supersession,
551
- // settled-phase choice, etc.) override on the ModelService subclass —
552
- // no override on DataServer is needed.
553
-
554
- async openModelDocument(args: OpenModelArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
555
- // Register the editor session (idempotent — `ModelService.open` refreshes
556
- // an already-open document rather than re-opening), then return the built
557
- // state at the configured target phase. The one-shot snapshot; subsequent
558
- // build-phase events arrive via `watchModelDocument`.
559
- await this.modelService.open(args);
560
- // Record the hold so `dispose` can release it for a client that never
561
- // closes. Keyed by the URI as given, because that is what `close` takes.
562
- let holders = this.openedDocuments.get(args.uri);
563
- if (!holders) {
564
- holders = new Set<string>();
565
- this.openedDocuments.set(args.uri, holders);
597
+ // Reads go to `ModelService`; a request that opens or writes a document
598
+ // goes to the session this connection registered under its `clientId`.
599
+ // Each answer is encoded on the wire boundary via
600
+ // `encoder.astDocumentToTransferDocument`. To change how documents are
601
+ // read, override on the ModelService subclass; to change how they are
602
+ // written, on the session class the bound `ClientSessionFactory` builds.
603
+
604
+ async createSession(args: CreateSessionArgs): Promise<void> {
605
+ // After teardown nothing would ever end a session registered now, and its
606
+ // id would stay taken for the life of the process.
607
+ if (this.disposed) {
608
+ throw new SessionClosedError(args.clientId);
566
609
  }
567
- holders.add(args.clientId);
568
- const document = await this.getModelDocument({ uri: args.uri });
569
- // Project the authoritative client-facing version onto the open snapshot.
570
- // `getModelDocument` encodes the freshly-built AST snapshot, whose version
571
- // is the `LangiumDocument`'s own `textDocument.version`. That lags the
572
- // multi-client synced version whenever the open seeded the synced document
573
- // with a caller-supplied version id — and the synced version is what
574
- // `ModelService.update`'s optimistic-concurrency gate compares
575
- // `baseVersion` against, so reporting the snapshot's would make the
576
- // caller's first tagged write self-conflict. A genuine concurrent edit
577
- // still trips the gate and is reconciled by the caller's replay rather
578
- // than predicted here.
579
- return { ...document, version: this.services.workspace.TextDocuments.version(args.uri) };
610
+ const session = this.modelService.createSession(args.label, args.clientId, { resumeToken: args.resumeToken });
611
+ this.clientSessions.set(args.clientId, session);
612
+ // A session also ends without closeSession, as when a client registers
613
+ // again on another connection, and its watches and entry here would
614
+ // otherwise outlive it.
615
+ session.onDidDispose(cause => {
616
+ // A session class may report its end late, once a replacement holds
617
+ // the id here; the replacement's entry and watches stay.
618
+ if (this.clientSessions.get(args.clientId) !== session) {
619
+ return;
620
+ }
621
+ this.dropWatches(args.clientId);
622
+ this.clientSessions.delete(args.clientId);
623
+ this.tracer.debug(`Forget session ${args.clientId}: it ended as ${cause}`);
624
+ });
580
625
  }
581
626
 
582
- async closeModelDocument(args: CloseModelArgs): Promise<void> {
583
- // Closing a session also releases its watch for (uri, clientId) — a
584
- // forgotten unwatch would otherwise leak phase-event dispatch until the
585
- // connection closes. Idempotent: a close without a prior watch is a no-op.
586
- await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
587
- this.forgetOpenDocument(args.uri, args.clientId);
588
- await this.modelService.close(args);
627
+ /** End a session this connection registered. */
628
+ async closeSession(args: CloseSessionArgs): Promise<void> {
629
+ const session = this.clientSessions.get(args.clientId);
630
+ if (session) {
631
+ this.endSession(args.clientId, session);
632
+ }
633
+ }
634
+
635
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
636
+ protected endSession(
637
+ clientId: string,
638
+ session: ClientSession<AstNode, AstDiagnostic, TTransfer>,
639
+ cause: SessionEndCause = 'closed'
640
+ ): void {
641
+ this.dropWatches(clientId);
642
+ session.dispose(cause);
643
+ }
644
+
645
+ protected dropWatches(clientId: string): void {
646
+ this.watchKeys.delete(clientId);
647
+ for (const [uri, record] of this.uriWatchRecords) {
648
+ if (record.watchers.delete(clientId)) {
649
+ this.pruneUriWatchRecord(uri);
650
+ }
651
+ }
652
+ }
653
+
654
+ async createModelDocument(args: CreateModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
655
+ const session = this.requireSession(args.clientId);
656
+ await session.create(args.uri, args.text);
657
+ return this.openedSnapshot(args.uri, () => session.close(args.uri));
658
+ }
659
+
660
+ async updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>[]> {
661
+ const astDocuments = await this.requireSession(args.clientId).updateAll({
662
+ updates: args.updates.map(update => this.toSessionWrite(update))
663
+ });
664
+ return astDocuments.map(astDocument => this.encodeDocument(astDocument));
589
665
  }
590
666
 
591
667
  /**
592
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
593
- * close it a second time. Idempotent.
668
+ * The session write a wire write request carries. Only the fields a session
669
+ * takes: a field an adopter adds to a request reaches the session only
670
+ * through an override of this.
594
671
  */
595
- protected forgetOpenDocument(uri: string, clientId: string): void {
596
- const holders = this.openedDocuments.get(uri);
597
- if (!holders) {
598
- return;
599
- }
600
- holders.delete(clientId);
601
- if (holders.size === 0) {
602
- this.openedDocuments.delete(uri);
672
+ protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer> {
673
+ return { uri: request.uri, model: request.model, baseVersion: request.baseVersion };
674
+ }
675
+
676
+ /**
677
+ * The session this connection registered under `clientId`, which every
678
+ * document request acts as. An id that is not one fails with the
679
+ * closed-session code: opening or writing under it would leave an open that
680
+ * no session end ever closes.
681
+ */
682
+ protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer> {
683
+ const session = this.clientSessions.get(clientId);
684
+ if (!session) {
685
+ throw new SessionClosedError(clientId, 'The client session is not registered on this connection.');
603
686
  }
687
+ return session;
688
+ }
689
+
690
+ async openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
691
+ const session = this.requireSession(args.clientId);
692
+ const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
693
+ await session.open(args.uri, args.options);
694
+ // A repeat open keeps the earlier one, which is still in use.
695
+ return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
604
696
  }
605
697
 
606
698
  /**
607
- * Close every document still open over this connection, for the clients that
608
- * opened it here.
609
- *
610
- * The document store releases a per-URI hold only from an explicit close, so
611
- * without this a client that dies mid-session keeps its documents open for the
612
- * lifetime of the process: `isOpenInAnyClient` stays true, the document stays
613
- * resident, and the last-close revert never runs. A long-lived multi-client
614
- * head is the configuration where a dead client is normal rather than
615
- * exceptional, so the leak accumulates there.
616
- *
617
- * Runs from {@link dispose}, which is synchronous, so each close is fired and
618
- * its failure swallowed — a teardown must not reject, and a URI whose close
619
- * fails is no worse off than it was before this drain existed.
699
+ * The snapshot a session's open or create answers with. When the read
700
+ * fails, `rollback` undoes the open this call made before the failure is
701
+ * rethrown: the caller sees no open, so nothing on its side would ever close
702
+ * it.
620
703
  */
621
- protected closeOpenDocuments(): void {
622
- const held = [...this.openedDocuments];
623
- this.openedDocuments.clear();
624
- for (const [uri, clientIds] of held) {
625
- for (const clientId of clientIds) {
626
- void Promise.resolve(this.modelService.close({ uri, clientId })).catch(() => undefined);
627
- }
704
+ protected async openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
705
+ try {
706
+ return 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;
628
711
  }
629
712
  }
630
713
 
714
+ async closeModelDocument(args: CloseModelArgs): Promise<void> {
715
+ // Through the handle, so a close under an ended session fails as that
716
+ // session's calls do, and a session class's own close is honoured.
717
+ const session = this.requireSession(args.clientId);
718
+ // Closing also releases the watch for (uri, clientId) — a forgotten
719
+ // unwatch would otherwise leak phase-event dispatch until the connection
720
+ // closes. Idempotent: a close without a prior watch is a no-op.
721
+ await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
722
+ await session.close(args.uri);
723
+ }
724
+
631
725
  async getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
632
726
  // Smart dispatch: a warm document (already in LangiumDocuments) is
633
727
  // returned at its settle phase without a redundant build; a cold URI
@@ -640,18 +734,47 @@ export class DataServer<
640
734
  // unsubscribed caller that needs diagnostics inline passes
641
735
  // `includeDiagnostics: true` to settle at `Validated` instead.
642
736
  const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
643
- const astDocument = await this.modelService.ensureDocumentState(args.uri, state);
644
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
737
+ try {
738
+ return this.encodeDocument(await this.modelService.ensureDocumentState(args.uri, state));
739
+ } catch (error: unknown) {
740
+ // The protocol answers a read of a URI with no document with an
741
+ // envelope that has no model.
742
+ if (this.isMissingDocument(error, args.uri)) {
743
+ return this.envelope(UriUtils.toUri(args.uri));
744
+ }
745
+ throw error;
746
+ }
645
747
  }
646
748
 
647
749
  async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
648
- const astDocument = await this.modelService.update(args);
649
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
750
+ const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
751
+ return this.encodeDocument(astDocument);
650
752
  }
651
753
 
652
- async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
653
- const astDocument = await this.modelService.save(args);
654
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
754
+ async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferSavedDocument<TTransfer, TDiagnostic>> {
755
+ const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
756
+ return { ...this.encodeDocument(astDocument), persisted: astDocument.persisted };
757
+ }
758
+
759
+ async persistModelDocument(args: TransferPersistDocumentArgs): Promise<TransferSavedDocument<TTransfer, TDiagnostic>> {
760
+ const version = await this.requireSession(args.clientId).persist({ uri: args.uri, baseVersion: args.baseVersion });
761
+ const astDocument = await this.modelService.ensureDocumentState(args.uri, this.services.workspace.DocumentBuilder.finalBuildState());
762
+ return { ...this.encodeDocument(astDocument), persisted: { version } };
763
+ }
764
+
765
+ /**
766
+ * Delete the document through the session, then release the session's
767
+ * watch of it, as {@link closeModelDocument} does. Released only after the
768
+ * delete: one that fails leaves the session its open and its watch. Other
769
+ * sessions' watches survive, as for any deletion.
770
+ */
771
+ async deleteModelDocument(args: TransferDeleteDocumentArgs): Promise<void> {
772
+ const session = this.requireSession(args.clientId);
773
+ // Keyed before the delete: once the file is gone, a symlink to it no
774
+ // longer resolves to the key the watch is under.
775
+ const uri = this.canonicalKey(args.uri);
776
+ await session.delete({ uri: args.uri, baseVersion: args.baseVersion });
777
+ await this.unwatchModelDocument({ uri, clientId: args.clientId });
655
778
  }
656
779
 
657
780
  /**
@@ -659,28 +782,27 @@ export class DataServer<
659
782
  * fan out to the wired `clientProxy.onDocumentUpdated`. The
660
783
  * bidirectional pattern means the event channel is the client
661
784
  * notification surface, not a returned handle — this method only
662
- * registers the URI in the dispatch table.
785
+ * registers the watcher in {@link uriWatchRecords}.
663
786
  *
664
- * Also baselines the per-URI emission fingerprint (see
665
- * {@link lastEmittedFingerprint}) to the document's current state when
666
- * the first watcher for the URI registers. This guarantees that any
667
- * phase event firing immediately after the watch with no observable
668
- * change is suppressed — watchers obtain initial state via
669
- * `getModelDocument` (or {@link openModelDocument}) and do not need a
670
- * redundant phase notification for that same state.
787
+ * Also baselines the URI's emission fingerprint (see
788
+ * {@link dispatchPhaseEvent}) to the document's current state when the
789
+ * first watcher for the URI registers. This guarantees that any phase event firing immediately after
790
+ * the watch with no observable change is suppressed — watchers obtain
791
+ * initial state via `getModelDocument` (or {@link openModelDocument}) and
792
+ * do not need a redundant phase notification for that same state.
671
793
  */
672
794
  async watchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
673
795
  const uri = this.canonicalKey(args.uri);
674
- let subscribers = this.subscriptions.get(uri);
675
- if (!subscribers) {
676
- subscribers = new Set();
677
- this.subscriptions.set(uri, subscribers);
678
- }
679
- subscribers.add(args.clientId);
680
- if (!this.lastEmittedFingerprint.has(uri)) {
681
- const document = this.services.workspace.LangiumDocuments.getDocument(UriUtils.toUri(uri));
682
- if (document) {
683
- this.lastEmittedFingerprint.set(uri, this.computeDocumentFingerprint(document));
796
+ const keys = this.watchKeys.get(args.clientId) ?? new Map<string, string>();
797
+ this.watchKeys.set(args.clientId, keys.set(args.uri, uri));
798
+ const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
799
+ this.uriWatchRecords.set(uri, record);
800
+ record.watchers.add(args.clientId);
801
+ if (record.fingerprint === undefined) {
802
+ const document = this.modelService.getDocument(args.uri);
803
+ if (document && !this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
804
+ record.fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
805
+ record.fingerprintVersion = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
684
806
  }
685
807
  }
686
808
  }
@@ -688,29 +810,54 @@ export class DataServer<
688
810
  /**
689
811
  * Remove a watch for `(uri, clientId)` previously created by
690
812
  * {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
691
- * Dispatch for `uri` stops once no watchers remain, at which point the
692
- * per-URI emission fingerprint is also cleared so the next first-watch
693
- * re-baselines against the then-current document state rather than a
694
- * stale snapshot from the previous watch.
813
+ * Dispatch for `uri` stops once no watchers remain, and the emission
814
+ * fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
815
+ *
816
+ * A URI the client watched is unwatched under the key it resolved to then,
817
+ * from {@link watchKeys}, which still holds once its file is gone.
695
818
  */
696
819
  async unwatchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
697
- const uri = this.canonicalKey(args.uri);
698
- const subscribers = this.subscriptions.get(uri);
699
- if (!subscribers) {
820
+ const keys = this.watchKeys.get(args.clientId);
821
+ const uri = keys?.get(args.uri) ?? this.canonicalKey(args.uri);
822
+ // Every spelling the client watched it under was this one watch.
823
+ keys?.forEach((key, spelling) => {
824
+ if (key === uri) {
825
+ keys.delete(spelling);
826
+ }
827
+ });
828
+ if (keys?.size === 0) {
829
+ this.watchKeys.delete(args.clientId);
830
+ }
831
+ if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
832
+ this.pruneUriWatchRecord(uri);
833
+ }
834
+ }
835
+
836
+ /**
837
+ * Drop what `uri` no longer needs: the
838
+ * {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
839
+ * and the whole record once it holds no
840
+ * {@link DataServerUriWatchRecord.releaseBroadcastPending} mark either.
841
+ * Every path that removes a watcher or consumes a mark ends here.
842
+ */
843
+ protected pruneUriWatchRecord(uri: string): void {
844
+ const record = this.uriWatchRecords.get(uri);
845
+ if (!record || record.watchers.size > 0) {
700
846
  return;
701
847
  }
702
- subscribers.delete(args.clientId);
703
- if (subscribers.size === 0) {
704
- this.subscriptions.delete(uri);
705
- this.lastEmittedFingerprint.delete(uri);
848
+ if (record.releaseBroadcastPending) {
849
+ record.fingerprint = undefined;
850
+ record.fingerprintVersion = undefined;
851
+ } else {
852
+ this.uriWatchRecords.delete(uri);
706
853
  }
707
854
  }
708
855
 
709
856
  /**
710
- * Canonicalise a URI string for use as a subscription / fingerprint
711
- * map key, via the shared `DocumentUriPolicy`. Callers may send
712
- * non-canonical URIs (drive-letter casing, percent-encoding differences,
713
- * or a symlink path) over the wire; the dispatch side keys by
857
+ * Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
858
+ * shared `DocumentUriPolicy`. Callers may send non-canonical URIs
859
+ * (drive-letter casing, percent-encoding differences, or a symlink path)
860
+ * over the wire; the dispatch side keys by
714
861
  * `document.uri.toString()` from `LangiumDocuments`, so writer keys must
715
862
  * canonicalise to the same form or events silently fail to deliver.
716
863
  * Routing through the seam (rather than a bare `UriUtils.normalize`)
@@ -720,26 +867,24 @@ export class DataServer<
720
867
  * LSP head resolves.
721
868
  *
722
869
  * Adopters can still override for head-specific URI policy by subclassing.
870
+ * The result keys watches only; a document is looked up by its own URI.
723
871
  */
724
872
  protected canonicalKey(uri: string): string {
725
873
  return this.services.workspace.DocumentUriPolicy.canonicalUri(uri);
726
874
  }
727
875
 
728
876
  async getProjects(): Promise<readonly TProject[]> {
729
- // Pass-through: `ProjectManager<TProject>` already produces `TProject`
730
- // (the shared services are parameterised over the same generic).
731
877
  // The framework reads `id` for registry identity and `dependencies`
732
878
  // for the visibility closure; every other field rides on the
733
879
  // JSON-RPC envelope as adopter-defined wire metadata.
734
- return this.services.workspace.ProjectManager.getProjects();
880
+ return this.services.workspace.ProjectManager.getProjects().map(project => this.encodeProject(project));
735
881
  }
736
882
 
737
883
  async getProjectForUri(args: GetProjectForUriArgs): Promise<TProject | undefined> {
738
- // Pass-through: `ProjectManager.getProject(uri)` already returns the
739
- // adopter's `TProject` shape. Membership logic belongs to the adopter's
740
- // `ProjectManager`; the data-server forwards the URI without
741
- // interpretation.
742
- return this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
884
+ // Membership logic belongs to the adopter's `ProjectManager`; the
885
+ // data-server forwards the URI without interpretation.
886
+ const project = this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
887
+ return project && this.encodeProject(project);
743
888
  }
744
889
 
745
890
  /**
@@ -759,27 +904,60 @@ export class DataServer<
759
904
  // (see resolveReferenceServices) and delegate.
760
905
  // ============================================================
761
906
 
762
- async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
763
- // Candidates are derived from resolved cross-references, so the relevant document(s) must
764
- // have finished the Linked phase — otherwise a query issued right after a model update races
765
- // the asynchronous rebuild and returns stale candidates. Wait the source document
766
- // specifically, but ONLY when a document is actually loaded at that URI: a synthetic source
767
- // can address a URI with no document (a directory URI, typically), and a per-URI `waitUntil`
768
- // there throws "No document found". Fall back to a global Linked settle, matching the
769
- // id-based ElementSource (no URI) path.
770
- const uri = isDocumentSource(ctx.source) || isSyntheticSource(ctx.source) ? UriUtils.toUri(ctx.source.uri) : undefined;
907
+ /**
908
+ * Settle the build before a reference question is answered from the index.
909
+ *
910
+ * A query issued right after a model update otherwise races the rebuild and
911
+ * reads an index missing the symbols it asks about. The cost is not confined
912
+ * to this call: a scope built inside that window is cached, and the build's
913
+ * remaining documents link against it.
914
+ *
915
+ * Waits the source document specifically, but ONLY when one is loaded at
916
+ * that URI: a synthetic source can address a URI with no document (a
917
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
918
+ * found". Falls back to a global settle, matching the id-based
919
+ * `ElementSource` path.
920
+ *
921
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
922
+ */
923
+ protected async awaitReferencesLinked(source: ReferenceSource): Promise<void> {
924
+ const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
771
925
  const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
772
- await this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
926
+ const stopwatch = this.services.Clock.stopwatch();
927
+ const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
928
+ if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
929
+ return;
930
+ }
931
+ const elapsedMs = Math.round(stopwatch.elapsedMs);
932
+ // A per-URI wait resolves off a document-phase notification, so a
933
+ // missed one strands a wait on a document that HAS reached the
934
+ // phase. Re-read before failing; the workspace-wide wait has no
935
+ // equivalent reading and can only reject.
936
+ const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
937
+ if (waitUri && document && document.state >= DocumentState.Linked) {
938
+ this.tracer
939
+ .withUri(waitUri.toString())
940
+ .warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
941
+ return;
942
+ }
943
+ throw referenceSettleTimeoutError(elapsedMs);
944
+ }
945
+
946
+ async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
947
+ await this.awaitReferencesLinked(ctx.source);
773
948
  return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
774
949
  }
775
950
 
776
- async resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined> {
951
+ async resolveReference<TElement extends TransferElement = TransferElement>(
952
+ ref: ReferenceRequest
953
+ ): Promise<ReferenceTarget<TElement> | undefined> {
954
+ await this.awaitReferencesLinked(ref.source);
777
955
  const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
778
956
  if (!resolved) {
779
957
  return undefined;
780
958
  }
781
- const element = this.encoder.toTransfer(resolved.node) as unknown as TTransfer;
782
- return { ...resolved.candidate, element };
959
+ // `TElement` is the caller's claim about the target's type; nothing checks it.
960
+ return { ...resolved.candidate, element: this.encoder.toTransfer(resolved.node) as TElement };
783
961
  }
784
962
 
785
963
  async findNextName(args: FindNextNameArgs): Promise<string> {
@@ -789,15 +967,31 @@ export class DataServer<
789
967
  // synthetic source — and the create-element flow driving this method is
790
968
  // the one that produces directory URIs, on which a bare
791
969
  // `getServices(uri)` throws while `findReferenceCandidates` succeeds.
792
- const nameProvider = this.resolveReferenceServices(ReferenceSource.synthetic(args.uri, args.type)).NameProvider;
970
+ const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
971
+ // Mid-rebuild the names of documents not yet re-indexed are absent from
972
+ // the taken set, and the caller PERSISTS what it is handed. Nothing
973
+ // reserves the answer either, so a name is free of the collisions the
974
+ // index knows about and of nothing else — two callers racing get the same
975
+ // proposal, which only uniqueness at the write can catch.
976
+ await this.awaitReferencesLinked(source);
977
+ const nameProvider = this.resolveReferenceServices(source).NameProvider;
793
978
  const tier = args.tier ?? 'project';
794
979
  if (tier === 'public') {
795
980
  return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
796
981
  }
797
982
  if (tier === 'local') {
798
- // Document-scoped uniqueness: the document root is the container.
799
- const document = await this.modelService.ensureDocumentState(args.uri);
800
- return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root as AstNode) : args.proposal;
983
+ // Document-scoped uniqueness: the document root is the container. A
984
+ // URI with no document has nothing to collide with, like a document
985
+ // with no root.
986
+ try {
987
+ const document = await this.modelService.ensureDocumentState(args.uri);
988
+ return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
989
+ } catch (error: unknown) {
990
+ if (this.isMissingDocument(error, args.uri)) {
991
+ return args.proposal;
992
+ }
993
+ throw error;
994
+ }
801
995
  }
802
996
  const project = this.services.workspace.ProjectManager.getProject(uri);
803
997
  if (!project) {
@@ -834,67 +1028,32 @@ export class DataServer<
834
1028
  }
835
1029
 
836
1030
  /**
837
- * Pick the language that owns a reference source, in order:
1031
+ * Pick the language that owns a reference source: the registry's
1032
+ * `getLanguageFor` over the source's declared language, URI and AST type,
1033
+ * with an {@link isElementSource} routed by the document that holds the
1034
+ * element (see {@link findElementDocumentUri}) before its type, and
1035
+ * {@link fallbackReferenceLanguage}, adopter policy, last.
838
1036
  *
839
- * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
840
- * whose URI resolves to a registered language routes by URI.
841
- * 2. A single-language workspace always routes to that one language — so
842
- * single-language adopters never reach the steps below, and never pay
843
- * for them.
844
- * 3. An {@link isElementSource} source carries no URI, so in a
845
- * multi-language workspace it is routed via the document that holds the
846
- * element (see {@link findElementDocumentUri}).
847
- * 4. A source carrying an AST type is routed by that type when exactly one
848
- * registered grammar can produce it (see
849
- * {@link resolveReferenceLanguageByType}, over the registry's own type
850
- * index). This is what resolves a create-element flow's synthetic source
851
- * on a bare directory URI without asking the adopter.
852
- * 5. Anything still unresolved falls to {@link fallbackReferenceLanguage},
853
- * which is adopter policy.
1037
+ * An unregistered declared language falls through rather than failing: the
1038
+ * id crosses the wire, so a client built against a head with one more
1039
+ * grammar would otherwise lose queries the other signals answer.
854
1040
  */
855
1041
  protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined {
856
1042
  const registry = this.services.ServiceRegistry;
857
- // `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
858
- // an extensionless / unregistered URI falls through to the steps below
859
- // rather than throwing "no services for the extension ''".
860
- const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
861
- const byUri = uri && registry.getServicesFor(uri);
862
- if (byUri) {
863
- return byUri;
864
- }
865
- const all = registry.all;
866
- if (all.length === 1) {
867
- return all[0] as HydraniumLanguageServices;
868
- }
869
1043
  if (isElementSource(source)) {
870
- const documentUri = this.findElementDocumentUri(source);
871
- const byDocument = documentUri && registry.getServicesFor(documentUri);
872
- if (byDocument) {
873
- return byDocument;
874
- }
1044
+ // The index lookup runs only once the cheaper signals abstained.
1045
+ return (
1046
+ registry.getLanguageFor({}) ??
1047
+ registry.getLanguageFor({ target: this.findElementDocumentUri(source), type: source.type }) ??
1048
+ this.fallbackReferenceLanguage(source)
1049
+ );
875
1050
  }
876
- const byType = this.resolveReferenceLanguageByType(source);
877
- return byType ?? this.fallbackReferenceLanguage(source);
878
- }
879
-
880
- /**
881
- * Route a reference source by the AST type it carries — a
882
- * {@link isSyntheticSource}'s `type` (the transient node being created) or an
883
- * {@link isElementSource}'s optional narrowing `type`.
884
- *
885
- * Answers only when EXACTLY ONE registered grammar can produce the type.
886
- * Several can when the type comes from a grammar both import, and then the
887
- * type genuinely does not identify a language — that is a fall-through to
888
- * adopter policy, not a coin toss. Note this asks which grammar can *produce*
889
- * the type, not which mentions it: a grammar that merely cross-references a
890
- * type can never hold a node of it.
891
- */
892
- protected resolveReferenceLanguageByType(source: ReferenceSource): HydraniumLanguageServices | undefined {
893
- const type = isSyntheticSource(source) ? source.type : isElementSource(source) ? source.type : undefined;
894
- // The registry owns the type index — it is the one place that knows when
895
- // the registered set changed, so unlike a private memo here it cannot go
896
- // stale on a language registered after the first lookup.
897
- return type ? this.services.ServiceRegistry.soleServicesByType(type) : undefined;
1051
+ const hint = isSyntheticSource(source)
1052
+ ? { languageId: source.language, target: source.uri, type: source.type }
1053
+ : isDocumentSource(source)
1054
+ ? { target: source.uri }
1055
+ : {};
1056
+ return registry.getLanguageFor(hint) ?? this.fallbackReferenceLanguage(source);
898
1057
  }
899
1058
 
900
1059
  /**
@@ -904,15 +1063,14 @@ export class DataServer<
904
1063
  * disambiguates names that repeat across types (honouring grammar
905
1064
  * subtyping through `AstReflection.isSubtype`).
906
1065
  *
907
- * Only reached on the multi-language, name-based path (step 3 of
908
- * {@link resolveReferenceLanguage}); single-language adopters return at
909
- * step 2.
1066
+ * Only reached in a multi-language workspace, once the declared language
1067
+ * and the URI have abstained.
910
1068
  *
911
1069
  * Abstains when the name matches elements in more than one DOCUMENT — the
912
1070
  * index spans every language and is filled in build order, so "the
913
- * first match" would be file-watch order rather than an answer. Step 3
914
- * then falls through to the type-based step 4, which abstains on ties
915
- * in the same way, and finally to adopter policy.
1071
+ * first match" would be file-watch order rather than an answer. Routing
1072
+ * then falls through to the element's type, which abstains on ties in the
1073
+ * same way, and finally to adopter policy.
916
1074
  */
917
1075
  protected findElementDocumentUri(source: ElementSource): URI | undefined {
918
1076
  const matches = this.services.workspace.IndexManager.getElementsByName(source.name, source.type);
@@ -947,61 +1105,155 @@ export class DataServer<
947
1105
  // Internal plumbing
948
1106
  // ============================================================
949
1107
 
1108
+ /**
1109
+ * Whether `error`, from waiting on `uri`'s document, means that `uri` has
1110
+ * no document: a URI with neither a file nor text builds nothing, and
1111
+ * Langium's wait after the build rejects for want of one, with a
1112
+ * `ServerCancelled` response error. Any other failure, such as a read
1113
+ * that fails before a document is registered, a cancelled wait or a
1114
+ * `ReentrantWriteLockError`, is the caller's to see.
1115
+ */
1116
+ protected isMissingDocument(error: unknown, uri: string): boolean {
1117
+ return isResponseError(error) && error.code === SERVER_CANCELLED && this.modelService.getDocument(uri) === undefined;
1118
+ }
1119
+
950
1120
  /**
951
1121
  * Build a {@link TransferDocument} envelope from the current document state,
952
1122
  * delegating root + diagnostic encoding to {@link encoder} (see
953
- * `TransferEncoder.toTransferDocument` for the walk).
954
- *
955
- * The encoder field's generic-map binding is widened to
956
- * `Record<string, TransferElement>` at the framework-default level, and an
957
- * adopter supplying a typed-overlay encoder narrows the runtime shape to
958
- * its wire types. The cast on the return is where that invariant — the
959
- * adopter's `TTransfer` matches its encoder's overlay — is asserted, at a
960
- * single boundary point rather than spread across the callers.
1123
+ * `TransferEncoder.toTransferDocument` for the walk). `fingerprint` is the
1124
+ * caller's {@link computeDocumentFingerprint} of that same state, which
1125
+ * spares hashing it twice.
961
1126
  */
962
- protected envelope(uri: URI): TransferDocument<TTransfer, TDiagnostic> {
1127
+ protected envelope(uri: URI, fingerprint?: string): TransferDocument<TTransfer, TDiagnostic> {
963
1128
  // Resolve through the model service's canonicalizing gateway rather than
964
1129
  // reaching into `LangiumDocuments` directly, so a divergent (symlink) URI
965
1130
  // still finds the document the build keys by its real path — and so the
966
1131
  // data-server never has to remember to canonicalize this lookup itself.
967
1132
  const document = this.modelService.getDocument(uri.toString());
968
- if (!document) {
1133
+ if (!document || this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
969
1134
  // No document — a shaped envelope rather than a throw, so the caller
970
- // decides policy at its own layer; `root` is optional on the envelope
1135
+ // decides policy at its own layer; `model` is optional on the envelope
971
1136
  // so the compiler forces that decision. Adopters preferring to throw
972
- // override `envelope`.
973
- return {
974
- uri: uri.toString(),
975
- version: 0,
976
- root: undefined,
977
- diagnostics: [] as TDiagnostic[]
978
- };
1137
+ // override `envelope`. The builder's unparsed placeholder is no
1138
+ // document either: its root parses no text.
1139
+ return TransferDocument.absent<TTransfer, TDiagnostic>(uri.toString());
979
1140
  }
980
- return this.encoder.toTransferDocument<AstNode>(document) as unknown as TransferDocument<TTransfer, TDiagnostic>;
1141
+ const encoded = this.encoder.toTransferDocument(document);
1142
+ return this.withServerState(encoded, fingerprint ?? this.computeDocumentFingerprint(document.parseResult.value, encoded));
981
1143
  }
982
1144
 
983
1145
  /**
984
- * Subscribe one listener at the configured {@link DataServerOptions.subscriptionPhase}.
985
- * The listener dispatches subscription events for every matching URI. A
986
- * single listener (rather than one per subscription) keeps the cost flat
987
- * regardless of subscriber count.
1146
+ * The transfer document a request answers with for `astDocument`, its model
1147
+ * hashed and the text stamped on it by {@link withServerState}. Every
1148
+ * document a request answers with goes through here, so none goes out
1149
+ * without them.
988
1150
  */
989
- protected subscribeToDocumentBuilder(): void {
990
- this.disposables.push(
991
- this.services.workspace.DocumentBuilder.onDocumentPhase(this.options.subscriptionPhase, (document, cancelToken) =>
992
- this.dispatchPhaseEvent(document, cancelToken)
993
- )
994
- );
1151
+ protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
1152
+ const encoded = this.encoder.astDocumentToTransferDocument(astDocument);
1153
+ return this.withServerState(encoded, this.computeDocumentFingerprint(astDocument.root, encoded));
995
1154
  }
996
1155
 
997
1156
  /**
998
- * Subscribe to the universal save event on `HydraniumTextDocuments` so a
999
- * single `onDocumentSaved` wire notification fires for ANY save of a
1000
- * subscribed URI — regardless of whether the save originated from the
1001
- * data-server's RPC `saveModelDocument`, the LSP head's text-editor save,
1002
- * or any other client writing through `notifyDidSaveTextDocument`.
1157
+ * The project a client receives for `project`, unchanged by default. Every
1158
+ * project a request answers with or a change notification carries goes
1159
+ * through here, so a field derived for clients cannot miss one path. The
1160
+ * result crosses as JSON, so a value a client reads goes in a data field,
1161
+ * not a getter.
1162
+ */
1163
+ protected encodeProject(project: TProject): TProject {
1164
+ return project;
1165
+ }
1166
+
1167
+ /**
1168
+ * `encoded` with `hash` on its model and the text the server holds for it:
1169
+ * the store's while it holds the document, the build's otherwise. The text
1170
+ * is read when the document is sent rather than kept with the build: a save
1171
+ * changes `text.dirty` without a rebuild, and the store's text moves on before
1172
+ * the build that follows it.
1173
+ */
1174
+ protected withServerState(
1175
+ encoded: EncodedTransferDocument<TransferElement, TDiagnostic>,
1176
+ hash: string
1177
+ ): TransferDocument<TTransfer, TDiagnostic> {
1178
+ const text = this.services.workspace.TextDocuments.textState(encoded.uri) ?? this.builtTextState(encoded.uri);
1179
+ if (text && text.version > encoded.model.version) {
1180
+ this.tracer.withUri(encoded.uri).debug(`Send a model behind its text: model v${encoded.model.version} / text v${text.version}`);
1181
+ }
1182
+ return {
1183
+ uri: encoded.uri,
1184
+ // The encoder returns the structural base; `TTransfer` is the adopter's
1185
+ // declaration of the roots its languages produce, and nothing checks it.
1186
+ model: { ...encoded.model, hash } as TransferModelSnapshot<TTransfer, TDiagnostic>,
1187
+ ...(text ? { text } : {})
1188
+ };
1189
+ }
1190
+
1191
+ /**
1192
+ * The text a build read for a document the store never held, which is
1193
+ * clean: the store holds every text a client gave it.
1194
+ */
1195
+ protected builtTextState(uri: string): TextState | undefined {
1196
+ const textDocument = this.modelService.getDocument(uri)?.textDocument;
1197
+ return textDocument && { version: textDocument.version, hash: textHash(textDocument.getText()), dirty: false };
1198
+ }
1199
+
1200
+ /**
1201
+ * Follow every document at the configured
1202
+ * {@link DataServerOptions.subscriptionPhase}, once per connection rather
1203
+ * than once per watch, so the cost stays flat in the number of watches.
1204
+ */
1205
+ protected subscribeToModelUpdates(): void {
1206
+ const phase = this.options.subscriptionPhase;
1207
+ this.disposables.push(this.modelService.onModelUpdated(event => this.dispatchPhaseEvent(event), { phase }));
1208
+ // One message per build rather than one per document.
1209
+ this.disposables.push(this.modelService.onModelsBuilt(event => this.dispatchBuiltEvent(event.uris), { phase }));
1210
+ }
1211
+
1212
+ /**
1213
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
1214
+ * and that NOBODY on this
1215
+ * connection is watching — the ones a client was not told about through
1216
+ * {@link dispatchPhaseEvent}, which is gated per URI.
1217
+ *
1218
+ * **The gap this closes is the one no other source can observe.** A document
1219
+ * the client watches, it hears about already. A file changed on disk, the
1220
+ * host's own filesystem watcher reports — and on a browser host, where the
1221
+ * workspace lives behind this head, an external change cannot happen at all.
1222
+ * What is left, and what nothing outside the server can see, is a document
1223
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
1224
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
1225
+ * the update channel is silent by design. A consumer displaying data derived
1226
+ * from that document — a tree label, a decorator — otherwise goes stale with
1227
+ * no signal from any source, and repairs itself the moment someone opens the
1228
+ * file to investigate, which is what makes it expensive to diagnose later.
1003
1229
  *
1004
- * Architectural symmetry with {@link subscribeToDocumentBuilder}: every
1230
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
1231
+ * rather than being handed transfer documents it did not ask for. That is the
1232
+ * property the watcher gate protects, and it is preserved here by
1233
+ * carrying no document rather than by gating the message.
1234
+ *
1235
+ * Quiet in the common case. Editing a document that an editor has open leaves
1236
+ * that URI watched and therefore out of this set, so a build with no
1237
+ * dependents produces nothing at all, and workspace initialisation produces
1238
+ * nothing because it does not build to this phase. The ceiling is a
1239
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
1240
+ */
1241
+ protected dispatchBuiltEvent(built: readonly CanonicalUri[]): void {
1242
+ const uris = built.map(uri => this.canonicalKey(uri)).filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
1243
+ if (uris.length === 0) {
1244
+ return;
1245
+ }
1246
+ this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
1247
+ this.clientProxy.onDocumentsBuilt({ uris });
1248
+ }
1249
+
1250
+ /**
1251
+ * Follow every save so a single `onDocumentSaved` wire notification fires
1252
+ * for ANY save of a subscribed URI — regardless of whether the save
1253
+ * originated from the data-server's RPC `saveModelDocument`, the LSP head's
1254
+ * text-editor save, or any other client.
1255
+ *
1256
+ * Architectural symmetry with {@link subscribeToModelUpdates}: every
1005
1257
  * subscribed client sees every state change to documents they care about,
1006
1258
  * regardless of which client triggered it. Firing `onDocumentSaved` only
1007
1259
  * from the data-server's own RPC path is a bug, not an optimisation: an
@@ -1009,41 +1261,115 @@ export class DataServer<
1009
1261
  * clients, which never clear their dirty state.
1010
1262
  */
1011
1263
  protected subscribeToTextDocumentSaves(): void {
1012
- this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
1264
+ this.disposables.push(this.modelService.onModelSaved(event => this.dispatchSaveEvent(event)));
1265
+ }
1266
+
1267
+ /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
1268
+ protected subscribeToDirtyChanges(): void {
1269
+ this.disposables.push(this.modelService.onDirtyChanged(event => this.dispatchDirtyEvent(event)));
1013
1270
  }
1014
1271
 
1015
1272
  /**
1016
- * Mark the last-close transition per URI (see
1017
- * {@link pendingRevertBroadcasts}). The listener consults
1018
- * `isOpenInAnyClient` AFTER the store decremented the closing client's
1019
- * hold, so a `false` answer means this close was the last one.
1273
+ * Send a dirty flip to the connection, gated on the URI's watchers as
1274
+ * {@link dispatchSaveEvent} is: the answer at any one moment travels on
1275
+ * every document sent, so a client that watches nothing reads it there.
1020
1276
  */
1021
- protected subscribeToTextDocumentCloses(): void {
1022
- const textDocuments = this.services.workspace.TextDocuments;
1277
+ protected dispatchDirtyEvent(event: ModelDirtyChangedEvent): void {
1278
+ const uri = this.canonicalKey(event.uri);
1279
+ if (this.uriWatchRecords.get(uri)?.watchers.size) {
1280
+ this.clientProxy.onDocumentDirtyChanged({ uri, text: event.text });
1281
+ }
1282
+ }
1283
+
1284
+ /**
1285
+ * Mark each document the store releases, so {@link dispatchPhaseEvent}
1286
+ * broadcasts the build that follows even without a watcher. By default
1287
+ * that build reverts the document to its disk content, discarding unsaved
1288
+ * in-session edits, and the last close typically also
1289
+ * removed the last watcher: without the broadcast, a consumer that only
1290
+ * ever fetches via `getModelDocument` keeps showing the discarded state.
1291
+ * The broadcast is de-duplicated against the fingerprint while a watcher
1292
+ * holds one, so a close whose disk state equals the last emitted state
1293
+ * stays silent; with no watcher there is no fingerprint, and every release
1294
+ * build is sent. The first build after the release consumes the mark, and
1295
+ * goes out as the release unless it is stamped past the version a client
1296
+ * opened the document at again: a client's write or an integrity repair
1297
+ * that rides it keeps its author.
1298
+ *
1299
+ * A release, not the close itself: a document whose last client lost its
1300
+ * connection is released only once the release grace runs out, or when
1301
+ * another client opens it meanwhile, and not at all when a client lost
1302
+ * from it opens it again within its own grace.
1303
+ */
1304
+ protected subscribeToModelReleases(): void {
1023
1305
  this.disposables.push(
1024
- textDocuments.onDidClose(event => {
1025
- if (!textDocuments.isOpenInAnyClient(event.document.uri)) {
1026
- this.pendingRevertBroadcasts.add(this.canonicalKey(event.document.uri));
1027
- }
1306
+ this.modelService.onModelReleased(event => {
1307
+ const uri = this.canonicalKey(event.uri);
1308
+ const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
1309
+ record.releaseBroadcastPending = true;
1310
+ this.uriWatchRecords.set(uri, record);
1311
+ this.tracer.withUri(uri).debug('Release marked: the first build after it is broadcast, watched or not');
1028
1312
  })
1029
1313
  );
1030
1314
  }
1031
1315
 
1032
- /** Fan out a save event for the document's URI, gated by the subscription map. */
1033
- protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void {
1034
- // The save event arrives under the CLIENT URI the text store keys by (e.g. a
1035
- // symlink path S); the subscription map and `dispatchPhaseEvent` key by the
1036
- // CANONICAL identity R. Canonicalize before both the gate and the envelope so
1037
- // a save of a symlinked file isn't silently dropped (and the envelope resolves
1038
- // the R-keyed document rather than missing into an empty one).
1316
+ /**
1317
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
1318
+ * rather than only to the ones watching that URI.
1319
+ *
1320
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
1321
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
1322
+ * fire on every build, so the watcher gate is what keeps bandwidth
1323
+ * proportional to what a client asked for. A deletion is neither: it is one
1324
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
1325
+ * document's content. Gating it forces any consumer that displays the
1326
+ * workspace — a model tree, a file decorator — to learn about disappearances
1327
+ * from a filesystem watcher instead, which a client hosted in a browser has
1328
+ * no way to run: its workspace lives behind the head. A client that does not
1329
+ * care filters on the URI, which costs it a comparison.
1330
+ *
1331
+ * The precedent is the release broadcast (see
1332
+ * {@link subscribeToModelReleases}), where the same judgement was already made
1333
+ * in the other direction: a transition that matters enough is delivered
1334
+ * without a subscription.
1335
+ *
1336
+ * A deletion is announced before the build that follows it, so this goes
1337
+ * out ahead of the `'rebuilt'` events for the dependents whose references
1338
+ * the deletion just broke.
1339
+ *
1340
+ * The URI's fingerprint and release mark are dropped: they describe a
1341
+ * document that no longer exists. A kept fingerprint is adopted as the
1342
+ * baseline and suppresses the first emit after the file returns with its
1343
+ * previous content.
1344
+ *
1345
+ * The watchers SURVIVE: a recreated file resumes delivering to them with no
1346
+ * re-subscription, and a client that answers the deletion by closing
1347
+ * releases the watch through `closeModelDocument` anyway. A session that
1348
+ * deleted the document has its own released by {@link deleteModelDocument}.
1349
+ */
1350
+ protected dispatchDeleteEvent(event: ModelDeletedEvent): void {
1351
+ const uri = this.canonicalKey(event.uri);
1352
+ const record = this.uriWatchRecords.get(uri);
1353
+ if (record) {
1354
+ record.fingerprint = undefined;
1355
+ record.fingerprintVersion = undefined;
1356
+ record.releaseBroadcastPending = undefined;
1357
+ record.sentVersion = undefined;
1358
+ this.pruneUriWatchRecord(uri);
1359
+ }
1360
+ this.clientProxy.onDocumentDeleted({ uri, sourceClientId: event.sourceClientId });
1361
+ }
1362
+
1363
+ /** Fan out a save event for the document's URI, gated on the URI's watchers. */
1364
+ protected dispatchSaveEvent(event: AstDocumentSavedEvent<AstNode>): void {
1039
1365
  const uri = this.canonicalKey(event.document.uri);
1040
- if (!this.subscriptions.has(uri)) {
1366
+ if (!this.uriWatchRecords.get(uri)?.watchers.size) {
1041
1367
  return;
1042
1368
  }
1043
- const response = this.envelope(UriUtils.toUri(uri));
1369
+ const response = this.envelope(UriUtils.toUri(event.document.uri));
1044
1370
  const wireEvent: TransferDocumentSavedEvent<TTransfer, TDiagnostic> = {
1045
1371
  document: response,
1046
- sourceClientId: event.clientId
1372
+ sourceClientId: event.sourceClientId
1047
1373
  };
1048
1374
  this.clientProxy.onDocumentSaved(wireEvent);
1049
1375
  }
@@ -1057,116 +1383,114 @@ export class DataServer<
1057
1383
  * out to multiple local subscribers with an `Emitter<T>` — the
1058
1384
  * framework deliberately does NOT promise multi-listener semantics.
1059
1385
  *
1060
- * The dispatch is guarded by two filters:
1061
- * 1. **Subscription map**: events for URIs no subscriber registered for
1062
- * are NOT sent over the wire (bandwidth scales with subscribed URIs,
1063
- * not phase events).
1064
- * 2. **Emission fingerprint**: events for rebuilds that produce no
1065
- * observable change since the last emit are suppressed. See
1066
- * {@link lastEmittedFingerprint} for the rationale.
1386
+ * An event for a URI no client watches is NOT sent over the wire, so
1387
+ * bandwidth scales with watched URIs rather than with phase events; a
1388
+ * pending release mark is the exception (see
1389
+ * {@link subscribeToModelReleases}).
1390
+ *
1391
+ * An event for a rebuild with no observable change since the last emit is
1392
+ * suppressed against the URI's fingerprint and the version it was taken at;
1393
+ * a new version with the same fingerprint goes out with the same
1394
+ * `model.hash`, so a watcher still learns the version. Such rebuilds are routine: a
1395
+ * second client attaching to an open document makes
1396
+ * `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
1397
+ * to re-trigger the build, and Langium rebuilds a document when a
1398
+ * dependency changes even if its diagnostics come out the same. Sent at a
1399
+ * version this head has not sent, they reach watchers as `'changed'`, and a
1400
+ * watcher that reads `'changed'` as another client's write and resets its
1401
+ * root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
1402
+ * fingerprint, so the first event after a watch is de-duplicated against
1403
+ * the state the watcher just fetched; it goes with the last watcher, so the
1404
+ * next first watch re-baselines rather than adopting a stale digest. A
1405
+ * digest keeps its memory constant in document size; see
1406
+ * {@link computeDocumentFingerprint} for the inputs.
1067
1407
  */
1068
- protected dispatchPhaseEvent(document: LangiumDocument, cancelToken: CancellationToken): void {
1069
- if (cancelToken.isCancellationRequested) {
1070
- // Build preempted by a concurrent write lock (or other cancel source) —
1071
- // the subscription event is stale by the time it would fire. Skip
1072
- // emission so RPC subscribers don't surface intermediate states.
1073
- // A pending revert mark is deliberately NOT consumed here: the
1074
- // follow-up build re-fires this phase and broadcasts then.
1408
+ protected dispatchPhaseEvent(event: ModelUpdatedEvent<AstNode>): void {
1409
+ const uri = this.canonicalKey(event.document.uri);
1410
+ const record = this.uriWatchRecords.get(uri);
1411
+ const afterRelease = record?.releaseBroadcastPending === true;
1412
+ if (!record || (record.watchers.size === 0 && !afterRelease)) {
1075
1413
  return;
1076
1414
  }
1077
- const uri = document.uri.toString();
1078
- // Consume the last-close mark even when subscriptions exist — the
1079
- // regular dispatch below serves those watchers, and the mark's author
1080
- // attribution is more precise than the post-close `UNKNOWN_CLIENT_ID`
1081
- // the author lookup would yield.
1082
- const revertedOnClose = this.pendingRevertBroadcasts.delete(uri);
1083
- if (!this.subscriptions.has(uri) && !revertedOnClose) {
1415
+ if (afterRelease) {
1416
+ // Consumed even when watchers exist — the regular dispatch below
1417
+ // serves them, and the mark's attribution is more precise than the
1418
+ // post-close unknown client the manager's attribution would yield.
1419
+ // With no watcher the record goes now, so the fingerprint written
1420
+ // below lands on a detached record and the next first watch
1421
+ // re-baselines instead of adopting it.
1422
+ record.releaseBroadcastPending = undefined;
1423
+ this.pruneUriWatchRecord(uri);
1424
+ }
1425
+ // The encoder reads the built document, which the event's holds for this
1426
+ // synchronous run.
1427
+ const document = this.modelService.getDocument(event.document.uri);
1428
+ if (!document) {
1084
1429
  return;
1085
1430
  }
1086
- const fingerprint = this.computeDocumentFingerprint(document);
1087
- if (this.lastEmittedFingerprint.get(uri) === fingerprint) {
1431
+ const fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
1432
+ const stamped = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
1433
+ if (record.fingerprint === fingerprint && record.fingerprintVersion === stamped) {
1088
1434
  // A rebuild that produced no observable change since the last emit —
1089
1435
  // suppressed so RPC subscribers don't see a no-op broadcast. Logged at
1090
1436
  // debug so a *needed* re-broadcast wrongly suppressed by this dedup
1091
1437
  // (the failure mode the fingerprint strategy must avoid) is visible.
1092
- this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${document.textDocument.version}: fingerprint unchanged`);
1438
+ this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${stamped}: fingerprint and version unchanged`);
1093
1439
  return;
1094
1440
  }
1095
- this.lastEmittedFingerprint.set(uri, fingerprint);
1096
- const event: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> = {
1097
- document: this.envelope(document.uri),
1098
- sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID : this.resolveSourceClientId(document),
1099
- reason: this.resolveUpdateReason(document.uri)
1441
+ record.fingerprint = fingerprint;
1442
+ record.fingerprintVersion = stamped;
1443
+ // The event's attribution, so this head names the same client as the
1444
+ // in-process heads do for one build, except for a version this head
1445
+ // already sent; see `DataServerUriWatchRecord.sentVersion`.
1446
+ const version = this.modelService.isOpen(event.document.uri) ? document.textDocument.version : undefined;
1447
+ const { reason, sourceClientId } =
1448
+ version !== undefined && record.sentVersion === version
1449
+ ? { reason: 'rebuilt' as const, sourceClientId: UNKNOWN_CLIENT_ID }
1450
+ : event;
1451
+ record.sentVersion = version;
1452
+ // The stamp, not the live version: a write after the build's parse moves
1453
+ // only the latter. At the opened version too, which a reopen with the
1454
+ // released text keeps.
1455
+ const openedVersion = afterRelease ? this.modelService.openedVersion(event.document.uri) : undefined;
1456
+ const releaseBuild = afterRelease && (openedVersion === undefined || stamped <= openedVersion);
1457
+ const wireEvent: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> = {
1458
+ document: this.envelope(document.uri, fingerprint),
1459
+ sourceClientId: releaseBuild ? DOCUMENT_RELEASE_CLIENT_ID : sourceClientId,
1460
+ reason
1100
1461
  };
1462
+ const mark = afterRelease ? `, release mark: opened v${openedVersion ?? '-'}, attributed ${sourceClientId}` : '';
1101
1463
  this.tracer
1102
1464
  .withUri(uri)
1103
- .debug(`Emit onDocumentUpdated v${event.document.version} (reason=${event.reason}, sourceClientId=${event.sourceClientId})`);
1104
- this.clientProxy.onDocumentUpdated(event);
1465
+ .debug(`Emit onDocumentUpdated v${stamped} (reason=${wireEvent.reason}, sourceClientId=${wireEvent.sourceClientId}${mark})`);
1466
+ this.clientProxy.onDocumentUpdated(wireEvent);
1105
1467
  }
1106
1468
 
1107
1469
  /**
1108
- * Fingerprint of the document's observable state, used to de-dup
1109
- * `onDocumentUpdated` emissions. The {@link FingerprintStrategy} option
1110
- * selects what is hashed (default `'transfer-document'` — see the type), and
1111
- * {@link additionalFingerprintInputs} folds in any extra adopter signal.
1470
+ * Fingerprint of the snapshot `root` and its encoding `encoded`, used to
1471
+ * de-dup `onDocumentUpdated` emissions and sent as every document's
1472
+ * `model.hash`, so it must not depend on the version or on live state. The
1473
+ * {@link FingerprintStrategy} option selects what is hashed (default
1474
+ * `'transfer-document'` — see the type).
1112
1475
  *
1113
- * The default `'transfer-document'` strategy goes through the encoder's
1114
- * {@link TransferEncoder.toTransferDocument}, which is cached per build —
1115
- * so within one phase event the fingerprint and the subsequently-emitted
1116
- * `envelope` share a single encode walk.
1476
+ * {@link TransferEncoder.toTransferDocument} is cached per build, so within
1477
+ * one phase event the fingerprint and the subsequently-emitted `envelope`
1478
+ * share a single encode walk.
1117
1479
  *
1118
1480
  * Wrapped in {@link Tracer.time} against {@link FINGERPRINT_LOG_AFTER_MS}.
1119
1481
  */
1120
- protected computeDocumentFingerprint(document: LangiumDocument): string {
1121
- return this.tracer.withUri(document.uri.toString()).time(
1122
- 'Compute fingerprint',
1123
- () => {
1124
- const base =
1482
+ protected computeDocumentFingerprint(root: AstNode, encoded: EncodedTransferDocument<TransferElement, TDiagnostic>): string {
1483
+ return this.tracer
1484
+ .withUri(encoded.uri)
1485
+ .time(
1486
+ 'Compute fingerprint',
1487
+ () =>
1125
1488
  this.options.fingerprintStrategy === 'text-diagnostics'
1126
- ? textDiagnosticsFingerprint(document)
1127
- : transferDocumentFingerprint(this.encoder.toTransferDocument(document));
1128
- const extra = this.additionalFingerprintInputs(document);
1129
- return extra.length === 0 ? base : fingerprintHash([base, FINGERPRINT_SEPARATOR, ...extra.map(value => JSON.stringify(value))]);
1130
- },
1131
- 'debug',
1132
- { logAfterMs: FINGERPRINT_LOG_AFTER_MS }
1133
- );
1134
- }
1135
-
1136
- /**
1137
- * Extra inputs folded into {@link computeDocumentFingerprint} alongside the
1138
- * chosen {@link FingerprintStrategy}. Default: none. Override to contribute a
1139
- * signal that lives outside the document's text / root / diagnostics — each
1140
- * entry need only be stable across equivalent emissions and
1141
- * JSON-serialisable.
1142
- */
1143
- protected additionalFingerprintInputs(_document: LangiumDocument): readonly unknown[] {
1144
- return [];
1145
- }
1146
-
1147
- /**
1148
- * Discriminate the reason for a phase-event-driven update notification.
1149
- * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
1150
- * - URI in the `deleted` list → `'deleted'`
1151
- * - URI in the `changed` list → `'changed'` (the URI was passed to
1152
- * `documentBuilder.update(changed, deleted)`, which spans `didChange`
1153
- * text-document events and programmatic `update([uri], [])` calls).
1154
- * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
1155
- * because something it depends on changed; its own text wasn't flagged).
1156
- *
1157
- * `'saved'` is NOT emitted from this code path — saves take the dedicated
1158
- * `DataClientProtocol.onDocumentSaved` channel; adopters that want a
1159
- * unified update stream synthesise `'saved'` in their bridge layer.
1160
- */
1161
- protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'] {
1162
- const last = this.lastBuildUpdate;
1163
- if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
1164
- return 'deleted';
1165
- }
1166
- if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
1167
- return 'changed';
1168
- }
1169
- return 'rebuilt';
1489
+ ? textDiagnosticsFingerprint(this.services.workspace.ModelLedger.textOf(root), encoded.model)
1490
+ : transferDocumentFingerprint(encoded.model),
1491
+ 'debug',
1492
+ { logAfterMs: FINGERPRINT_LOG_AFTER_MS }
1493
+ );
1170
1494
  }
1171
1495
 
1172
1496
  /**
@@ -1192,40 +1516,38 @@ export class DataServer<
1192
1516
  /**
1193
1517
  * Fan one internal {@link ProjectChangeEvent} out to per-project wire
1194
1518
  * notifications. Each `removed` entry pairs the id with the pre-removal
1195
- * snapshot needed for the `'removed'` wire payload.
1519
+ * snapshot needed for the `'removed'` wire payload. A project whose
1520
+ * {@link encodeProject} throws is logged and skipped, so the rest of the
1521
+ * batch still reaches the client.
1196
1522
  */
1197
1523
  protected dispatchProjectChangeEvent(event: ProjectChangeEvent<TProject>): void {
1524
+ const send = (project: TProject, reason: ProjectChangeReason): void => {
1525
+ let encoded: TProject;
1526
+ try {
1527
+ encoded = this.encodeProject(project);
1528
+ } catch (error: unknown) {
1529
+ this.tracer.error(`Project ${project.id} not sent as ${reason}: encodeProject threw: ${describeErrorWithStack(error)}`);
1530
+ return;
1531
+ }
1532
+ this.clientProxy.onProjectsChanged({ project: encoded, reason });
1533
+ };
1198
1534
  for (const id of event.added) {
1199
1535
  const project = this.services.workspace.ProjectManager.getProjectById(id);
1200
1536
  if (project) {
1201
- this.clientProxy.onProjectsChanged({ project, reason: 'added' });
1537
+ send(project, 'added');
1202
1538
  }
1203
1539
  }
1204
1540
  for (const id of event.updated) {
1205
1541
  const project = this.services.workspace.ProjectManager.getProjectById(id);
1206
1542
  if (project) {
1207
- this.clientProxy.onProjectsChanged({ project, reason: 'updated' });
1543
+ send(project, 'updated');
1208
1544
  }
1209
1545
  }
1210
1546
  for (const entry of event.removed) {
1211
- this.clientProxy.onProjectsChanged({ project: entry.snapshot, reason: 'removed' });
1547
+ send(entry.snapshot, 'removed');
1212
1548
  }
1213
1549
  }
1214
1550
 
1215
- /**
1216
- * Resolve the wire-level `sourceClientId` for `document`'s events — the client
1217
- * that authored its current version, from the version-author history on
1218
- * `HydraniumTextDocuments`. The protocol-level counterpart of the internal
1219
- * `AstDocumentManager.getAuthor`: a framework-internal rebuild has no author,
1220
- * so this surfaces the {@link UNKNOWN_CLIENT_ID} presentation default. Adopters
1221
- * that rebuild through non-text-document channels override to derive a
1222
- * source id of their own.
1223
- */
1224
- protected resolveSourceClientId(document: LangiumDocument): string {
1225
- const author = this.services.workspace.TextDocuments.getAuthor(document.textDocument.uri, document.textDocument.version);
1226
- return author ?? UNKNOWN_CLIENT_ID;
1227
- }
1228
-
1229
1551
  // --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
1230
1552
  // Computed in THIS process: the data-server child holds the model store, so
1231
1553
  // these snapshots reflect the heap that actually carries the workspace
@@ -1287,11 +1609,11 @@ export class DataServer<
1287
1609
  /** Resolve a partial options object into a fully-defaulted form. */
1288
1610
  protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions {
1289
1611
  const additionalMethods = partial.additionalMethods ?? [];
1290
- const builtIn = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS] as readonly string[];
1612
+ const builtIn: readonly string[] = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS];
1291
1613
  const overlap = additionalMethods.filter(name => builtIn.includes(name));
1292
1614
  if (overlap.length > 0) {
1293
1615
  throw new Error(
1294
- `DataServer.additionalMethods overlaps with built-in data-server methods: ${overlap.join(', ')}. ` +
1616
+ `DataServerOptions.additionalMethods overlaps with built-in data-server methods: ${overlap.join(', ')}. ` +
1295
1617
  'Adopter protocols must not redeclare framework method names; rename the adopter method or remove it from additionalMethods.'
1296
1618
  );
1297
1619
  }
@@ -1301,7 +1623,8 @@ export class DataServer<
1301
1623
  methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
1302
1624
  additionalMethods,
1303
1625
  excludedMethods: partial.excludedMethods ?? [],
1304
- diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
1626
+ diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
1627
+ referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
1305
1628
  };
1306
1629
  }
1307
1630
  }