@hydranium/data-server 1.0.0-next.12 → 1.0.0-next.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,10 +6,37 @@
6
6
  *
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
- import { createRpcProxy, DisposableCollection, isDocumentSource, isElementSource, isSyntheticSource, ReferenceSource } from '@hydranium/protocol';
9
+ import { createRpcProxy, defineMessage, DisposableCollection, isDocumentSource, isElementSource, isSyntheticSource, messageError, ReferenceSource, SessionClosedError, TransferDocument, asSnapshotVersion } from '@hydranium/protocol';
10
10
  import { DATA_SERVER_DIAGNOSTICS_METHODS, DATA_SERVER_PROTOCOL_METHODS, DATA_SERVER_WIRE_PREFIX } from '@hydranium/protocol/data';
11
11
  import { REVERT_ON_CLOSE_CLIENT_ID, UNKNOWN_CLIENT_ID } from '@hydranium/core';
12
12
  import { defaultDataServerDiagnostics } from './default-diagnostics.js';
13
+ /**
14
+ * Raised when a profiling command arrives with no capture running.
15
+ *
16
+ * A `ResponseError` rather than a plain `Error` so the identity survives to the
17
+ * response boundary, which is where the message is rendered. An unwrapped throw
18
+ * reaches the client as a generic internal error instead: no code for a caller
19
+ * to switch on, and nothing for the boundary to render from.
20
+ */
21
+ export const NO_ACTIVE_PROFILE = defineMessage('hydranium/data-server/no-active-profile', 'No profiling capture is active; call startProfiling first.');
22
+ /**
23
+ * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
24
+ * survives reconstruction and is what a caller switches on.
25
+ */
26
+ export const NO_ACTIVE_PROFILE_CODE = 1002;
27
+ export const noActiveProfileError = () => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
28
+ /**
29
+ * Raised when a reference question's wait for the build exceeds
30
+ * {@link DataServerOptions.referenceSettleTimeoutMs}.
31
+ *
32
+ * A `ResponseError` because a class name does not cross RPC: without the code a
33
+ * wire client cannot tell a wedged build from a reference that resolves to
34
+ * nothing, which is the distinction the wait exists to keep.
35
+ */
36
+ export const REFERENCE_SETTLE_TIMEOUT = defineMessage('hydranium/data-server/reference-settle-timeout', 'Timed out after {elapsedMs}ms waiting for the build to settle before answering a reference query.');
37
+ /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
38
+ export const REFERENCE_SETTLE_TIMEOUT_CODE = 1003;
39
+ export const referenceSettleTimeoutError = (elapsedMs) => messageError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT, { elapsedMs });
13
40
  import { DocumentState, UriUtils } from '@hydranium/langium';
14
41
  /**
15
42
  * Domain separator between text and diagnostics inputs of
@@ -47,6 +74,7 @@ function fingerprintHash(parts) {
47
74
  const low = (h1 >>> 0).toString(16).padStart(8, '0');
48
75
  return high + low;
49
76
  }
77
+ const resumableByModelService = new WeakMap();
50
78
  /** Hash a document's raw text + diagnostics — the `'text-diagnostics'` strategy. */
