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

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, TIMED_OUT, 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,35 +279,46 @@ 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();
294
+ this.subscribeToDirtyChanges();
258
295
  this.subscribeToTextDocumentCloses();
259
296
  this.subscribeToProjectManager();
260
297
  // Self-register teardown so an adopter that keeps no reference to the
261
298
  // server still releases per-connection state, with no lifecycle hook of
262
- // its own. See `dispose`.
263
- this.disposables.push(connection.onClose(() => this.dispose()));
299
+ // its own. The client did not close anything itself, so its sessions end
300
+ // as lost and each document it was the last to have open waits out the
301
+ // store's revert grace. See `dispose`.
302
+ this.disposables.push(connection.onClose(() => this.dispose('lost')));
264
303
  }
265
304
  /**
266
305
  * Release everything the constructor wired up — the bound protocol
267
306
  * handlers and every listener — and clear the subscription map and the
268
307
  * per-URI emission-fingerprint cache, so a long-lived shared services
269
308
  * 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.
309
+ * closes. Also ends every session this connection registered, which closes
310
+ * every document it has open: the SHARED store's state rather than this
311
+ * server's, which outlives the connection unless released here.
273
312
  *
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.
313
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
314
+ * connection closes, so adopters who don't hold a reference still get
315
+ * per-connection cleanup; adopters that DO hold a reference may call
316
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
317
+ * `'closed'` reverts every document whose last open they close at once,
318
+ * and `'lost'`, the connection's own close, lets each wait out the revert
319
+ * grace.
278
320
  */
279
- dispose() {
321
+ dispose(cause = 'closed') {
280
322
  this.disposed = true;
281
323
  // Release an in-flight interactive capture so the process-wide inspector
282
324
  // singleton is not left active after the connection closes.
@@ -285,97 +327,166 @@ export class DataServer {
285
327
  this.activeProfile = undefined;
286
328
  void capture.stop({}).catch(() => undefined);
287
329
  }
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.
330
+ // AFTER `disposables.dispose()`, deliberately: ending a session releases
331
+ // each document it was the last to hold, and this server's own
332
+ // `onDidCloseLastOpen` listener would otherwise mark a revert broadcast
333
+ // for a connection that is already gone.
291
334
  this.disposables.dispose();
292
- this.closeOpenDocuments();
335
+ for (const [clientId, session] of this.clientSessions) {
336
+ this.endSession(clientId, session, cause);
337
+ }
293
338
  this.subscriptions.clear();
294
339
  this.lastEmittedFingerprint.clear();
295
340
  this.pendingRevertBroadcasts.clear();
296
341
  }
297
342
  // ============================================================
298
- // DataServerProtocol implementation — delegates to ModelService.
343
+ // DataServerProtocol implementation
299
344
  // ============================================================
300
345
  //
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);
346
+ // Reads go to `ModelService`; a request that opens or writes a document
347
+ // goes to the session this connection registered under its `clientId`.
348
+ // Each answer is encoded on the wire boundary via
349
+ // `encoder.astDocumentToTransferDocument`. To change how documents are
350
+ // read, override on the ModelService subclass; to change how they are
351
+ // written, on the session class the bound `ClientSessionFactory` builds.
352
+ async createSession(args) {
353
+ // After teardown nothing would ever end a session registered now, and its
354
+ // id would stay taken for the life of the process.
355
+ if (this.disposed) {
356
+ throw new SessionClosedError(args.clientId);
357
+ }
358
+ const resumable = this.resumableSessions();
359
+ const previous = resumable.get(args.clientId);
360
+ if (previous && args.resumeToken !== undefined && previous.token === args.resumeToken) {
361
+ previous.end();
362
+ }
363
+ const session = this.modelService.createSession(args.label, args.clientId);
364
+ this.clientSessions.set(args.clientId, session);
365
+ if (args.resumeToken !== undefined) {
366
+ // Taken over by a client registering again after its connection
367
+ // dropped, so the old session ends as lost: the documents it was the
368
+ // last to have open wait out the grace, and the new session's opens
369
+ // find their unsaved text.
370
+ resumable.set(args.clientId, { token: args.resumeToken, end: () => this.endSession(args.clientId, session, 'lost') });
371
+ }
341
372
  }
