@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.
@@ -9,12 +9,17 @@
9
9
 
10
10
  import {
11
11
  createRpcProxy,
12
+ defineMessage,
12
13
  DisposableCollection,
13
14
  isDocumentSource,
14
15
  isElementSource,
15
16
  isSyntheticSource,
17
+ messageError,
16
18
  ReferenceSource,
19
+ SessionClosedError,
20
+ TIMED_OUT,
17
21
  type CloseModelArgs,
22
+ type HydraniumResponseError,
18
23
  type Disposable,
19
24
  type ElementSource,
20
25
  type FindNextNameArgs,
@@ -28,8 +33,9 @@ import {
28
33
  type ReferenceTarget,
29
34
  type Tracer,
30
35
  type TransferDiagnostic,
31
- type TransferDocument,
32
- type TransferElement
36
+ TransferDocument,
37
+ type TransferElement,
38
+ asSnapshotVersion
33
39
  } from '@hydranium/protocol';
34
40
  import {
35
41
  DATA_SERVER_DIAGNOSTICS_METHODS,
@@ -42,24 +48,75 @@ import {
42
48
  type StartProfilingArgs,
43
49
  type StopProfilingArgs,
44
50
  type WriteServerHeapSnapshotArgs,
51
+ type CloseSessionArgs,
52
+ type CreateModelDocumentArgs,
53
+ type CreateSessionArgs,
45
54
  type GetModelDocumentArgs,
46
55
  type GetProjectForUriArgs,
47
56
  type TransferSaveDocumentArgs,
48
57
  type WatchModelDocumentArgs,
49
58
  type TransferDocumentSavedEvent,
50
59
  type TransferDocumentUpdatedEvent,
51
- type TransferUpdateDocumentArgs
60
+ type TransferUpdateDocumentArgs,
61
+ type TransferUpdateDocumentsArgs
52
62
  } from '@hydranium/protocol/data';
53
63
  import { REVERT_ON_CLOSE_CLIENT_ID, UNKNOWN_CLIENT_ID } from '@hydranium/core';
54
64
  import { defaultDataServerDiagnostics } from './default-diagnostics.js';
65
+
66
+ /**
67
+ * Raised when a profiling command arrives with no capture running.
68
+ *
69
+ * A `ResponseError` rather than a plain `Error` so the identity survives to the
70
+ * response boundary, which is where the message is rendered. An unwrapped throw
71
+ * reaches the client as a generic internal error instead: no code for a caller
72
+ * to switch on, and nothing for the boundary to render from.
73
+ */
74
+ export const NO_ACTIVE_PROFILE = defineMessage(
75
+ 'hydranium/data-server/no-active-profile',
76
+ 'No profiling capture is active; call startProfiling first.'
77
+ );
78
+
79
+ /**
80
+ * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
81
+ * survives reconstruction and is what a caller switches on.
82
+ */
83
+ export const NO_ACTIVE_PROFILE_CODE = 1002;
84
+
85
+ export const noActiveProfileError = (): HydraniumResponseError => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
86
+
87
+ /**
88
+ * Raised when a reference question's wait for the build exceeds
89
+ * {@link DataServerOptions.referenceSettleTimeoutMs}.
90
+ *
91
+ * A `ResponseError` because a class name does not cross RPC: without the code a
92
+ * wire client cannot tell a wedged build from a reference that resolves to
93
+ * nothing, which is the distinction the wait exists to keep.
94
+ */
95
+ export const REFERENCE_SETTLE_TIMEOUT = defineMessage(
96
+ 'hydranium/data-server/reference-settle-timeout',
97
+ 'Timed out after {elapsedMs}ms waiting for the build to settle before answering a reference query.'
98
+ );
99
+
100
+ /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
101
+ export const REFERENCE_SETTLE_TIMEOUT_CODE = 1003;
102
+
103
+ export const referenceSettleTimeoutError = (elapsedMs: number): HydraniumResponseError =>
104
+ messageError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT, { elapsedMs });
105
+
55
106
  import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
56
107
  import type {
108
+ ClientSession,
109
+ ClientSessionWriteArgs,
57
110
  ClientTextDocumentChangeEvent,
111
+ DocumentDirtyChangedEvent,
58
112
  HydraniumLanguageServices,
59
113
  LogNameOptions,
114
+ AstDiagnostic,
115
+ AstDocument,
60
116
  ModelService,
61
117
  ProjectChangeEvent,
62
118
  ServerSharedServices,
119
+ SessionEndCause,
63
120
  TransferEncoder
64
121
  } from '@hydranium/core';
65
122
  import type { TextDocument } from 'vscode-languageserver-textdocument';
@@ -104,6 +161,18 @@ function fingerprintHash(parts: readonly string[]): string {
104
161
  return high + low;
105
162
  }
106
163
 
164
+ /**
165
+ * A session a data connection registered with a resume token, and how to end
166
+ * it from another connection. See {@link DataServer.resumableSessions}.
167
+ */
168
+ export interface ResumableSession {
169
+ readonly token: string;
170
+ /** End the session as its connection closing would. */
171
+ readonly end: () => void;
172
+ }
173
+
174
+ const resumableByModelService = new WeakMap<object, Map<string, ResumableSession>>();
175
+
107
176
  /**
108
177
  * Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
109
178
  * de-dup `onDocumentUpdated` emissions.
@@ -201,6 +270,22 @@ export interface DataServerOptions extends LogNameOptions {
201
270
  */
202
271
  readonly fingerprintStrategy?: FingerprintStrategy;
203
272
 
273
+ /**
274
+ * How long a reference question waits for the build to reach `Linked` before
275
+ * failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the
276
+ * wait resolves off a build-phase notification, so a build cancelled below
277
+ * `Linked` with nothing after it leaves the request unanswered for the life
278
+ * of the server.
279
+ *
280
+ * Expiry rejects rather than reading the index anyway: the unsettled index
281
+ * is what the wait keeps the caller away from, so falling through to it on a
282
+ * slow build reinstates the fault — and on a name proposal persists it.
283
+ *
284
+ * Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace
285
+ * still reaching `Linked` for the first time.
286
+ */
287
+ readonly referenceSettleTimeoutMs?: number;
288
+
204
289
  /**
205
290
  * Wire-method namespace for both inbound request handlers and the
206
291
  * outbound notification client proxy. Defaults to
@@ -258,15 +343,20 @@ export interface DataServerOptions extends LogNameOptions {
258
343
  * When supplied, every inbound data-server RPC is timed into this collector
259
344
  * (via the `createRpcProxy` binding) and exposed through
260
345
  * {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an
261
- * LSP connection can pass the SAME collector to
262
- * `instrumentLspConnection(connection, latency)` so one report covers both
263
- * heads. Absent by default (no timing overhead).
346
+ * LSP connection can pass the SAME collector through `lspLatencyOptions` to
347
+ * that connection, so one report covers both heads. Absent by default (no
348
+ * timing overhead).
264
349
  */
265
350
  readonly latency?: LatencyCollector;
266
351
  }
