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

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