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

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