267
352
 
268
- /** Fully-resolved variant — every field set, used internally after merging defaults. */
269
- interface ResolvedDataServerOptions {
353
+ /**
354
+ * Fully-resolved variant of {@link DataServerOptions} — every field set, after
355
+ * merging defaults. Returned by the `protected`
356
+ * {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so
357
+ * an adopter changing how defaults resolve has to name it.
358
+ */
359
+ export interface ResolvedDataServerOptions {
270
360
  readonly subscriptionPhase: DocumentState;
271
361
  readonly fingerprintStrategy: FingerprintStrategy;
272
362
  readonly methodNamespace: string;
@@ -274,6 +364,7 @@ interface ResolvedDataServerOptions {
274
364
  readonly excludedMethods: readonly string[];
275
365
  /** Always resolved — to the caller's, or to the platform default. */
276
366
  readonly diagnostics: DataServerDiagnosticsProvider;
367
+ readonly referenceSettleTimeoutMs: number;
277
368
  }
278
369
 
279
370
  /**
@@ -301,9 +392,11 @@ interface ResolvedDataServerOptions {
301
392
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
302
393
  * builds the {@link DataClientProtocol} notification proxy on the same
303
394
  * connection in one {@link createRpcProxy} call (binding `this` as its
304
- * `localTarget`) under the configured namespace, and subscribes one
305
- * `DocumentBuilder.onDocumentPhase` listener per configured phase that
306
- * dispatches subscription events via `clientProxy.onDocumentUpdated`.
395
+ * `localTarget`) under the configured namespace, and subscribes two listeners
396
+ * at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
397
+ * per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
398
+ * `DocumentBuilder.onBuildPhase` one dispatching a single
399
+ * `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
307
400
  *
308
401
  * The data-server requires the full {@link ServerSharedServices}
309
402
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -331,35 +424,36 @@ export class DataServer<
331
424
  * Framework defaults, exposed so an adopter can spread them when
332
425
  * extending rather than restate a value the framework may change.
333
426
  */
334
- static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>> = {
335
- subscriptionPhase: DocumentState.Validated
427
+ static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>> = {
428
+ subscriptionPhase: DocumentState.Validated,
429
+ referenceSettleTimeoutMs: 60_000
336
430
  };
337
431
 
338
432
  protected readonly options: ResolvedDataServerOptions;
339
433
  /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
340
434
  protected readonly subscriptions = new Map<string, Set<string>>();
341
435
  /**
342
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
343
- * connection.
436
+ * The client sessions this connection registered, by client id. A document
437
+ * request carrying one of these ids acts as that session; one carrying any
438
+ * other id fails.
344
439
  *
345
- * Kept because the document store releases a client's hold only from an
346
- * explicit close, and a client that dies without closing would otherwise keep
347
- * the document open forever — resident, and with its last-close revert
348
- * suppressed. The store has no notion of which connection a clientId reached
349
- * it over, so the connection-scoped set has to live here; teaching it a client
350
- * identity is the more robust and much larger alternative.
440
+ * Entries stay after {@link dispose} has ended their sessions, so a request
441
+ * still running from before the connection closed reaches the ended handle
442
+ * and fails with the session's own error.
351
443
  */
352
- protected readonly openedDocuments = new Map<string, Set<string>>();
444
+ protected readonly clientSessions = new Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer>>();
353
445
  /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
354
446
  protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
355
447
  protected readonly disposables = new DisposableCollection();
356
448
  /**
357
449
  * Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
358
450
  * `reason` discrimination on outbound `onDocumentUpdated` notifications:
359
- * a URI in the `changed` list emits `'changed'`, in `deleted` emits
360
- * `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
361
- * URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
362
- * the LSP side, so reason fidelity stays consistent between heads.
451
+ * a URI in the `changed` list emits `'changed'`, otherwise `'rebuilt'`
452
+ * (cascade rebuild from a dependent URI's change). The same mechanism
453
+ * `AstDocumentManager.onUpdate` uses on the LSP side, so reason fidelity
454
+ * stays consistent between heads. The `deleted` half is read by
455
+ * {@link dispatchDeleteEvents} rather than by the reason discrimination,
456
+ * a deletion travelling on its own channel.
363
457
  */
364
458
  protected lastBuildUpdate?: { changed: readonly URI[]; deleted: readonly URI[] };
365
459
  /**
@@ -399,12 +493,12 @@ export class DataServer<
399
493
  */
400
494
  protected readonly lastEmittedFingerprint = new Map<string, string>();
401
495
  /**
402
- * URIs whose LAST client just closed. The update handler rebuilds such a
403
- * document from its disk content (discarding unsaved in-session edits),
404
- * but {@link dispatchPhaseEvent} gates on the subscription map — and the
405
- * last close typically also removed the last watcher, so consumers that
406
- * only ever fetch via `getModelDocument` would keep showing the
407
- * discarded state forever. Marked on the last-close transition (see
496
+ * URIs the text store just released after their last close. The store
497
+ * rebuilds such a document from its disk content (discarding unsaved
498
+ * in-session edits), but {@link dispatchPhaseEvent} gates on the
499
+ * subscription map — and the last close typically also removed the last
500
+ * watcher, so consumers that only ever fetch via `getModelDocument` would
501
+ * keep showing the discarded state forever. Marked on the release (see
408
502
  * {@link subscribeToTextDocumentCloses}) and consumed by
409
503
  * {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
410
504
  * phase event even without a subscription — de-duplicated against
@@ -420,27 +514,23 @@ export class DataServer<
420
514
  /** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */
421
515
  protected readonly latency?: LatencyCollector;
422
516
  /** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */
423
- protected readonly encoder: TransferEncoder<unknown, TDiagnostic>;
517
+ protected readonly encoder: TransferEncoder<TDiagnostic>;
424
518
  /**
425
519
  * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
426
- * The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
427
- * carry LSP-shape diagnostics in their AstDocument (e.g. an adopter's LSP-shape diagnostic type)
428
- * while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
429
- * `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
430
- * to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
520
+ * Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
521
+ * {@link encoder} converts one into the other on the way out.
431
522
  */
432
- protected readonly modelService: ModelService<AstNode, unknown, TTransfer>;
523
+ protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
433
524
 
434
525
  constructor(
435
526
  protected readonly connection: MessageConnection,
436
- protected readonly services: ServerSharedServices<TProject>,
527
+ protected readonly services: ServerSharedServices<TProject, TDiagnostic>,
437
528
  options: DataServerOptions = {}
438
529
  ) {
439
530
  this.options = this.resolveOptions(options);
440
531
  this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
441
532
  // DI-bound: adopters rebind `services.model.TransferEncoder` /
442
- // `services.model.ModelService` with their own subclasses. Slot types use the
443
- // framework upper bounds; the casts below narrow to this instance's generics.
533
+ // `services.model.ModelService` with their own subclasses.
444
534
  const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
445
535
  if (!encoder || !modelService) {
446
536
  throw new Error(
@@ -448,8 +538,8 @@ export class DataServer<
448
538
  'Did you compose `createServerSharedModule(ctx)` into your shared module?'
449
539
  );
450
540
  }
451
- this.encoder = encoder as TransferEncoder<unknown, TDiagnostic>;
452
- this.modelService = modelService as ModelService<AstNode, unknown, TTransfer>;
541
+ this.encoder = encoder;
542
+ this.modelService = modelService;
453
543
  const excluded = new Set<string>(this.options.excludedMethods);
454
544
  const registeredMethods = [
455
545
  ...DATA_SERVER_PROTOCOL_METHODS,
@@ -465,21 +555,29 @@ export class DataServer<
465
555
  methodNamespace: this.options.methodNamespace,
466
556
  localTarget: this,
467
557
  localMethods: registeredMethods as readonly (keyof this & string)[],
468
- latency: this.latency
558
+ latency: this.latency,
559
+ // Bound at the chokepoint rather than per handler, so an adopter's
560
+ // `additionalMethods` are rendered on the same terms as the
561
+ // framework's own rejections.
562
+ renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
469
563
  });
470
564
  this.disposables.push(
471
565
  this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
472
566
  this.lastBuildUpdate = { changed, deleted };
567
+ this.dispatchDeleteEvents(deleted);
473
568
  })
474
569
  );
475
570
  this.subscribeToDocumentBuilder();
476
571
  this.subscribeToTextDocumentSaves();
572
+ this.subscribeToDirtyChanges();
477
573
  this.subscribeToTextDocumentCloses();
478
574
  this.subscribeToProjectManager();
479
575
  // Self-register teardown so an adopter that keeps no reference to the
480
576
  // server still releases per-connection state, with no lifecycle hook of
481
- // its own. See `dispose`.
482
- this.disposables.push(connection.onClose(() => this.dispose()));
577
+ // its own. The client did not close anything itself, so its sessions end
578
+ // as lost and each document it was the last to have open waits out the
579
+ // store's revert grace. See `dispose`.
580
+ this.disposables.push(connection.onClose(() => this.dispose('lost')));
483
581
  }