51
79
  function textDiagnosticsFingerprint(document) {
52
80
  return fingerprintHash([document.textDocument.getText(), FINGERPRINT_SEPARATOR, JSON.stringify(document.diagnostics ?? [])]);
@@ -94,9 +122,11 @@ const FINGERPRINT_LOG_AFTER_MS = 5;
94
122
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
95
123
  * builds the {@link DataClientProtocol} notification proxy on the same
96
124
  * connection in one {@link createRpcProxy} call (binding `this` as its
97
- * `localTarget`) under the configured namespace, and subscribes one
98
- * `DocumentBuilder.onDocumentPhase` listener per configured phase that
99
- * dispatches subscription events via `clientProxy.onDocumentUpdated`.
125
+ * `localTarget`) under the configured namespace, and subscribes two listeners
126
+ * at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
127
+ * per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
128
+ * `DocumentBuilder.onBuildPhase` one dispatching a single
129
+ * `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
100
130
  *
101
131
  * The data-server requires the full {@link ServerSharedServices}
102
132
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -121,33 +151,34 @@ export class DataServer {
121
151
  * extending rather than restate a value the framework may change.
122
152
  */
123
153
  static DEFAULT_OPTIONS = {
124
- subscriptionPhase: DocumentState.Validated
154
+ subscriptionPhase: DocumentState.Validated,
155
+ referenceSettleTimeoutMs: 60_000
125
156
  };
126
157
  options;
127
158
  /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
128
159
  subscriptions = new Map();
129
160
  /**
130
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
131
- * connection.
161
+ * The client sessions this connection registered, by client id. A document
162
+ * request carrying one of these ids acts as that session; one carrying any
163
+ * other id fails.
132
164
  *
133
- * Kept because the document store releases a client's hold only from an
134
- * explicit close, and a client that dies without closing would otherwise keep
135
- * the document open forever — resident, and with its last-close revert
136
- * suppressed. The store has no notion of which connection a clientId reached
137
- * it over, so the connection-scoped set has to live here; teaching it a client
138
- * identity is the more robust and much larger alternative.
165
+ * Entries stay after {@link dispose} has ended their sessions, so a request
166
+ * still running from before the connection closed reaches the ended handle
167
+ * and fails with the session's own error.
139
168
  */
140
- openedDocuments = new Map();
169
+ clientSessions = new Map();
141
170
  /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
142
171
  clientProxy;
143
172
  disposables = new DisposableCollection();
144
173
  /**
145
174
  * Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
146
175
  * `reason` discrimination on outbound `onDocumentUpdated` notifications:
147
- * a URI in the `changed` list emits `'changed'`, in `deleted` emits
148
- * `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
149
- * URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
150
- * the LSP side, so reason fidelity stays consistent between heads.
176
+ * a URI in the `changed` list emits `'changed'`, otherwise `'rebuilt'`
177
+ * (cascade rebuild from a dependent URI's change). The same mechanism
178
+ * `AstDocumentManager.onUpdate` uses on the LSP side, so reason fidelity
179
+ * stays consistent between heads. The `deleted` half is read by
180
+ * {@link dispatchDeleteEvents} rather than by the reason discrimination,
181
+ * a deletion travelling on its own channel.
151
182
  */
152
183
  lastBuildUpdate;
153
184
  /**
@@ -187,12 +218,12 @@ export class DataServer {
187
218
  */
188
219
  lastEmittedFingerprint = new Map();
189
220
  /**
190
- * URIs whose LAST client just closed. The update handler rebuilds such a
191
- * document from its disk content (discarding unsaved in-session edits),
192
- * but {@link dispatchPhaseEvent} gates on the subscription map — and the
193
- * last close typically also removed the last watcher, so consumers that
194
- * only ever fetch via `getModelDocument` would keep showing the
195
- * discarded state forever. Marked on the last-close transition (see
221
+ * URIs the text store just released after their last close. The store
222
+ * rebuilds such a document from its disk content (discarding unsaved
223
+ * in-session edits), but {@link dispatchPhaseEvent} gates on the
224
+ * subscription map — and the last close typically also removed the last
225
+ * watcher, so consumers that only ever fetch via `getModelDocument` would
226
+ * keep showing the discarded state forever. Marked on the release (see
196
227
  * {@link subscribeToTextDocumentCloses}) and consumed by
197
228
  * {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
198
229
  * phase event even without a subscription — de-duplicated against
@@ -248,10 +279,15 @@ export class DataServer {
248
279
  methodNamespace: this.options.methodNamespace,
249
280
  localTarget: this,
250
281
  localMethods: registeredMethods,
251
- latency: this.latency
282
+ latency: this.latency,
283
+ // Bound at the chokepoint rather than per handler, so an adopter's
284
+ // `additionalMethods` are rendered on the same terms as the
285
+ // framework's own rejections.
286
+ renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
252
287
  });
253
288
  this.disposables.push(this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
254
289
  this.lastBuildUpdate = { changed, deleted };
290
+ this.dispatchDeleteEvents(deleted);
255
291
  }));
256
292
  this.subscribeToDocumentBuilder();
257
293
  this.subscribeToTextDocumentSaves();
@@ -259,24 +295,29 @@ export class DataServer {
259
295
  this.subscribeToProjectManager();
260
296
  // Self-register teardown so an adopter that keeps no reference to the
261
297
  // server still releases per-connection state, with no lifecycle hook of
262
- // its own. See `dispose`.
263
- this.disposables.push(connection.onClose(() => this.dispose()));
298
+ // its own. The client did not close anything itself, so its sessions end
299
+ // as lost and each document it was the last to have open waits out the
300
+ // store's revert grace. See `dispose`.
301
+ this.disposables.push(connection.onClose(() => this.dispose('lost')));
264
302
  }
265
303
  /**
266
304
  * Release everything the constructor wired up — the bound protocol
267
305
  * handlers and every listener — and clear the subscription map and the
268
306
  * per-URI emission-fingerprint cache, so a long-lived shared services
269
307
  * bundle does not retain per-connection memory after the connection
270
- * closes. Also closes every document still open over this connection (see
271
- * {@link closeOpenDocuments}), which is the SHARED store's state rather than
272
- * this server's and so outlives the connection unless released here.
308
+ * closes. Also ends every session this connection registered, which closes
309
+ * every document it has open: the SHARED store's state rather than this
310
+ * server's, which outlives the connection unless released here.
273
311
  *
274
- * Idempotent: subsequent calls are no-ops. Self-fires on
275
- * `connection.onClose` so adopters who don't hold a reference still
276
- * get per-connection cleanup; adopters that DO hold a reference may
277
- * call `dispose()` directly for early teardown.
312
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
313
+ * connection closes, so adopters who don't hold a reference still get
314
+ * per-connection cleanup; adopters that DO hold a reference may call
315
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
316
+ * `'closed'` reverts every document whose last open they close at once,
317
+ * and `'lost'`, the connection's own close, lets each wait out the revert
318
+ * grace.
278
319
  */
279
- dispose() {
320
+ dispose(cause = 'closed') {
280
321
  this.disposed = true;
281
322
  // Release an in-flight interactive capture so the process-wide inspector
282
323
  // singleton is not left active after the connection closes.
@@ -285,97 +326,166 @@ export class DataServer {
285
326
  this.activeProfile = undefined;
286
327
  void capture.stop({}).catch(() => undefined);
287
328
  }
288
- // AFTER `disposables.dispose()`, deliberately: closing a document fires
289
- // `onDidClose`, and this server's own close listener would otherwise mark a
290
- // revert broadcast for a connection that is already gone.
329
+ // AFTER `disposables.dispose()`, deliberately: ending a session releases
330
+ // each document it was the last to hold, and this server's own
331
+ // `onDidCloseLastOpen` listener would otherwise mark a revert broadcast
332
+ // for a connection that is already gone.
291
333
  this.disposables.dispose();
292
- this.closeOpenDocuments();
334
+ for (const [clientId, session] of this.clientSessions) {
335
+ this.endSession(clientId, session, cause);
336
+ }
293
337
  this.subscriptions.clear();
294
338
  this.lastEmittedFingerprint.clear();
295
339
  this.pendingRevertBroadcasts.clear();
296
340
  }
297
341
  // ============================================================
298
- // DataServerProtocol implementation — delegates to ModelService.
342
+ // DataServerProtocol implementation
299
343
  // ============================================================
300
344
  //
301
- // The lifecycle methods (`get` / `update` / `save` / `ready`) forward
302
- // straight to `ModelService` and encode the returned `AstDocument` on
303
- // the wire boundary via `encoder.astDocumentToTransferDocument`.
304
- // Adopters customising lifecycle behaviour (normalisation, supersession,
305
- // settled-phase choice, etc.) override on the ModelService subclass —
306
- // no override on DataServer is needed.
307
- async openModelDocument(args) {
308
- // Register the editor session (idempotent — `ModelService.open` refreshes
309
- // an already-open document rather than re-opening), then return the built
310
- // state at the configured target phase. The one-shot snapshot; subsequent
311
- // build-phase events arrive via `watchModelDocument`.
312
- await this.modelService.open(args);
313
- // Record the hold so `dispose` can release it for a client that never
314
- // closes. Keyed by the URI as given, because that is what `close` takes.
315
- let holders = this.openedDocuments.get(args.uri);
316
- if (!holders) {
317
- holders = new Set();
318
- this.openedDocuments.set(args.uri, holders);
319
- }
320
- holders.add(args.clientId);
321
- const document = await this.getModelDocument({ uri: args.uri });
322
- // Project the authoritative client-facing version onto the open snapshot.
323
- // `getModelDocument` encodes the freshly-built AST snapshot, whose version
324
- // is the `LangiumDocument`'s own `textDocument.version`. That lags the
325
- // multi-client synced version whenever the open seeded the synced document
326
- // with a caller-supplied version id — and the synced version is what
327
- // `ModelService.update`'s optimistic-concurrency gate compares
328
- // `baseVersion` against, so reporting the snapshot's would make the
329
- // caller's first tagged write self-conflict. A genuine concurrent edit
330
- // still trips the gate and is reconciled by the caller's replay rather
331
- // than predicted here.
332
- return { ...document, version: this.services.workspace.TextDocuments.version(args.uri) };
333
- }
334
- async closeModelDocument(args) {
335
- // Closing a session also releases its watch for (uri, clientId) — a
336
- // forgotten unwatch would otherwise leak phase-event dispatch until the
337
- // connection closes. Idempotent: a close without a prior watch is a no-op.
338
- await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
339
- this.forgetOpenDocument(args.uri, args.clientId);
340
- await this.modelService.close(args);
345
+ // Reads go to `ModelService`; a request that opens or writes a document
346
+ // goes to the session this connection registered under its `clientId`.
347
+ // Each answer is encoded on the wire boundary via
348
+ // `encoder.astDocumentToTransferDocument`. To change how documents are
349
+ // read, override on the ModelService subclass; to change how they are
350
+ // written, on the session class the bound `ClientSessionFactory` builds.
351
+ async createSession(args) {
352
+ // After teardown nothing would ever end a session registered now, and its
353
+ // id would stay taken for the life of the process.
354
+ if (this.disposed) {
355
+ throw new SessionClosedError(args.clientId);
356
+ }
357
+ const resumable = this.resumableSessions();
358
+ const previous = resumable.get(args.clientId);
359
+ if (previous && args.resumeToken !== undefined && previous.token === args.resumeToken) {
360
+ previous.end();
361
+ }
362
+ const session = this.modelService.createSession(args.label, args.clientId);
363
+ this.clientSessions.set(args.clientId, session);
364
+ if (args.resumeToken !== undefined) {
365
+ // Taken over by a client registering again after its connection
366
+ // dropped, so the old session ends as lost: the documents it was the
367
+ // last to have open wait out the grace, and the new session's opens
368
+ // find their unsaved text.
369
+ resumable.set(args.clientId, { token: args.resumeToken, end: () => this.endSession(args.clientId, session, 'lost') });
370
+ }
341
371
  }
342
372
  /**
343
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
344
- * close it a second time. Idempotent.
373
+ * End a session this connection registered. The ended handle stays in
374
+ * {@link clientSessions}, as it does after {@link dispose}, so a request for
375
+ * the id still arriving fails with the ended session's own error.
345
376
  */
346
- forgetOpenDocument(uri, clientId) {
347
- const holders = this.openedDocuments.get(uri);
348
- if (!holders) {
349
- return;
377
+ async closeSession(args) {
378
+ const session = this.clientSessions.get(args.clientId);
379
+ if (session) {
380
+ this.endSession(args.clientId, session);
350
381
  }
351
- holders.delete(clientId);
352
- if (holders.size === 0) {
353
- this.openedDocuments.delete(uri);
382
+ }
383
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
384
+ endSession(clientId, session, cause = 'closed') {
385
+ for (const [uri, watchers] of this.subscriptions) {
386
+ if (watchers.delete(clientId) && watchers.size === 0) {
387
+ this.subscriptions.delete(uri);
388
+ this.lastEmittedFingerprint.delete(uri);
389
+ }
354
390
  }
391
+ session.dispose(cause);
355
392
  }
356
393
  /**
357
- * Close every document still open over this connection, for the clients that
358
- * opened it here.
394
+ * The resumable sessions of this services tree, by client id, across all of
395
+ * its data connections: a client resumes on another connection than the one
396
+ * that registered it. An entry leaves when its session ends, by any path, so
397
+ * it keeps no ended connection alive.
359
398
  *
360
- * The document store releases a per-URI hold only from an explicit close, so
361
- * without this a client that dies mid-session keeps its documents open for the
362
- * lifetime of the process: `isOpenInAnyClient` stays true, the document stays
363
- * resident, and the last-close revert never runs. A long-lived multi-client
364
- * head is the configuration where a dead client is normal rather than
365
- * exceptional, so the leak accumulates there.
399
+ * A takeover by resume token ends the old session even when its connection
400
+ * is still alive, so two clients that shared an id and its token would end
401
+ * each other's sessions. And the token is a guard against colliding with a
402
+ * session the server has not yet seen end, not a secret: the wire carries no
403
+ * authentication, and a peer that learns the token can end the session.
404
+ */
405
+ resumableSessions() {
406
+ let sessions = resumableByModelService.get(this.modelService);
407
+ if (!sessions) {
408
+ const created = new Map();
409
+ // Subscribed once per services tree, and never disposed: it lives as
410
+ // long as the text store it listens to.
411
+ this.services.workspace.TextDocuments.onDidCloseSession(event => created.delete(event.clientId));
412
+ resumableByModelService.set(this.modelService, created);
413
+ sessions = created;
414
+ }
415
+ return sessions;
416
+ }
417
+ async createModelDocument(args) {
418
+ const session = this.requireSession(args.clientId);
419
+ await session.create(args.uri, args.text);
420
+ return this.openedSnapshot(args.uri, () => session.close(args.uri));
421
+ }
422
+ async updateModelDocuments(args) {
423
+ const astDocuments = await this.requireSession(args.clientId).updateAll({
424
+ updates: args.updates.map(update => this.toSessionWrite(update))
425
+ });
426
+ return astDocuments.map(astDocument => this.encoder.astDocumentToTransferDocument(astDocument));
427
+ }
428
+ /**
429
+ * The session write a wire write request carries. Only the fields a session
430
+ * takes: a field an adopter adds to a request reaches the session only
431
+ * through an override of this.
432
+ */
433
+ toSessionWrite(request) {
434
+ return { uri: request.uri, model: request.model, basedOn: request.basedOn };
435
+ }
436
+ /**
437
+ * The session this connection registered under `clientId`, which every
438
+ * document request acts as. An id that is not one fails with the
439
+ * closed-session code: opening or writing under it would leave an open that
440
+ * no session end ever closes.
441
+ */
442
+ requireSession(clientId) {
443
+ const session = this.clientSessions.get(clientId);
444
+ if (!session) {
445
+ throw new SessionClosedError(clientId, `Client session ${clientId} was never registered on this connection`);
446
+ }
447
+ return session;
448
+ }
449
+ async openModelDocument(args) {
450
+ const session = this.requireSession(args.clientId);
451
+ const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
452
+ await session.open(args.uri, args.options);
453
+ // A repeat open keeps the earlier one, which is still in use.
454
+ return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
455
+ }
456
+ /**
457
+ * The snapshot a session's open or create answers with. When the read
458
+ * fails, `rollback` undoes the open this call made before the failure is
459
+ * rethrown: the caller sees no open, so nothing on its side would ever close
460
+ * it.
366
461
  *
367
- * Runs from {@link dispose}, which is synchronous, so each close is fired and
368
- * its failure swallowed — a teardown must not reject, and a URI whose close
369
- * fails is no worse off than it was before this drain existed.
462
+ * Versioned with the store's shared version rather than the snapshot's own:
463
+ * the built document's `textDocument.version` lags the store's whenever the
464
+ * store assigned the version, and the store's is what a write's `basedOn` is
465
+ * compared against, so reporting the snapshot's would make the caller's
466
+ * first based-on write conflict with itself.
370
467
  */
371
- closeOpenDocuments() {
372
- const held = [...this.openedDocuments];
373
- this.openedDocuments.clear();
374
- for (const [uri, clientIds] of held) {
375
- for (const clientId of clientIds) {
376
- void Promise.resolve(this.modelService.close({ uri, clientId })).catch(() => undefined);
377
- }
468
+ async openedSnapshot(uri, rollback) {
469
+ let document;
470
+ try {
471
+ document = await this.getModelDocument({ uri });
378
472
  }
473
+ catch (error) {
474
+ // The open's failure is the one the caller needs, not the cleanup's.
475
+ await rollback?.().catch(() => undefined);
476
+ throw error;
477
+ }
478
+ return { ...document, version: asSnapshotVersion(this.services.workspace.TextDocuments.version(uri)) };
479
+ }
480
+ async closeModelDocument(args) {
481
+ // Through the handle, so a close under an ended session fails as that
482
+ // session's calls do, and a session class's own close is honoured.
483
+ const session = this.requireSession(args.clientId);
484
+ // Closing also releases the watch for (uri, clientId) — a forgotten
485
+ // unwatch would otherwise leak phase-event dispatch until the connection
486
+ // closes. Idempotent: a close without a prior watch is a no-op.
487
+ await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
488
+ await session.close(args.uri);
379
489
  }
380
490
  async getModelDocument(args) {
381
491
  // Smart dispatch: a warm document (already in LangiumDocuments) is
@@ -393,11 +503,11 @@ export class DataServer {
393
503
  return this.encoder.astDocumentToTransferDocument(astDocument);
394
504
  }
395
505
  async updateModelDocument(args) {
396
- const astDocument = await this.modelService.update(args);
506
+ const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
397
507
  return this.encoder.astDocumentToTransferDocument(astDocument);
398
508
  }
399
509
  async saveModelDocument(args) {
400
- const astDocument = await this.modelService.save(args);
510
+ const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
401
511
  return this.encoder.astDocumentToTransferDocument(astDocument);
402
512
  }
403
513
  /**
@@ -498,20 +608,58 @@ export class DataServer {
498
608
  // Resolve the language's reference services from each request's source
499
609
  // (see resolveReferenceServices) and delegate.
500
610
  // ============================================================
501
- async findReferenceCandidates(ctx) {
502
- // Candidates are derived from resolved cross-references, so the relevant document(s) must
503
- // have finished the Linked phase — otherwise a query issued right after a model update races
504
- // the asynchronous rebuild and returns stale candidates. Wait the source document
505
- // specifically, but ONLY when a document is actually loaded at that URI: a synthetic source
506
- // can address a URI with no document (a directory URI, typically), and a per-URI `waitUntil`
507
- // there throws "No document found". Fall back to a global Linked settle, matching the
508
- // id-based ElementSource (no URI) path.
509
- const uri = isDocumentSource(ctx.source) || isSyntheticSource(ctx.source) ? UriUtils.toUri(ctx.source.uri) : undefined;
611
+ /**
612
+ * Settle the build before a reference question is answered from the index.
613
+ *
614
+ * A query issued right after a model update otherwise races the rebuild and
615
+ * reads an index missing the symbols it asks about. The cost is not confined
616
+ * to this call: a scope built inside that window is cached, and the build's
617
+ * remaining documents link against it.
618
+ *
619
+ * Waits the source document specifically, but ONLY when one is loaded at
620
+ * that URI: a synthetic source can address a URI with no document (a
621
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
622
+ * found". Falls back to a global settle, matching the id-based
623
+ * `ElementSource` path.
624
+ *
625
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
626
+ */
627
+ async awaitReferencesLinked(source) {
628
+ const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
510
629
  const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
511
- await this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
630
+ const stopwatch = this.services.Clock.stopwatch();
631
+ let timer;
632
+ const timeout = new Promise((resolve, reject) => {
633
+ timer = this.services.Clock.setTimer(() => {
634
+ const elapsedMs = Math.round(stopwatch.elapsedMs);
635
+ // A per-URI wait resolves off a document-phase notification, so a
636
+ // missed one strands a wait on a document that HAS reached the
637
+ // phase. Re-read before failing; the workspace-wide wait has no
638
+ // equivalent reading and can only reject.
639
+ const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
640
+ if (waitUri && document && document.state >= DocumentState.Linked) {
641
+ this.tracer
642
+ .withUri(waitUri.toString())
643
+ .warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
644
+ resolve();
645
+ return;
646
+ }
647
+ reject(referenceSettleTimeoutError(elapsedMs));
648
+ }, this.options.referenceSettleTimeoutMs);
649
+ });
650
+ try {
651
+ await Promise.race([this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri), timeout]);
652
+ }
653
+ finally {
654
+ timer?.dispose();
655
+ }
656
+ }
657
+ async findReferenceCandidates(ctx) {
658
+ await this.awaitReferencesLinked(ctx.source);
512
659
  return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
513
660
  }
514
661
  async resolveReference(ref) {
662
+ await this.awaitReferencesLinked(ref.source);
515
663
  const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
516
664
  if (!resolved) {
517
665
  return undefined;
@@ -526,7 +674,14 @@ export class DataServer {
526
674
  // synthetic source — and the create-element flow driving this method is
527
675
  // the one that produces directory URIs, on which a bare
528
676
  // `getServices(uri)` throws while `findReferenceCandidates` succeeds.
529
- const nameProvider = this.resolveReferenceServices(ReferenceSource.synthetic(args.uri, args.type)).NameProvider;
677
+ const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
678
+ // Mid-rebuild the names of documents not yet re-indexed are absent from
679
+ // the taken set, and the caller PERSISTS what it is handed. Nothing
680
+ // reserves the answer either, so a name is free of the collisions the
681
+ // index knows about and of nothing else — two callers racing get the same
682
+ // proposal, which only uniqueness at the write can catch.
683
+ await this.awaitReferencesLinked(source);
684
+ const nameProvider = this.resolveReferenceServices(source).NameProvider;
530
685
  const tier = args.tier ?? 'project';
531
686
  if (tier === 'public') {
532
687
  return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
@@ -569,6 +724,9 @@ export class DataServer {
569
724
  /**
570
725
  * Pick the language that owns a reference source, in order:
571
726
  *
727
+ * 0. A {@link isSyntheticSource} naming its own `language` routes there.
728
+ * First because every step below infers, and an inference must not
729
+ * override a caller that has said which grammar it means.
572
730
  * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
573
731
  * whose URI resolves to a registered language routes by URI.
574
732
  * 2. A single-language workspace always routes to that one language — so
@@ -587,6 +745,15 @@ export class DataServer {
587
745
  */
588
746
  resolveReferenceLanguage(source) {
589
747
  const registry = this.services.ServiceRegistry;
748
+ if (isSyntheticSource(source) && source.language !== undefined) {
749
+ const declared = registry.getServicesById(source.language);
750
+ if (declared) {
751
+ return declared;
752
+ }
753
+ // Falling through on an UNREGISTERED id rather than failing: the id
754
+ // crosses the wire, so a client built against a head with one more
755
+ // grammar would otherwise lose queries the steps below can answer.
756
+ }
590
757
  // `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
591
758
  // an extensionless / unregistered URI falls through to the steps below
592
759
  // rather than throwing "no services for the extension ''".
@@ -698,12 +865,7 @@ export class DataServer {
698
865
  // decides policy at its own layer; `root` is optional on the envelope
699
866
  // so the compiler forces that decision. Adopters preferring to throw
700
867
  // override `envelope`.
701
- return {
702
- uri: uri.toString(),
703
- version: 0,
704
- root: undefined,
705
- diagnostics: []
706
- };
868
+ return TransferDocument.absent(uri.toString());
707
869
  }
708
870
  return this.encoder.toTransferDocument(document);
709
871
  }
@@ -715,6 +877,54 @@ export class DataServer {
715
877
  */
716
878
  subscribeToDocumentBuilder() {
717
879
  this.disposables.push(this.services.workspace.DocumentBuilder.onDocumentPhase(this.options.subscriptionPhase, (document, cancelToken) => this.dispatchPhaseEvent(document, cancelToken)));
880
+ // The BUILD-phase hook, not the per-document one: this notification is one
881
+ // message per build rather than one per document, and Langium hands the
882
+ // whole batch over here. It also does not fire for a cancelled build,
883
+ // which is what the per-document dispatch has to check by hand.
884
+ this.disposables.push(this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built)));
885
+ }
886
+ /**
887
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
888
+ * and that NOBODY on this
889
+ * connection is watching — the ones a client was not told about through
890
+ * {@link dispatchPhaseEvent}, which is gated per URI.
891
+ *
892
+ * **The gap this closes is the one no other source can observe.** A document
893
+ * the client watches, it hears about already. A file changed on disk, the
894
+ * host's own filesystem watcher reports — and on a browser host, where the
895
+ * workspace lives behind this head, an external change cannot happen at all.
896
+ * What is left, and what nothing outside the server can see, is a document
897
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
898
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
899
+ * the update channel is silent by design. A consumer displaying data derived
900
+ * from that document — a tree label, a decorator — otherwise goes stale with
901
+ * no signal from any source, and repairs itself the moment someone opens the
902
+ * file to investigate, which is what makes it expensive to diagnose later.
903
+ *
904
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
905
+ * rather than being handed transfer documents it did not ask for. That is the
906
+ * property the subscription map protects, and it is preserved here by
907
+ * carrying no document rather than by gating the message.
908
+ *
909
+ * Quiet in the common case. Editing a document that an editor has open leaves
910
+ * that URI watched and therefore out of this set, so a build with no
911
+ * dependents produces nothing at all, and workspace initialisation produces
912
+ * nothing because it does not build to this phase. The ceiling is a
913
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
914
+ *
915
+ * The URI is canonicalised for the same reason the subscription map is keyed
916
+ * that way, and is untested for the same reason as its twin in
917
+ * {@link dispatchDeleteEvents}: the builder reports URIs out of its own
918
+ * store, so a non-canonical one cannot be produced without a fixture
919
+ * asserting a shape the real system never emits.
920
+ */
921
+ dispatchBuiltEvent(built) {
922
+ const uris = built.map(document => this.canonicalKey(document.uri.toString())).filter(uri => !this.subscriptions.has(uri));
923
+ if (uris.length === 0) {
924
+ return;
925
+ }
926
+ this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
927
+ this.clientProxy.onDocumentsBuilt({ uris });
718
928
  }
719
929
  /**
720
930
  * Subscribe to the universal save event on `HydraniumTextDocuments` so a
@@ -734,19 +944,67 @@ export class DataServer {
734
944
  this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
735
945
  }
736
946
  /**
737
- * Mark the last-close transition per URI (see
738
- * {@link pendingRevertBroadcasts}). The listener consults
739
- * `isOpenInAnyClient` AFTER the store decremented the closing client's
740
- * hold, so a `false` answer means this close was the last one.
947
+ * Mark each document the store releases after its last close (see
948
+ * {@link pendingRevertBroadcasts}). A release, not the close itself: a
949
+ * document whose last client lost its connection is released only once
950
+ * the revert grace runs out, or when another client opens it meanwhile, and
951
+ * not at all when a client lost from it opens it again within its own
952
+ * grace.
741
953
  */
742
954
  subscribeToTextDocumentCloses() {
743
- const textDocuments = this.services.workspace.TextDocuments;
744
- this.disposables.push(textDocuments.onDidClose(event => {
745
- if (!textDocuments.isOpenInAnyClient(event.document.uri)) {
746
- this.pendingRevertBroadcasts.add(this.canonicalKey(event.document.uri));
747
- }
955
+ this.disposables.push(this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
956
+ this.pendingRevertBroadcasts.add(this.canonicalKey(event.uri));
748
957
  }));
749
958
  }
959
+ /**
960
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
961
+ * rather than only to the ones watching that URI.
962
+ *
963
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
964
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
965
+ * fire on every build, so the subscription map is what keeps bandwidth
966
+ * proportional to what a client asked for. A deletion is neither: it is one
967
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
968
+ * document's content. Gating it forces any consumer that displays the
969
+ * workspace — a model tree, a file decorator — to learn about disappearances
970
+ * from a filesystem watcher instead, which a client hosted in a browser has
971
+ * no way to run: its workspace lives behind the head. A client that does not
972
+ * care filters on the URI, which costs it a comparison.
973
+ *
974
+ * The precedent is the last-close revert broadcast (see
975
+ * {@link pendingRevertBroadcasts}), where the same judgement was already made
976
+ * in the other direction: a transition that matters enough is delivered
977
+ * without a subscription.
978
+ *
979
+ * Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
980
+ * listener, which is the only place a deletion is observable: `update`
981
+ * removes the document before deriving the rebuild set, so it is never built.
982
+ * That ordering also puts this notification ahead of the `'rebuilt'` events
983
+ * for the dependents whose references the deletion just broke.
984
+ *
985
+ * The `deleted` list arrives already expanded to concrete document URIs —
986
+ * `deleteDocuments` resolves a directory URI to the documents beneath it — so
987
+ * no caller has to handle a directory here.
988
+ *
989
+ * Per-URI derived state is dropped for the same reason it is dropped
990
+ * anywhere: it describes a document that no longer exists.
991
+ * {@link lastEmittedFingerprint} in particular can outlive its subscriptions
992
+ * through the last-close revert path — left behind, it is adopted as the
993
+ * baseline by the next {@link watchModelDocument} and suppresses the first
994
+ * emit after the file returns with its previous content.
995
+ *
996
+ * The subscription itself SURVIVES: a recreated file resumes delivering to
997
+ * the same watchers with no re-subscription, and a client that answers the
998
+ * deletion by closing releases the watch through `closeModelDocument` anyway.
999
+ */
1000
+ dispatchDeleteEvents(deleted) {
1001
+ for (const removed of deleted) {
1002
+ const uri = this.canonicalKey(removed.toString());
1003
+ this.lastEmittedFingerprint.delete(uri);
1004
+ this.pendingRevertBroadcasts.delete(uri);
1005
+ this.clientProxy.onDocumentDeleted({ uri });
1006
+ }
1007
+ }
750
1008
  /** Fan out a save event for the document's URI, gated by the subscription map. */
751
1009
  dispatchSaveEvent(event) {
752
1010
  // The save event arrives under the CLIENT URI the text store keys by (e.g. a
@@ -855,26 +1113,19 @@ export class DataServer {
855
1113
  /**
856
1114
  * Discriminate the reason for a phase-event-driven update notification.
857
1115
  * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
858
- * - URI in the `deleted` list → `'deleted'`
859
1116
  * - URI in the `changed` list → `'changed'` (the URI was passed to
860
1117
  * `documentBuilder.update(changed, deleted)`, which spans `didChange`
861
1118
  * text-document events and programmatic `update([uri], [])` calls).
862
1119
  * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
863
1120
  * because something it depends on changed; its own text wasn't flagged).
864
1121
  *
865
- * `'saved'` is NOT emitted from this code path — saves take the dedicated
866
- * `DataClientProtocol.onDocumentSaved` channel; adopters that want a
867
- * unified update stream synthesise `'saved'` in their bridge layer.
1122
+ * `'saved'` is NOT emitted here — saves take the dedicated
1123
+ * `DataClientProtocol.onDocumentSaved` channel, and adopters wanting a
1124
+ * unified stream synthesise it in their bridge layer. A deletion is not a
1125
+ * reason at all; see {@link dispatchDeleteEvents}.
868
1126
  */
869
1127
  resolveUpdateReason(uri) {
870
- const last = this.lastBuildUpdate;
871
- if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
872
- return 'deleted';
873
- }
874
- if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
875
- return 'changed';
876
- }
877
- return 'rebuilt';
1128
+ return this.lastBuildUpdate?.changed.some(changed => UriUtils.equals(changed, uri)) ? 'changed' : 'rebuilt';
878
1129
  }
879
1130
  /**
880
1131
  * Subscribe to the project tier's change channel and re-fan registry
@@ -967,7 +1218,7 @@ export class DataServer {
967
1218
  }
968
1219
  async stopProfiling(args) {
969
1220
  if (!this.activeProfile) {
970
- throw new Error('No profiling capture is active; call startProfiling first.');
1221
+ throw noActiveProfileError();
971
1222
  }
972
1223
  const capture = this.activeProfile;
973
1224
  this.activeProfile = undefined;
@@ -996,7 +1247,8 @@ export class DataServer {
996
1247
  methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
997
1248
  additionalMethods,
998
1249
  excludedMethods: partial.excludedMethods ?? [],
999
- diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
1250
+ diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
1251
+ referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
1000
1252
  };
1001
1253
  }
1002
1254
  }