@hydranium/data-server 1.0.0-next.19 → 1.0.0-next.193

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