484
582
 
485
583
  /**
@@ -487,16 +585,19 @@ export class DataServer<
487
585
  * handlers and every listener — and clear the subscription map and the
488
586
  * per-URI emission-fingerprint cache, so a long-lived shared services
489
587
  * bundle does not retain per-connection memory after the connection
490
- * closes. Also closes every document still open over this connection (see
491
- * {@link closeOpenDocuments}), which is the SHARED store's state rather than
492
- * this server's and so outlives the connection unless released here.
588
+ * closes. Also ends every session this connection registered, which closes
589
+ * every document it has open: the SHARED store's state rather than this
590
+ * server's, which outlives the connection unless released here.
493
591
  *
494
- * Idempotent: subsequent calls are no-ops. Self-fires on
495
- * `connection.onClose` so adopters who don't hold a reference still
496
- * get per-connection cleanup; adopters that DO hold a reference may
497
- * call `dispose()` directly for early teardown.
592
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
593
+ * connection closes, so adopters who don't hold a reference still get
594
+ * per-connection cleanup; adopters that DO hold a reference may call
595
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
596
+ * `'closed'` reverts every document whose last open they close at once,
597
+ * and `'lost'`, the connection's own close, lets each wait out the revert
598
+ * grace.
498
599
  */
499
- dispose(): void {
600
+ dispose(cause: SessionEndCause = 'closed'): void {
500
601
  this.disposed = true;
501
602
  // Release an in-flight interactive capture so the process-wide inspector
502
603
  // singleton is not left active after the connection closes.
@@ -505,102 +606,181 @@ export class DataServer<
505
606
  this.activeProfile = undefined;
506
607
  void capture.stop({}).catch(() => undefined);
507
608
  }
508
- // AFTER `disposables.dispose()`, deliberately: closing a document fires
509
- // `onDidClose`, and this server's own close listener would otherwise mark a
510
- // revert broadcast for a connection that is already gone.
609
+ // AFTER `disposables.dispose()`, deliberately: ending a session releases
610
+ // each document it was the last to hold, and this server's own
611
+ // `onDidCloseLastOpen` listener would otherwise mark a revert broadcast
612
+ // for a connection that is already gone.
511
613
  this.disposables.dispose();
512
- this.closeOpenDocuments();
614
+ for (const [clientId, session] of this.clientSessions) {
615
+ this.endSession(clientId, session, cause);
616
+ }
513
617
  this.subscriptions.clear();
514
618
  this.lastEmittedFingerprint.clear();
515
619
  this.pendingRevertBroadcasts.clear();
516
620
  }