342
373
  /**
343
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
344
- * close it a second time. Idempotent.
374
+ * End a session this connection registered. The ended handle stays in
375
+ * {@link clientSessions}, as it does after {@link dispose}, so a request for
376
+ * the id still arriving fails with the ended session's own error.
345
377
  */
346
- forgetOpenDocument(uri, clientId) {
347
- const holders = this.openedDocuments.get(uri);
348
- if (!holders) {
349
- return;
378
+ async closeSession(args) {
379
+ const session = this.clientSessions.get(args.clientId);
380
+ if (session) {
381
+ this.endSession(args.clientId, session);
350
382
  }
351
- holders.delete(clientId);
352
- if (holders.size === 0) {
353
- this.openedDocuments.delete(uri);
383
+ }
384
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
385
+ endSession(clientId, session, cause = 'closed') {
386
+ for (const [uri, watchers] of this.subscriptions) {
387
+ if (watchers.delete(clientId) && watchers.size === 0) {
388
+ this.subscriptions.delete(uri);
389
+ this.lastEmittedFingerprint.delete(uri);
390
+ }
354
391
  }
392
+ session.dispose(cause);
355
393
  }
356
394
  /**
357
- * Close every document still open over this connection, for the clients that
358
- * opened it here.
395
+ * The resumable sessions of this services tree, by client id, across all of
396
+ * its data connections: a client resumes on another connection than the one
397
+ * that registered it. An entry leaves when its session ends, by any path, so
398
+ * it keeps no ended connection alive.
359
399
  *
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.
400
+ * A takeover by resume token ends the old session even when its connection
401
+ * is still alive, so two clients that shared an id and its token would end
402
+ * each other's sessions. And the token is a guard against colliding with a
403
+ * session the server has not yet seen end, not a secret: the wire carries no
404
+ * authentication, and a peer that learns the token can end the session.
405
+ */
406
+ resumableSessions() {
407
+ let sessions = resumableByModelService.get(this.modelService);
408
+ if (!sessions) {
409
+ const created = new Map();
410
+ // Subscribed once per services tree, and never disposed: it lives as
411
+ // long as the text store it listens to.
412
+ this.services.workspace.TextDocuments.onDidCloseSession(event => created.delete(event.clientId));
413
+ resumableByModelService.set(this.modelService, created);
414
+ sessions = created;
415
+ }
416
+ return sessions;
417
+ }
418
+ async createModelDocument(args) {
419
+ const session = this.requireSession(args.clientId);
420
+ await session.create(args.uri, args.text);
421
+ return this.openedSnapshot(args.uri, () => session.close(args.uri));
422
+ }
423
+ async updateModelDocuments(args) {
424
+ const astDocuments = await this.requireSession(args.clientId).updateAll({
425
+ updates: args.updates.map(update => this.toSessionWrite(update))
426
+ });
427
+ return astDocuments.map(astDocument => this.encodeDocument(astDocument));
428
+ }
429
+ /**
430
+ * The session write a wire write request carries. Only the fields a session
431
+ * takes: a field an adopter adds to a request reaches the session only
432
+ * through an override of this.
433
+ */
434
+ toSessionWrite(request) {
435
+ return { uri: request.uri, model: request.model, basedOn: request.basedOn };
436
+ }
437
+ /**
438
+ * The session this connection registered under `clientId`, which every
439
+ * document request acts as. An id that is not one fails with the
440
+ * closed-session code: opening or writing under it would leave an open that
441
+ * no session end ever closes.
442
+ */
443
+ requireSession(clientId) {
444
+ const session = this.clientSessions.get(clientId);
445
+ if (!session) {
446
+ throw new SessionClosedError(clientId, 'The client session was never registered on this connection.');
447
+ }
448
+ return session;
449
+ }
450
+ async openModelDocument(args) {
451
+ const session = this.requireSession(args.clientId);
452
+ const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
453
+ await session.open(args.uri, args.options);
454
+ // A repeat open keeps the earlier one, which is still in use.
455
+ return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
456
+ }
457
+ /**
458
+ * The snapshot a session's open or create answers with. When the read
459
+ * fails, `rollback` undoes the open this call made before the failure is
460
+ * rethrown: the caller sees no open, so nothing on its side would ever close
461
+ * it.
366
462
  *
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.
463
+ * Versioned with the store's shared version rather than the snapshot's own:
464
+ * the built document's `textDocument.version` lags the store's whenever the
465
+ * store assigned the version, and the store's is what a write's `basedOn` is
466
+ * compared against, so reporting the snapshot's would make the caller's
467
+ * first based-on write conflict with itself.
370
468
  */
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
- }
469
+ async openedSnapshot(uri, rollback) {
470
+ let document;
471
+ try {
472
+ document = await this.getModelDocument({ uri });
378
473
  }
474
+ catch (error) {
475
+ // The open's failure is the one the caller needs, not the cleanup's.
476
+ await rollback?.().catch(() => undefined);
477
+ throw error;
478
+ }
479
+ return { ...document, version: asSnapshotVersion(this.services.workspace.TextDocuments.version(uri)) };
480
+ }
481
+ async closeModelDocument(args) {
482
+ // Through the handle, so a close under an ended session fails as that
483
+ // session's calls do, and a session class's own close is honoured.
484
+ const session = this.requireSession(args.clientId);
485
+ // Closing also releases the watch for (uri, clientId) — a forgotten
486
+ // unwatch would otherwise leak phase-event dispatch until the connection
487
+ // closes. Idempotent: a close without a prior watch is a no-op.
488
+ await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
489
+ await session.close(args.uri);
379
490
  }
380
491
  async getModelDocument(args) {
381
492
  // Smart dispatch: a warm document (already in LangiumDocuments) is
@@ -390,15 +501,15 @@ export class DataServer {
390
501
  // `includeDiagnostics: true` to settle at `Validated` instead.
391
502
  const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
392
503
  const astDocument = await this.modelService.ensureDocumentState(args.uri, state);
393
- return this.encoder.astDocumentToTransferDocument(astDocument);
504
+ return this.encodeDocument(astDocument);
394
505
  }
395
506
  async updateModelDocument(args) {
396
- const astDocument = await this.modelService.update(args);
397
- return this.encoder.astDocumentToTransferDocument(astDocument);
507
+ const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
508
+ return this.encodeDocument(astDocument);
398
509
  }
399
510
  async saveModelDocument(args) {
400
- const astDocument = await this.modelService.save(args);
401
- return this.encoder.astDocumentToTransferDocument(astDocument);
511
+ const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
512
+ return this.encodeDocument(astDocument);
402
513
  }
403
514
  /**
404
515
  * Record a watch for `(uri, clientId)`. Subsequent phase events on `uri`
@@ -498,20 +609,50 @@ export class DataServer {
498
609
  // Resolve the language's reference services from each request's source
499
610
  // (see resolveReferenceServices) and delegate.
500
611
  // ============================================================
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;
612
+ /**
613
+ * Settle the build before a reference question is answered from the index.
614
+ *
615
+ * A query issued right after a model update otherwise races the rebuild and
616
+ * reads an index missing the symbols it asks about. The cost is not confined
617
+ * to this call: a scope built inside that window is cached, and the build's
618
+ * remaining documents link against it.
619
+ *
620
+ * Waits the source document specifically, but ONLY when one is loaded at
621
+ * that URI: a synthetic source can address a URI with no document (a
622
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
623
+ * found". Falls back to a global settle, matching the id-based
624
+ * `ElementSource` path.
625
+ *
626
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
627
+ */
628
+ async awaitReferencesLinked(source) {
629
+ const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
510
630
  const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
511
- await this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
631
+ const stopwatch = this.services.Clock.stopwatch();
632
+ const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
633
+ if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
634
+ return;
635
+ }
636
+ const elapsedMs = Math.round(stopwatch.elapsedMs);
637
+ // A per-URI wait resolves off a document-phase notification, so a
638
+ // missed one strands a wait on a document that HAS reached the
639
+ // phase. Re-read before failing; the workspace-wide wait has no
640
+ // equivalent reading and can only reject.
641
+ const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
642
+ if (waitUri && document && document.state >= DocumentState.Linked) {
643
+ this.tracer
644
+ .withUri(waitUri.toString())
645
+ .warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
646
+ return;
647
+ }
648
+ throw referenceSettleTimeoutError(elapsedMs);
649
+ }
650
+ async findReferenceCandidates(ctx) {
651
+ await this.awaitReferencesLinked(ctx.source);
512
652
  return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
513
653
  }
514
654
  async resolveReference(ref) {
655
+ await this.awaitReferencesLinked(ref.source);
515
656
  const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
516
657
  if (!resolved) {
517
658
  return undefined;
@@ -526,7 +667,14 @@ export class DataServer {
526
667
  // synthetic source — and the create-element flow driving this method is
527
668
  // the one that produces directory URIs, on which a bare
528
669
  // `getServices(uri)` throws while `findReferenceCandidates` succeeds.
529
- const nameProvider = this.resolveReferenceServices(ReferenceSource.synthetic(args.uri, args.type)).NameProvider;
670
+ const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
671
+ // Mid-rebuild the names of documents not yet re-indexed are absent from
672
+ // the taken set, and the caller PERSISTS what it is handed. Nothing
673
+ // reserves the answer either, so a name is free of the collisions the
674
+ // index knows about and of nothing else — two callers racing get the same
675
+ // proposal, which only uniqueness at the write can catch.
676
+ await this.awaitReferencesLinked(source);
677
+ const nameProvider = this.resolveReferenceServices(source).NameProvider;
530
678
  const tier = args.tier ?? 'project';
531
679
  if (tier === 'public') {
532
680
  return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
@@ -569,6 +717,9 @@ export class DataServer {
569
717
  /**
570
718
  * Pick the language that owns a reference source, in order:
571
719
  *
720
+ * 0. A {@link isSyntheticSource} naming its own `language` routes there.
721
+ * First because every step below infers, and an inference must not
722
+ * override a caller that has said which grammar it means.
572
723
  * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
573
724
  * whose URI resolves to a registered language routes by URI.
574
725
  * 2. A single-language workspace always routes to that one language — so
@@ -587,6 +738,15 @@ export class DataServer {
587
738
  */
588
739
  resolveReferenceLanguage(source) {
589
740
  const registry = this.services.ServiceRegistry;
741
+ if (isSyntheticSource(source) && source.language !== undefined) {
742
+ const declared = registry.getServicesById(source.language);
743
+ if (declared) {
744
+ return declared;
745
+ }
746
+ // Falling through on an UNREGISTERED id rather than failing: the id
747
+ // crosses the wire, so a client built against a head with one more
748
+ // grammar would otherwise lose queries the steps below can answer.
749
+ }
590
750
  // `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
591
751
  // an extensionless / unregistered URI falls through to the steps below
592
752
  // rather than throwing "no services for the extension ''".
@@ -698,14 +858,26 @@ export class DataServer {
698
858
  // decides policy at its own layer; `root` is optional on the envelope
699
859
  // so the compiler forces that decision. Adopters preferring to throw
700
860
  // override `envelope`.
701
- return {
702
- uri: uri.toString(),
703
- version: 0,
704
- root: undefined,
705
- diagnostics: []
706
- };
861
+ return TransferDocument.absent(uri.toString());
707
862
  }
708
- return this.encoder.toTransferDocument(document);
863
+ return this.withDirtyState(this.encoder.toTransferDocument(document));
864
+ }
865
+ /**
866
+ * The transfer document a request answers with for `astDocument`, the
867
+ * store's current `dirty` stamped on it by {@link withDirtyState}. Every
868
+ * document a request answers with goes through here, so none goes out
869
+ * without the stamp.
870
+ */
871
+ encodeDocument(astDocument) {
872
+ return this.withDirtyState(this.encoder.astDocumentToTransferDocument(astDocument));
873
+ }
874
+ /**
875
+ * `document` with the store's current {@link TransferDocument.dirty}. Read
876
+ * when the document is sent rather than kept with the build: a save changes
877
+ * the answer without a rebuild.
878
+ */
879
+ withDirtyState(document) {
880
+ return { ...document, dirty: this.services.workspace.TextDocuments.isDirty(document.uri) };
709
881
  }
710
882
  /**
711
883
  * Subscribe one listener at the configured {@link DataServerOptions.subscriptionPhase}.
@@ -715,6 +887,54 @@ export class DataServer {
715
887
  */
716
888
  subscribeToDocumentBuilder() {
717
889
  this.disposables.push(this.services.workspace.DocumentBuilder.onDocumentPhase(this.options.subscriptionPhase, (document, cancelToken) => this.dispatchPhaseEvent(document, cancelToken)));
890
+ // The BUILD-phase hook, not the per-document one: this notification is one
891
+ // message per build rather than one per document, and Langium hands the
892
+ // whole batch over here. It also does not fire for a cancelled build,
893
+ // which is what the per-document dispatch has to check by hand.
894
+ this.disposables.push(this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built)));
895
+ }
896
+ /**
897
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
898
+ * and that NOBODY on this
899
+ * connection is watching — the ones a client was not told about through
900
+ * {@link dispatchPhaseEvent}, which is gated per URI.
901
+ *
902
+ * **The gap this closes is the one no other source can observe.** A document
903
+ * the client watches, it hears about already. A file changed on disk, the
904
+ * host's own filesystem watcher reports — and on a browser host, where the
905
+ * workspace lives behind this head, an external change cannot happen at all.
906
+ * What is left, and what nothing outside the server can see, is a document
907
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
908
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
909
+ * the update channel is silent by design. A consumer displaying data derived
910
+ * from that document — a tree label, a decorator — otherwise goes stale with
911
+ * no signal from any source, and repairs itself the moment someone opens the
912
+ * file to investigate, which is what makes it expensive to diagnose later.
913
+ *
914
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
915
+ * rather than being handed transfer documents it did not ask for. That is the
916
+ * property the subscription map protects, and it is preserved here by
917
+ * carrying no document rather than by gating the message.
918
+ *
919
+ * Quiet in the common case. Editing a document that an editor has open leaves
920
+ * that URI watched and therefore out of this set, so a build with no
921
+ * dependents produces nothing at all, and workspace initialisation produces
922
+ * nothing because it does not build to this phase. The ceiling is a
923
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
924
+ *
925
+ * The URI is canonicalised for the same reason the subscription map is keyed
926
+ * that way, and is untested for the same reason as its twin in
927
+ * {@link dispatchDeleteEvents}: the builder reports URIs out of its own
928
+ * store, so a non-canonical one cannot be produced without a fixture
929
+ * asserting a shape the real system never emits.
930
+ */
931
+ dispatchBuiltEvent(built) {
932
+ const uris = built.map(document => this.canonicalKey(document.uri.toString())).filter(uri => !this.subscriptions.has(uri));
933
+ if (uris.length === 0) {
934
+ return;
935
+ }
936
+ this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
937
+ this.clientProxy.onDocumentsBuilt({ uris });
718
938
  }
719
939
  /**
720
940
  * Subscribe to the universal save event on `HydraniumTextDocuments` so a
@@ -733,20 +953,83 @@ export class DataServer {
733
953
  subscribeToTextDocumentSaves() {
734
954
  this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
735
955
  }
956
+ /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
957
+ subscribeToDirtyChanges() {
958
+ this.disposables.push(this.services.workspace.TextDocuments.onDidChangeDirty(event => this.dispatchDirtyEvent(event)));
959
+ }
736
960
  /**
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.
961
+ * Send a dirty flip to the connection, gated by the subscription map as
962
+ * {@link dispatchSaveEvent} is: the answer at any one moment travels on
963
+ * every document sent, so a client that watches nothing reads it there.
964
+ */
965
+ dispatchDirtyEvent(event) {
966
+ const uri = this.canonicalKey(event.uri);
967
+ if (this.subscriptions.has(uri)) {
968
+ this.clientProxy.onDocumentDirtyChanged({ uri, dirty: event.dirty });
969
+ }
970
+ }
971
+ /**
972
+ * Mark each document the store releases after its last close (see
973
+ * {@link pendingRevertBroadcasts}). A release, not the close itself: a
974
+ * document whose last client lost its connection is released only once
975
+ * the revert grace runs out, or when another client opens it meanwhile, and
976
+ * not at all when a client lost from it opens it again within its own
977
+ * grace.
741
978
  */
742
979
  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
- }
980
+ this.disposables.push(this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
981
+ this.pendingRevertBroadcasts.add(this.canonicalKey(event.uri));
748
982
  }));
749
983
  }
984
+ /**
985
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
986
+ * rather than only to the ones watching that URI.
987
+ *
988
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
989
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
990
+ * fire on every build, so the subscription map is what keeps bandwidth
991
+ * proportional to what a client asked for. A deletion is neither: it is one
992
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
993
+ * document's content. Gating it forces any consumer that displays the
994
+ * workspace — a model tree, a file decorator — to learn about disappearances
995
+ * from a filesystem watcher instead, which a client hosted in a browser has
996
+ * no way to run: its workspace lives behind the head. A client that does not
997
+ * care filters on the URI, which costs it a comparison.
998
+ *
999
+ * The precedent is the last-close revert broadcast (see
1000
+ * {@link pendingRevertBroadcasts}), where the same judgement was already made
1001
+ * in the other direction: a transition that matters enough is delivered
1002
+ * without a subscription.
1003
+ *
1004
+ * Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
1005
+ * listener, which is the only place a deletion is observable: `update`
1006
+ * removes the document before deriving the rebuild set, so it is never built.
1007
+ * That ordering also puts this notification ahead of the `'rebuilt'` events
1008
+ * for the dependents whose references the deletion just broke.
1009
+ *
1010
+ * The `deleted` list arrives already expanded to concrete document URIs —
1011
+ * `deleteDocuments` resolves a directory URI to the documents beneath it — so
1012
+ * no caller has to handle a directory here.
1013
+ *
1014
+ * Per-URI derived state is dropped for the same reason it is dropped
1015
+ * anywhere: it describes a document that no longer exists.
1016
+ * {@link lastEmittedFingerprint} in particular can outlive its subscriptions
1017
+ * through the last-close revert path — left behind, it is adopted as the
1018
+ * baseline by the next {@link watchModelDocument} and suppresses the first
1019
+ * emit after the file returns with its previous content.
1020
+ *
1021
+ * The subscription itself SURVIVES: a recreated file resumes delivering to
1022
+ * the same watchers with no re-subscription, and a client that answers the
1023
+ * deletion by closing releases the watch through `closeModelDocument` anyway.
1024
+ */
1025
+ dispatchDeleteEvents(deleted) {
1026
+ for (const removed of deleted) {
1027
+ const uri = this.canonicalKey(removed.toString());
1028
+ this.lastEmittedFingerprint.delete(uri);
1029
+ this.pendingRevertBroadcasts.delete(uri);
1030
+ this.clientProxy.onDocumentDeleted({ uri });
1031
+ }
1032
+ }
750
1033
  /** Fan out a save event for the document's URI, gated by the subscription map. */
751
1034
  dispatchSaveEvent(event) {
752
1035
  // The save event arrives under the CLIENT URI the text store keys by (e.g. a
@@ -855,26 +1138,19 @@ export class DataServer {
855
1138
  /**
856
1139
  * Discriminate the reason for a phase-event-driven update notification.
857
1140
  * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
858
- * - URI in the `deleted` list → `'deleted'`
859
1141
  * - URI in the `changed` list → `'changed'` (the URI was passed to
860
1142
  * `documentBuilder.update(changed, deleted)`, which spans `didChange`
861
1143
  * text-document events and programmatic `update([uri], [])` calls).
862
1144
  * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
863
1145
  * because something it depends on changed; its own text wasn't flagged).
864
1146
  *
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.
1147
+ * `'saved'` is NOT emitted here — saves take the dedicated
1148
+ * `DataClientProtocol.onDocumentSaved` channel, and adopters wanting a
1149
+ * unified stream synthesise it in their bridge layer. A deletion is not a
1150
+ * reason at all; see {@link dispatchDeleteEvents}.
868
1151
  */
869
1152
  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';
1153
+ return this.lastBuildUpdate?.changed.some(changed => UriUtils.equals(changed, uri)) ? 'changed' : 'rebuilt';
878
1154
  }
879
1155
  /**
880
1156
  * Subscribe to the project tier's change channel and re-fan registry
@@ -967,7 +1243,7 @@ export class DataServer {
967
1243
  }
968
1244
  async stopProfiling(args) {
969
1245
  if (!this.activeProfile) {
970
- throw new Error('No profiling capture is active; call startProfiling first.');
1246
+ throw noActiveProfileError();
971
1247
  }
972
1248
  const capture = this.activeProfile;
973
1249
  this.activeProfile = undefined;
@@ -996,7 +1272,8 @@ export class DataServer {
996
1272
  methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
997
1273
  additionalMethods,
998
1274
  excludedMethods: partial.excludedMethods ?? [],
999
- diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
1275
+ diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
1276
+ referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
1000
1277
  };
1001
1278
  }
1002
1279
  }