@hydranium/data-server 1.0.0-next.13 → 1.0.0-next.132

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