517
621
 
518
622
  // ============================================================
519
- // DataServerProtocol implementation — delegates to ModelService.
623
+ // DataServerProtocol implementation
520
624
  // ============================================================
521
625
  //
522
- // The lifecycle methods (`get` / `update` / `save` / `ready`) forward
523
- // straight to `ModelService` and encode the returned `AstDocument` on
524
- // the wire boundary via `encoder.astDocumentToTransferDocument`.
525
- // Adopters customising lifecycle behaviour (normalisation, supersession,
526
- // settled-phase choice, etc.) override on the ModelService subclass —
527
- // no override on DataServer is needed.
528
-
529
- async openModelDocument(args: OpenModelArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
530
- // Register the editor session (idempotent — `ModelService.open` refreshes
531
- // an already-open document rather than re-opening), then return the built
532
- // state at the configured target phase. The one-shot snapshot; subsequent
533
- // build-phase events arrive via `watchModelDocument`.
534
- await this.modelService.open(args);
535
- // Record the hold so `dispose` can release it for a client that never
536
- // closes. Keyed by the URI as given, because that is what `close` takes.
537
- let holders = this.openedDocuments.get(args.uri);
538
- if (!holders) {
539
- holders = new Set<string>();
540
- this.openedDocuments.set(args.uri, holders);
626
+ // Reads go to `ModelService`; a request that opens or writes a document
627
+ // goes to the session this connection registered under its `clientId`.
628
+ // Each answer is encoded on the wire boundary via
629
+ // `encoder.astDocumentToTransferDocument`. To change how documents are
630
+ // read, override on the ModelService subclass; to change how they are
631
+ // written, on the session class the bound `ClientSessionFactory` builds.
632
+
633
+ async createSession(args: CreateSessionArgs): Promise<void> {
634
+ // After teardown nothing would ever end a session registered now, and its
635
+ // id would stay taken for the life of the process.
636
+ if (this.disposed) {
637
+ throw new SessionClosedError(args.clientId);
638
+ }
639
+ const resumable = this.resumableSessions();
640
+ const previous = resumable.get(args.clientId);
641
+ if (previous && args.resumeToken !== undefined && previous.token === args.resumeToken) {
642
+ previous.end();
643
+ }
644
+ const session = this.modelService.createSession(args.label, args.clientId);
645
+ this.clientSessions.set(args.clientId, session);
646
+ if (args.resumeToken !== undefined) {
647
+ // Taken over by a client registering again after its connection
648
+ // dropped, so the old session ends as lost: the documents it was the
649
+ // last to have open wait out the grace, and the new session's opens
650
+ // find their unsaved text.
651
+ resumable.set(args.clientId, { token: args.resumeToken, end: () => this.endSession(args.clientId, session, 'lost') });
541
652
  }
542
- holders.add(args.clientId);
543
- const document = await this.getModelDocument({ uri: args.uri });
544
- // Project the authoritative client-facing version onto the open snapshot.
545
- // `getModelDocument` encodes the freshly-built AST snapshot, whose version
546
- // is the `LangiumDocument`'s own `textDocument.version`. That lags the
547
- // multi-client synced version whenever the open seeded the synced document
548
- // with a caller-supplied version id — and the synced version is what
549
- // `ModelService.update`'s optimistic-concurrency gate compares
550
- // `baseVersion` against, so reporting the snapshot's would make the
551
- // caller's first tagged write self-conflict. A genuine concurrent edit
552
- // still trips the gate and is reconciled by the caller's replay rather
553
- // than predicted here.
554
- return { ...document, version: this.services.workspace.TextDocuments.version(args.uri) };
555
653
  }
556
654
 
557
- async closeModelDocument(args: CloseModelArgs): Promise<void> {
558
- // Closing a session also releases its watch for (uri, clientId) — a
559
- // forgotten unwatch would otherwise leak phase-event dispatch until the
560
- // connection closes. Idempotent: a close without a prior watch is a no-op.
561
- await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
562
- this.forgetOpenDocument(args.uri, args.clientId);
563
- await this.modelService.close(args);
655
+ /**
656
+ * End a session this connection registered. The ended handle stays in
657
+ * {@link clientSessions}, as it does after {@link dispose}, so a request for
658
+ * the id still arriving fails with the ended session's own error.
659
+ */
660
+ async closeSession(args: CloseSessionArgs): Promise<void> {
661
+ const session = this.clientSessions.get(args.clientId);
662
+ if (session) {
663
+ this.endSession(args.clientId, session);
664
+ }
665
+ }
666
+
667
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
668
+ protected endSession(
669
+ clientId: string,
670
+ session: ClientSession<AstNode, AstDiagnostic, TTransfer>,
671
+ cause: SessionEndCause = 'closed'
672
+ ): void {
673
+ for (const [uri, watchers] of this.subscriptions) {
674
+ if (watchers.delete(clientId) && watchers.size === 0) {
675
+ this.subscriptions.delete(uri);
676
+ this.lastEmittedFingerprint.delete(uri);
677
+ }
678
+ }
679
+ session.dispose(cause);
564
680
  }
565
681
 
566
682
  /**
567
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
568
- * close it a second time. Idempotent.
683
+ * The resumable sessions of this services tree, by client id, across all of
684
+ * its data connections: a client resumes on another connection than the one
685
+ * that registered it. An entry leaves when its session ends, by any path, so
686
+ * it keeps no ended connection alive.
687
+ *
688
+ * A takeover by resume token ends the old session even when its connection
689
+ * is still alive, so two clients that shared an id and its token would end
690
+ * each other's sessions. And the token is a guard against colliding with a
691
+ * session the server has not yet seen end, not a secret: the wire carries no
692
+ * authentication, and a peer that learns the token can end the session.
569
693
  */
570
- protected forgetOpenDocument(uri: string, clientId: string): void {
571
- const holders = this.openedDocuments.get(uri);
572
- if (!holders) {
573
- return;
694
+ protected resumableSessions(): Map<string, ResumableSession> {
695
+ let sessions = resumableByModelService.get(this.modelService);
696
+ if (!sessions) {
697
+ const created = new Map<string, ResumableSession>();
698
+ // Subscribed once per services tree, and never disposed: it lives as
699
+ // long as the text store it listens to.
700
+ this.services.workspace.TextDocuments.onDidCloseSession(event => created.delete(event.clientId));
701
+ resumableByModelService.set(this.modelService, created);
702
+ sessions = created;
574
703
  }
575
- holders.delete(clientId);
576
- if (holders.size === 0) {
577
- this.openedDocuments.delete(uri);
704
+ return sessions;
705
+ }
706
+
707
+ async createModelDocument(args: CreateModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
708
+ const session = this.requireSession(args.clientId);
709
+ await session.create(args.uri, args.text);
710
+ return this.openedSnapshot(args.uri, () => session.close(args.uri));
711
+ }
712
+
713
+ async updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>[]> {
714
+ const astDocuments = await this.requireSession(args.clientId).updateAll({
715
+ updates: args.updates.map(update => this.toSessionWrite(update))
716
+ });
717
+ return astDocuments.map(astDocument => this.encodeDocument(astDocument));
718
+ }
719
+
720
+ /**
721
+ * The session write a wire write request carries. Only the fields a session
722
+ * takes: a field an adopter adds to a request reaches the session only
723
+ * through an override of this.
724
+ */
725
+ protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer> {
726
+ return { uri: request.uri, model: request.model, basedOn: request.basedOn };
727
+ }
728
+
729
+ /**
730
+ * The session this connection registered under `clientId`, which every
731
+ * document request acts as. An id that is not one fails with the
732
+ * closed-session code: opening or writing under it would leave an open that
733
+ * no session end ever closes.
734
+ */
735
+ protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer> {
736
+ const session = this.clientSessions.get(clientId);
737
+ if (!session) {
738
+ throw new SessionClosedError(clientId, 'The client session was never registered on this connection.');
578
739
  }
740
+ return session;
741
+ }
742
+
743
+ async openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
744
+ const session = this.requireSession(args.clientId);
745
+ const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
746
+ await session.open(args.uri, args.options);
747
+ // A repeat open keeps the earlier one, which is still in use.
748
+ return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
579
749
  }
580
750
 
581
751
  /**
582
- * Close every document still open over this connection, for the clients that
583
- * opened it here.
752
+ * The snapshot a session's open or create answers with. When the read
753
+ * fails, `rollback` undoes the open this call made before the failure is
754
+ * rethrown: the caller sees no open, so nothing on its side would ever close
755
+ * it.
584
756
  *
585
- * The document store releases a per-URI hold only from an explicit close, so
586
- * without this a client that dies mid-session keeps its documents open for the
587
- * lifetime of the process: `isOpenInAnyClient` stays true, the document stays
588
- * resident, and the last-close revert never runs. A long-lived multi-client
589
- * head is the configuration where a dead client is normal rather than
590
- * exceptional, so the leak accumulates there.
591
- *
592
- * Runs from {@link dispose}, which is synchronous, so each close is fired and
593
- * its failure swallowed — a teardown must not reject, and a URI whose close
594
- * fails is no worse off than it was before this drain existed.
757
+ * Versioned with the store's shared version rather than the snapshot's own:
758
+ * the built document's `textDocument.version` lags the store's whenever the
759
+ * store assigned the version, and the store's is what a write's `basedOn` is
760
+ * compared against, so reporting the snapshot's would make the caller's
761
+ * first based-on write conflict with itself.
595
762
  */
596
- protected closeOpenDocuments(): void {
597
- const held = [...this.openedDocuments];
598
- this.openedDocuments.clear();
599
- for (const [uri, clientIds] of held) {
600
- for (const clientId of clientIds) {
601
- void Promise.resolve(this.modelService.close({ uri, clientId })).catch(() => undefined);
602
- }
763
+ protected async openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
764
+ let document: TransferDocument<TTransfer, TDiagnostic>;
765
+ try {
766
+ document = await this.getModelDocument({ uri });
767
+ } catch (error: unknown) {
768
+ // The open's failure is the one the caller needs, not the cleanup's.
769
+ await rollback?.().catch(() => undefined);
770
+ throw error;
603
771
  }
772
+ return { ...document, version: asSnapshotVersion(this.services.workspace.TextDocuments.version(uri)) };
773
+ }
774
+
775
+ async closeModelDocument(args: CloseModelArgs): Promise<void> {
776
+ // Through the handle, so a close under an ended session fails as that
777
+ // session's calls do, and a session class's own close is honoured.
778
+ const session = this.requireSession(args.clientId);
779
+ // Closing also releases the watch for (uri, clientId) — a forgotten
780
+ // unwatch would otherwise leak phase-event dispatch until the connection
781
+ // closes. Idempotent: a close without a prior watch is a no-op.
782
+ await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
783
+ await session.close(args.uri);
604
784
  }
605
785
 
606
786
  async getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
@@ -616,17 +796,17 @@ export class DataServer<
616
796
  // `includeDiagnostics: true` to settle at `Validated` instead.
617
797
  const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
618
798
  const astDocument = await this.modelService.ensureDocumentState(args.uri, state);
619
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
799
+ return this.encodeDocument(astDocument);
620
800
  }
621
801
 
622
802
  async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
623
- const astDocument = await this.modelService.update(args);
624
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
803
+ const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
804
+ return this.encodeDocument(astDocument);
625
805
  }
626
806
 
627
807
  async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
628
- const astDocument = await this.modelService.save(args);
629
- return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
808
+ const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
809
+ return this.encodeDocument(astDocument);
630
810
  }
631
811
 
632
812
  /**
@@ -734,26 +914,57 @@ export class DataServer<
734
914
  // (see resolveReferenceServices) and delegate.
735
915
  // ============================================================
736
916
 
737
- async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
738
- // Candidates are derived from resolved cross-references, so the relevant document(s) must
739
- // have finished the Linked phase — otherwise a query issued right after a model update races
740
- // the asynchronous rebuild and returns stale candidates. Wait the source document
741
- // specifically, but ONLY when a document is actually loaded at that URI: a synthetic source
742
- // can address a URI with no document (a directory URI, typically), and a per-URI `waitUntil`
743
- // there throws "No document found". Fall back to a global Linked settle, matching the
744
- // id-based ElementSource (no URI) path.
745
- const uri = isDocumentSource(ctx.source) || isSyntheticSource(ctx.source) ? UriUtils.toUri(ctx.source.uri) : undefined;
917
+ /**
918
+ * Settle the build before a reference question is answered from the index.
919
+ *
920
+ * A query issued right after a model update otherwise races the rebuild and
921
+ * reads an index missing the symbols it asks about. The cost is not confined
922
+ * to this call: a scope built inside that window is cached, and the build's
923
+ * remaining documents link against it.
924
+ *
925
+ * Waits the source document specifically, but ONLY when one is loaded at
926
+ * that URI: a synthetic source can address a URI with no document (a
927
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
928
+ * found". Falls back to a global settle, matching the id-based
929
+ * `ElementSource` path.
930
+ *
931
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
932
+ */
933
+ protected async awaitReferencesLinked(source: ReferenceSource): Promise<void> {
934
+ const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
746
935
  const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
747
- await this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
936
+ const stopwatch = this.services.Clock.stopwatch();
937
+ const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
938
+ if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
939
+ return;
940
+ }
941
+ const elapsedMs = Math.round(stopwatch.elapsedMs);
942
+ // A per-URI wait resolves off a document-phase notification, so a
943
+ // missed one strands a wait on a document that HAS reached the
944
+ // phase. Re-read before failing; the workspace-wide wait has no
945
+ // equivalent reading and can only reject.
946
+ const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
947
+ if (waitUri && document && document.state >= DocumentState.Linked) {
948
+ this.tracer
949
+ .withUri(waitUri.toString())
950
+ .warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
951
+ return;
952
+ }
953
+ throw referenceSettleTimeoutError(elapsedMs);
954
+ }
955
+
956
+ async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
957
+ await this.awaitReferencesLinked(ctx.source);
748
958
  return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
749
959
  }
750
960
 
751
961
  async resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined> {
962
+ await this.awaitReferencesLinked(ref.source);
752
963
  const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
753
964
  if (!resolved) {
754
965
  return undefined;
755
966
  }
756
- const element = this.encoder.toTransfer(resolved.node) as unknown as TTransfer;
967
+ const element = this.encoder.toTransfer(resolved.node) as TTransfer;
757
968
  return { ...resolved.candidate, element };
758
969
  }
759
970
 
@@ -764,7 +975,14 @@ export class DataServer<
764
975
  // synthetic source — and the create-element flow driving this method is
765
976
  // the one that produces directory URIs, on which a bare
766
977
  // `getServices(uri)` throws while `findReferenceCandidates` succeeds.
767
- const nameProvider = this.resolveReferenceServices(ReferenceSource.synthetic(args.uri, args.type)).NameProvider;
978
+ const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
979
+ // Mid-rebuild the names of documents not yet re-indexed are absent from
980
+ // the taken set, and the caller PERSISTS what it is handed. Nothing
981
+ // reserves the answer either, so a name is free of the collisions the
982
+ // index knows about and of nothing else — two callers racing get the same
983
+ // proposal, which only uniqueness at the write can catch.
984
+ await this.awaitReferencesLinked(source);
985
+ const nameProvider = this.resolveReferenceServices(source).NameProvider;
768
986
  const tier = args.tier ?? 'project';
769
987
  if (tier === 'public') {
770
988
  return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
@@ -772,7 +990,7 @@ export class DataServer<
772
990
  if (tier === 'local') {
773
991
  // Document-scoped uniqueness: the document root is the container.
774
992
  const document = await this.modelService.ensureDocumentState(args.uri);
775
- return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root as AstNode) : args.proposal;
993
+ return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
776
994
  }
777
995
  const project = this.services.workspace.ProjectManager.getProject(uri);
778
996
  if (!project) {
@@ -811,6 +1029,9 @@ export class DataServer<
811
1029
  /**
812
1030
  * Pick the language that owns a reference source, in order:
813
1031
  *
1032
+ * 0. A {@link isSyntheticSource} naming its own `language` routes there.
1033
+ * First because every step below infers, and an inference must not
1034
+ * override a caller that has said which grammar it means.
814
1035
  * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
815
1036
  * whose URI resolves to a registered language routes by URI.
816
1037
  * 2. A single-language workspace always routes to that one language — so
@@ -829,6 +1050,15 @@ export class DataServer<
829
1050
  */
830
1051
  protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined {
831
1052
  const registry = this.services.ServiceRegistry;
1053
+ if (isSyntheticSource(source) && source.language !== undefined) {
1054
+ const declared = registry.getServicesById(source.language);
1055
+ if (declared) {
1056
+ return declared;
1057
+ }
1058
+ // Falling through on an UNREGISTERED id rather than failing: the id
1059
+ // crosses the wire, so a client built against a head with one more
1060
+ // grammar would otherwise lose queries the steps below can answer.
1061
+ }
832
1062
  // `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
833
1063
  // an extensionless / unregistered URI falls through to the steps below
834
1064
  // rather than throwing "no services for the extension ''".
@@ -839,7 +1069,7 @@ export class DataServer<
839
1069
  }
840
1070
  const all = registry.all;
841
1071
  if (all.length === 1) {
842
- return all[0] as HydraniumLanguageServices;
1072
+ return all[0];
843
1073
  }
844
1074
  if (isElementSource(source)) {
845
1075
  const documentUri = this.findElementDocumentUri(source);
@@ -945,14 +1175,28 @@ export class DataServer<
945
1175
  // decides policy at its own layer; `root` is optional on the envelope
946
1176
  // so the compiler forces that decision. Adopters preferring to throw
947
1177
  // override `envelope`.
948
- return {
949
- uri: uri.toString(),
950
- version: 0,
951
- root: undefined,
952
- diagnostics: [] as TDiagnostic[]
953
- };
1178
+ return TransferDocument.absent<TTransfer, TDiagnostic>(uri.toString());
954
1179
  }
955
- return this.encoder.toTransferDocument<AstNode>(document) as unknown as TransferDocument<TTransfer, TDiagnostic>;
1180
+ return this.withDirtyState(this.encoder.toTransferDocument(document) as TransferDocument<TTransfer, TDiagnostic>);
1181
+ }
1182
+
1183
+ /**
1184
+ * The transfer document a request answers with for `astDocument`, the
1185
+ * store's current `dirty` stamped on it by {@link withDirtyState}. Every
1186
+ * document a request answers with goes through here, so none goes out
1187
+ * without the stamp.
1188
+ */
1189
+ protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
1190
+ return this.withDirtyState(this.encoder.astDocumentToTransferDocument(astDocument) as TransferDocument<TTransfer, TDiagnostic>);
1191
+ }
1192
+
1193
+ /**
1194
+ * `document` with the store's current {@link TransferDocument.dirty}. Read
1195
+ * when the document is sent rather than kept with the build: a save changes
1196
+ * the answer without a rebuild.
1197
+ */
1198
+ protected withDirtyState(document: TransferDocument<TTransfer, TDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
1199
+ return { ...document, dirty: this.services.workspace.TextDocuments.isDirty(document.uri) };
956
1200
  }
957
1201
 
958
1202
  /**
@@ -967,6 +1211,57 @@ export class DataServer<
967
1211
  this.dispatchPhaseEvent(document, cancelToken)
968
1212
  )
969
1213
  );
1214
+ // The BUILD-phase hook, not the per-document one: this notification is one
1215
+ // message per build rather than one per document, and Langium hands the
1216
+ // whole batch over here. It also does not fire for a cancelled build,
1217
+ // which is what the per-document dispatch has to check by hand.
1218
+ this.disposables.push(
1219
+ this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built))
1220
+ );
1221
+ }
1222
+
1223
+ /**
1224
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
1225
+ * and that NOBODY on this
1226
+ * connection is watching — the ones a client was not told about through
1227
+ * {@link dispatchPhaseEvent}, which is gated per URI.
1228
+ *
1229
+ * **The gap this closes is the one no other source can observe.** A document
1230
+ * the client watches, it hears about already. A file changed on disk, the
1231
+ * host's own filesystem watcher reports — and on a browser host, where the
1232
+ * workspace lives behind this head, an external change cannot happen at all.
1233
+ * What is left, and what nothing outside the server can see, is a document
1234
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
1235
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
1236
+ * the update channel is silent by design. A consumer displaying data derived
1237
+ * from that document — a tree label, a decorator — otherwise goes stale with
1238
+ * no signal from any source, and repairs itself the moment someone opens the
1239
+ * file to investigate, which is what makes it expensive to diagnose later.
1240
+ *
1241
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
1242
+ * rather than being handed transfer documents it did not ask for. That is the
1243
+ * property the subscription map protects, and it is preserved here by
1244
+ * carrying no document rather than by gating the message.
1245
+ *
1246
+ * Quiet in the common case. Editing a document that an editor has open leaves
1247
+ * that URI watched and therefore out of this set, so a build with no
1248
+ * dependents produces nothing at all, and workspace initialisation produces
1249
+ * nothing because it does not build to this phase. The ceiling is a
1250
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
1251
+ *
1252
+ * The URI is canonicalised for the same reason the subscription map is keyed
1253
+ * that way, and is untested for the same reason as its twin in
1254
+ * {@link dispatchDeleteEvents}: the builder reports URIs out of its own
1255
+ * store, so a non-canonical one cannot be produced without a fixture
1256
+ * asserting a shape the real system never emits.
1257
+ */
1258
+ protected dispatchBuiltEvent(built: readonly LangiumDocument[]): void {
1259
+ const uris = built.map(document => this.canonicalKey(document.uri.toString())).filter(uri => !this.subscriptions.has(uri));
1260
+ if (uris.length === 0) {
1261
+ return;
1262
+ }
1263
+ this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
1264
+ this.clientProxy.onDocumentsBuilt({ uris });
970
1265
  }
971
1266
 
972
1267
  /**
@@ -987,23 +1282,89 @@ export class DataServer<
987
1282
  this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
988
1283
  }
989
1284
 
1285
+ /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
1286
+ protected subscribeToDirtyChanges(): void {
1287
+ this.disposables.push(this.services.workspace.TextDocuments.onDidChangeDirty(event => this.dispatchDirtyEvent(event)));
1288
+ }
1289
+
1290
+ /**
1291
+ * Send a dirty flip to the connection, gated by the subscription map as
1292
+ * {@link dispatchSaveEvent} is: the answer at any one moment travels on
1293
+ * every document sent, so a client that watches nothing reads it there.
1294
+ */
1295
+ protected dispatchDirtyEvent(event: DocumentDirtyChangedEvent): void {
1296
+ const uri = this.canonicalKey(event.uri);
1297
+ if (this.subscriptions.has(uri)) {
1298
+ this.clientProxy.onDocumentDirtyChanged({ uri, dirty: event.dirty });
1299
+ }
1300
+ }
1301
+
990
1302
  /**
991
- * Mark the last-close transition per URI (see
992
- * {@link pendingRevertBroadcasts}). The listener consults
993
- * `isOpenInAnyClient` AFTER the store decremented the closing client's
994
- * hold, so a `false` answer means this close was the last one.
1303
+ * Mark each document the store releases after its last close (see
1304
+ * {@link pendingRevertBroadcasts}). A release, not the close itself: a
1305
+ * document whose last client lost its connection is released only once
1306
+ * the revert grace runs out, or when another client opens it meanwhile, and
1307
+ * not at all when a client lost from it opens it again within its own
1308
+ * grace.
995
1309
  */
996
1310
  protected subscribeToTextDocumentCloses(): void {
997
- const textDocuments = this.services.workspace.TextDocuments;
998
1311
  this.disposables.push(
999
- textDocuments.onDidClose(event => {
1000
- if (!textDocuments.isOpenInAnyClient(event.document.uri)) {
1001
- this.pendingRevertBroadcasts.add(this.canonicalKey(event.document.uri));
1002
- }
1312
+ this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
1313
+ this.pendingRevertBroadcasts.add(this.canonicalKey(event.uri));
1003
1314
  })
1004
1315
  );
1005
1316
  }
1006
1317
 
1318
+ /**
1319
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
1320
+ * rather than only to the ones watching that URI.
1321
+ *
1322
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
1323
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
1324
+ * fire on every build, so the subscription map is what keeps bandwidth
1325
+ * proportional to what a client asked for. A deletion is neither: it is one
1326
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
1327
+ * document's content. Gating it forces any consumer that displays the
1328
+ * workspace — a model tree, a file decorator — to learn about disappearances
1329
+ * from a filesystem watcher instead, which a client hosted in a browser has
1330
+ * no way to run: its workspace lives behind the head. A client that does not
1331
+ * care filters on the URI, which costs it a comparison.
1332
+ *
1333
+ * The precedent is the last-close revert broadcast (see
1334
+ * {@link pendingRevertBroadcasts}), where the same judgement was already made
1335
+ * in the other direction: a transition that matters enough is delivered
1336
+ * without a subscription.
1337
+ *
1338
+ * Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
1339
+ * listener, which is the only place a deletion is observable: `update`
1340
+ * removes the document before deriving the rebuild set, so it is never built.
1341
+ * That ordering also puts this notification ahead of the `'rebuilt'` events
1342
+ * for the dependents whose references the deletion just broke.
1343
+ *
1344
+ * The `deleted` list arrives already expanded to concrete document URIs —
1345
+ * `deleteDocuments` resolves a directory URI to the documents beneath it — so
1346
+ * no caller has to handle a directory here.
1347
+ *
1348
+ * Per-URI derived state is dropped for the same reason it is dropped
1349
+ * anywhere: it describes a document that no longer exists.
1350
+ * {@link lastEmittedFingerprint} in particular can outlive its subscriptions
1351
+ * through the last-close revert path — left behind, it is adopted as the
1352
+ * baseline by the next {@link watchModelDocument} and suppresses the first
1353
+ * emit after the file returns with its previous content.
1354
+ *
1355
+ * The subscription itself SURVIVES: a recreated file resumes delivering to
1356
+ * the same watchers with no re-subscription, and a client that answers the
1357
+ * deletion by closing releases the watch through `closeModelDocument` anyway.
1358
+ */
1359
+ protected dispatchDeleteEvents(deleted: readonly URI[]): void {
1360
+ for (const removed of deleted) {
1361
+ const uri = this.canonicalKey(removed.toString());
1362
+ this.lastEmittedFingerprint.delete(uri);
1363
+ this.pendingRevertBroadcasts.delete(uri);
1364
+ this.clientProxy.onDocumentDeleted({ uri });
1365
+ }
1366
+ }
1367
+
1007
1368
  /** Fan out a save event for the document's URI, gated by the subscription map. */
1008
1369
  protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void {
1009
1370
  // The save event arrives under the CLIENT URI the text store keys by (e.g. a
@@ -1122,26 +1483,19 @@ export class DataServer<
1122
1483
  /**
1123
1484
  * Discriminate the reason for a phase-event-driven update notification.
1124
1485
  * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
1125
- * - URI in the `deleted` list → `'deleted'`
1126
1486
  * - URI in the `changed` list → `'changed'` (the URI was passed to
1127
1487
  * `documentBuilder.update(changed, deleted)`, which spans `didChange`
1128
1488
  * text-document events and programmatic `update([uri], [])` calls).
1129
1489
  * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
1130
1490
  * because something it depends on changed; its own text wasn't flagged).
1131
1491
  *
1132
- * `'saved'` is NOT emitted from this code path — saves take the dedicated
1133
- * `DataClientProtocol.onDocumentSaved` channel; adopters that want a
1134
- * unified update stream synthesise `'saved'` in their bridge layer.
1492
+ * `'saved'` is NOT emitted here — saves take the dedicated
1493
+ * `DataClientProtocol.onDocumentSaved` channel, and adopters wanting a
1494
+ * unified stream synthesise it in their bridge layer. A deletion is not a
1495
+ * reason at all; see {@link dispatchDeleteEvents}.
1135
1496
  */
1136
1497
  protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'] {
1137
- const last = this.lastBuildUpdate;
1138
- if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
1139
- return 'deleted';
1140
- }
1141
- if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
1142
- return 'changed';
1143
- }
1144
- return 'rebuilt';
1498
+ return this.lastBuildUpdate?.changed.some(changed => UriUtils.equals(changed, uri)) ? 'changed' : 'rebuilt';
1145
1499
  }
1146
1500
 
1147
1501
  /**
@@ -1243,7 +1597,7 @@ export class DataServer<
1243
1597
 
1244
1598
  async stopProfiling(args: StopProfilingArgs): Promise<string> {
1245
1599
  if (!this.activeProfile) {
1246
- throw new Error('No profiling capture is active; call startProfiling first.');
1600
+ throw noActiveProfileError();
1247
1601
  }
1248
1602
  const capture = this.activeProfile;
1249
1603
  this.activeProfile = undefined;
@@ -1262,7 +1616,7 @@ export class DataServer<
1262
1616
  /** Resolve a partial options object into a fully-defaulted form. */
1263
1617
  protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions {
1264
1618
  const additionalMethods = partial.additionalMethods ?? [];
1265
- const builtIn = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS] as readonly string[];
1619
+ const builtIn: readonly string[] = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS];
1266
1620
  const overlap = additionalMethods.filter(name => builtIn.includes(name));
1267
1621
  if (overlap.length > 0) {
1268
1622
  throw new Error(
@@ -1276,7 +1630,8 @@ export class DataServer<
1276
1630
  methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
1277
1631
  additionalMethods,
1278
1632
  excludedMethods: partial.excludedMethods ?? [],
1279
- diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
1633
+ diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
1634
+ referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
1280
1635
  };
1281
1636
  }
1282
1637
  }