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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,12 +9,16 @@
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,
17
20
  type CloseModelArgs,
21
+ type HydraniumResponseError,
18
22
  type Disposable,
19
23
  type ElementSource,
20
24
  type FindNextNameArgs,
@@ -28,8 +32,9 @@ import {
28
32
  type ReferenceTarget,
29
33
  type Tracer,
30
34
  type TransferDiagnostic,
31
- type TransferDocument,
32
- type TransferElement
35
+ TransferDocument,
36
+ type TransferElement,
37
+ asSnapshotVersion
33
38
  } from '@hydranium/protocol';
34
39
  import {
35
40
  DATA_SERVER_DIAGNOSTICS_METHODS,
@@ -42,24 +47,73 @@ import {
42
47
  type StartProfilingArgs,
43
48
  type StopProfilingArgs,
44
49
  type WriteServerHeapSnapshotArgs,
50
+ type CloseSessionArgs,
51
+ type CreateModelDocumentArgs,
52
+ type CreateSessionArgs,
45
53
  type GetModelDocumentArgs,
46
54
  type GetProjectForUriArgs,
47
55
  type TransferSaveDocumentArgs,
48
56
  type WatchModelDocumentArgs,
49
57
  type TransferDocumentSavedEvent,
50
58
  type TransferDocumentUpdatedEvent,
51
- type TransferUpdateDocumentArgs
59
+ type TransferUpdateDocumentArgs,
60
+ type TransferUpdateDocumentsArgs
52
61
  } from '@hydranium/protocol/data';
53
62
  import { REVERT_ON_CLOSE_CLIENT_ID, UNKNOWN_CLIENT_ID } from '@hydranium/core';
54
63
  import { defaultDataServerDiagnostics } from './default-diagnostics.js';
64
+
65
+ /**
66
+ * Raised when a profiling command arrives with no capture running.
67
+ *
68
+ * A `ResponseError` rather than a plain `Error` so the identity survives to the
69
+ * response boundary, which is where the message is rendered. An unwrapped throw
70
+ * reaches the client as a generic internal error instead: no code for a caller
71
+ * to switch on, and nothing for the boundary to render from.
72
+ */
73
+ export const NO_ACTIVE_PROFILE = defineMessage(
74
+ 'hydranium/data-server/no-active-profile',
75
+ 'No profiling capture is active; call startProfiling first.'
76
+ );
77
+
78
+ /**
79
+ * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
80
+ * survives reconstruction and is what a caller switches on.
81
+ */
82
+ export const NO_ACTIVE_PROFILE_CODE = 1002;
83
+
84
+ export const noActiveProfileError = (): HydraniumResponseError => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
85
+
86
+ /**
87
+ * Raised when a reference question's wait for the build exceeds
88
+ * {@link DataServerOptions.referenceSettleTimeoutMs}.
89
+ *
90
+ * A `ResponseError` because a class name does not cross RPC: without the code a
91
+ * wire client cannot tell a wedged build from a reference that resolves to
92
+ * nothing, which is the distinction the wait exists to keep.
93
+ */
94
+ export const REFERENCE_SETTLE_TIMEOUT = defineMessage(
95
+ 'hydranium/data-server/reference-settle-timeout',
96
+ 'Timed out after {elapsedMs}ms waiting for the build to settle before answering a reference query.'
97
+ );
98
+
99
+ /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
100
+ export const REFERENCE_SETTLE_TIMEOUT_CODE = 1003;
101
+
102
+ export const referenceSettleTimeoutError = (elapsedMs: number): HydraniumResponseError =>
103
+ messageError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT, { elapsedMs });
104
+
55
105
  import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
56
106
  import type {
107
+ ClientSession,
108
+ ClientSessionWriteArgs,
57
109
  ClientTextDocumentChangeEvent,
58
110
  HydraniumLanguageServices,
59
111
  LogNameOptions,
112
+ AstDiagnostic,
60
113
  ModelService,
61
114
  ProjectChangeEvent,
62
115
  ServerSharedServices,
116
+ SessionEndCause,
63
117
  TransferEncoder
64
118
  } from '@hydranium/core';
65
119
  import type { TextDocument } from 'vscode-languageserver-textdocument';
@@ -104,6 +158,18 @@ function fingerprintHash(parts: readonly string[]): string {
104
158
  return high + low;
105
159
  }
106
160
 
161
+ /**
162
+ * A session a data connection registered with a resume token, and how to end
163
+ * it from another connection. See {@link DataServer.resumableSessions}.
164
+ */
165
+ export interface ResumableSession {
166
+ readonly token: string;
167
+ /** End the session as its connection closing would. */
168
+ readonly end: () => void;
169
+ }
170
+
171
+ const resumableByModelService = new WeakMap<object, Map<string, ResumableSession>>();
172
+
107
173
  /**
108
174
  * Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
109
175
  * de-dup `onDocumentUpdated` emissions.
@@ -201,6 +267,22 @@ export interface DataServerOptions extends LogNameOptions {
201
267
  */
202
268
  readonly fingerprintStrategy?: FingerprintStrategy;
203
269
 
270
+ /**
271
+ * How long a reference question waits for the build to reach `Linked` before
272
+ * failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the
273
+ * wait resolves off a build-phase notification, so a build cancelled below
274
+ * `Linked` with nothing after it leaves the request unanswered for the life
275
+ * of the server.
276
+ *
277
+ * Expiry rejects rather than reading the index anyway: the unsettled index
278
+ * is what the wait keeps the caller away from, so falling through to it on a
279
+ * slow build reinstates the fault — and on a name proposal persists it.
280
+ *
281
+ * Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace
282
+ * still reaching `Linked` for the first time.
283
+ */
284
+ readonly referenceSettleTimeoutMs?: number;
285
+
204
286
  /**
205
287
  * Wire-method namespace for both inbound request handlers and the
206
288
  * outbound notification client proxy. Defaults to
@@ -258,15 +340,20 @@ export interface DataServerOptions extends LogNameOptions {
258
340
  * When supplied, every inbound data-server RPC is timed into this collector
259
341
  * (via the `createRpcProxy` binding) and exposed through
260
342
  * {@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).
343
+ * LSP connection can pass the SAME collector through `lspLatencyOptions` to
344
+ * that connection, so one report covers both heads. Absent by default (no
345
+ * timing overhead).
264
346
  */
265
347
  readonly latency?: LatencyCollector;
266
348
  }
267
349
 
268
- /** Fully-resolved variant — every field set, used internally after merging defaults. */
269
- interface ResolvedDataServerOptions {
350
+ /**
351
+ * Fully-resolved variant of {@link DataServerOptions} — every field set, after
352
+ * merging defaults. Returned by the `protected`
353
+ * {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so
354
+ * an adopter changing how defaults resolve has to name it.
355
+ */
356
+ export interface ResolvedDataServerOptions {
270
357
  readonly subscriptionPhase: DocumentState;
271
358
  readonly fingerprintStrategy: FingerprintStrategy;
272
359
  readonly methodNamespace: string;
@@ -274,6 +361,7 @@ interface ResolvedDataServerOptions {
274
361
  readonly excludedMethods: readonly string[];
275
362
  /** Always resolved — to the caller's, or to the platform default. */
276
363
  readonly diagnostics: DataServerDiagnosticsProvider;
364
+ readonly referenceSettleTimeoutMs: number;
277
365
  }
278
366
 
279
367
  /**
@@ -301,9 +389,11 @@ interface ResolvedDataServerOptions {
301
389
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
302
390
  * builds the {@link DataClientProtocol} notification proxy on the same
303
391
  * 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`.
392
+ * `localTarget`) under the configured namespace, and subscribes two listeners
393
+ * at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
394
+ * per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
395
+ * `DocumentBuilder.onBuildPhase` one dispatching a single
396
+ * `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
307
397
  *
308
398
  * The data-server requires the full {@link ServerSharedServices}
309
399
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -331,35 +421,36 @@ export class DataServer<
331
421
  * Framework defaults, exposed so an adopter can spread them when
332
422
  * extending rather than restate a value the framework may change.
333
423
  */
334
- static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>> = {
335
- subscriptionPhase: DocumentState.Validated
424
+ static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>> = {
425
+ subscriptionPhase: DocumentState.Validated,
426
+ referenceSettleTimeoutMs: 60_000
336
427
  };
337
428
 
338
429
  protected readonly options: ResolvedDataServerOptions;
339
430
  /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
340
431
  protected readonly subscriptions = new Map<string, Set<string>>();
341
432
  /**
342
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
343
- * connection.
433
+ * The client sessions this connection registered, by client id. A document
434
+ * request carrying one of these ids acts as that session; one carrying any
435
+ * other id fails.
344
436
  *
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.
437
+ * Entries stay after {@link dispose} has ended their sessions, so a request
438
+ * still running from before the connection closed reaches the ended handle
439
+ * and fails with the session's own error.
351
440
  */
352
- protected readonly openedDocuments = new Map<string, Set<string>>();
441
+ protected readonly clientSessions = new Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer>>();
353
442
  /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
354
443
  protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
355
444
  protected readonly disposables = new DisposableCollection();
356
445
  /**
357
446
  * Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
358
447
  * `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.
448
+ * a URI in the `changed` list emits `'changed'`, otherwise `'rebuilt'`
449
+ * (cascade rebuild from a dependent URI's change). The same mechanism
450
+ * `AstDocumentManager.onUpdate` uses on the LSP side, so reason fidelity
451
+ * stays consistent between heads. The `deleted` half is read by
452
+ * {@link dispatchDeleteEvents} rather than by the reason discrimination,
453
+ * a deletion travelling on its own channel.
363
454
  */
364
455
  protected lastBuildUpdate?: { changed: readonly URI[]; deleted: readonly URI[] };
365
456
  /**
@@ -399,12 +490,12 @@ export class DataServer<
399
490
  */
400
491
  protected readonly lastEmittedFingerprint = new Map<string, string>();
401
492
  /**
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
493
+ * URIs the text store just released after their last close. The store
494
+ * rebuilds such a document from its disk content (discarding unsaved
495
+ * in-session edits), but {@link dispatchPhaseEvent} gates on the
496
+ * subscription map — and the last close typically also removed the last
497
+ * watcher, so consumers that only ever fetch via `getModelDocument` would
498
+ * keep showing the discarded state forever. Marked on the release (see
408
499
  * {@link subscribeToTextDocumentCloses}) and consumed by
409
500
  * {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
410
501
  * phase event even without a subscription — de-duplicated against
@@ -420,7 +511,7 @@ export class DataServer<
420
511
  /** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */
421
512
  protected readonly latency?: LatencyCollector;
422
513
  /** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */
423
- protected readonly encoder: TransferEncoder<unknown, TDiagnostic>;
514
+ protected readonly encoder: TransferEncoder<TDiagnostic>;
424
515
  /**
425
516
  * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
426
517
  * The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
@@ -429,7 +520,7 @@ export class DataServer<
429
520
  * `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
430
521
  * to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
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,
@@ -448,8 +539,8 @@ export class DataServer<
448
539
  'Did you compose `createServerSharedModule(ctx)` into your shared module?'
449
540
  );
450
541
  }
451
- this.encoder = encoder as TransferEncoder<unknown, TDiagnostic>;
452
- this.modelService = modelService as ModelService<AstNode, unknown, TTransfer>;
542
+ this.encoder = encoder as TransferEncoder<TDiagnostic>;
543
+ this.modelService = modelService as ModelService<AstNode, AstDiagnostic, TTransfer>;
453
544
  const excluded = new Set<string>(this.options.excludedMethods);
454
545
  const registeredMethods = [
455
546
  ...DATA_SERVER_PROTOCOL_METHODS,
@@ -465,11 +556,16 @@ export class DataServer<
465
556
  methodNamespace: this.options.methodNamespace,
466
557
  localTarget: this,
467
558
  localMethods: registeredMethods as readonly (keyof this & string)[],
468
- latency: this.latency
559
+ latency: this.latency,
560
+ // Bound at the chokepoint rather than per handler, so an adopter's
561
+ // `additionalMethods` are rendered on the same terms as the
562
+ // framework's own rejections.
563
+ renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
469
564
  });
470
565
  this.disposables.push(
471
566
  this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
472
567
  this.lastBuildUpdate = { changed, deleted };
568
+ this.dispatchDeleteEvents(deleted);
473
569
  })
474
570
  );
475
571
  this.subscribeToDocumentBuilder();
@@ -478,8 +574,10 @@ export class DataServer<
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,184 @@ 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(
718
+ astDocument =>
719
+ this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>
720
+ );
721
+ }
722
+
723
+ /**
724
+ * The session write a wire write request carries. Only the fields a session
725
+ * takes: a field an adopter adds to a request reaches the session only
726
+ * through an override of this.
727
+ */
728
+ protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer> {
729
+ return { uri: request.uri, model: request.model, basedOn: request.basedOn };
730
+ }
731
+
732
+ /**
733
+ * The session this connection registered under `clientId`, which every
734
+ * document request acts as. An id that is not one fails with the
735
+ * closed-session code: opening or writing under it would leave an open that
736
+ * no session end ever closes.
737
+ */
738
+ protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer> {
739
+ const session = this.clientSessions.get(clientId);
740
+ if (!session) {
741
+ throw new SessionClosedError(clientId, `Client session ${clientId} was never registered on this connection`);
578
742
  }
743
+ return session;
744
+ }
745
+
746
+ async openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
747
+ const session = this.requireSession(args.clientId);
748
+ const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
749
+ await session.open(args.uri, args.options);
750
+ // A repeat open keeps the earlier one, which is still in use.
751
+ return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
579
752
  }
580
753
 
581
754
  /**
582
- * Close every document still open over this connection, for the clients that
583
- * opened it here.
584
- *
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.
755
+ * The snapshot a session's open or create answers with. When the read
756
+ * fails, `rollback` undoes the open this call made before the failure is
757
+ * rethrown: the caller sees no open, so nothing on its side would ever close
758
+ * it.
591
759
  *
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.
760
+ * Versioned with the store's shared version rather than the snapshot's own:
761
+ * the built document's `textDocument.version` lags the store's whenever the
762
+ * store assigned the version, and the store's is what a write's `basedOn` is
763
+ * compared against, so reporting the snapshot's would make the caller's
764
+ * first based-on write conflict with itself.
595
765
  */
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
- }
766
+ protected async openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
767
+ let document: TransferDocument<TTransfer, TDiagnostic>;
768
+ try {
769
+ document = await this.getModelDocument({ uri });
770
+ } catch (error: unknown) {
771
+ // The open's failure is the one the caller needs, not the cleanup's.
772
+ await rollback?.().catch(() => undefined);
773
+ throw error;
603
774
  }
775
+ return { ...document, version: asSnapshotVersion(this.services.workspace.TextDocuments.version(uri)) };
776
+ }
777
+
778
+ async closeModelDocument(args: CloseModelArgs): Promise<void> {
779
+ // Through the handle, so a close under an ended session fails as that
780
+ // session's calls do, and a session class's own close is honoured.
781
+ const session = this.requireSession(args.clientId);
782
+ // Closing also releases the watch for (uri, clientId) — a forgotten
783
+ // unwatch would otherwise leak phase-event dispatch until the connection
784
+ // closes. Idempotent: a close without a prior watch is a no-op.
785
+ await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
786
+ await session.close(args.uri);
604
787
  }
605
788
 
606
789
  async getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
@@ -620,12 +803,12 @@ export class DataServer<
620
803
  }
621
804
 
622
805
  async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
623
- const astDocument = await this.modelService.update(args);
806
+ const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
624
807
  return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
625
808
  }
626
809
 
627
810
  async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
628
- const astDocument = await this.modelService.save(args);
811
+ const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
629
812
  return this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>;
630
813
  }
631
814
 
@@ -734,21 +917,59 @@ export class DataServer<
734
917
  // (see resolveReferenceServices) and delegate.
735
918
  // ============================================================
736
919
 
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;
920
+ /**
921
+ * Settle the build before a reference question is answered from the index.
922
+ *
923
+ * A query issued right after a model update otherwise races the rebuild and
924
+ * reads an index missing the symbols it asks about. The cost is not confined
925
+ * to this call: a scope built inside that window is cached, and the build's
926
+ * remaining documents link against it.
927
+ *
928
+ * Waits the source document specifically, but ONLY when one is loaded at
929
+ * that URI: a synthetic source can address a URI with no document (a
930
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
931
+ * found". Falls back to a global settle, matching the id-based
932
+ * `ElementSource` path.
933
+ *
934
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
935
+ */
936
+ protected async awaitReferencesLinked(source: ReferenceSource): Promise<void> {
937
+ const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
746
938
  const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
747
- await this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
939
+ const stopwatch = this.services.Clock.stopwatch();
940
+ let timer: Disposable | undefined;
941
+ const timeout = new Promise<void>((resolve, reject) => {
942
+ timer = this.services.Clock.setTimer(() => {
943
+ const elapsedMs = Math.round(stopwatch.elapsedMs);
944
+ // A per-URI wait resolves off a document-phase notification, so a
945
+ // missed one strands a wait on a document that HAS reached the
946
+ // phase. Re-read before failing; the workspace-wide wait has no
947
+ // equivalent reading and can only reject.
948
+ const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
949
+ if (waitUri && document && document.state >= DocumentState.Linked) {
950
+ this.tracer
951
+ .withUri(waitUri.toString())
952
+ .warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
953
+ resolve();
954
+ return;
955
+ }
956
+ reject(referenceSettleTimeoutError(elapsedMs));
957
+ }, this.options.referenceSettleTimeoutMs);
958
+ });
959
+ try {
960
+ await Promise.race([this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri), timeout]);
961
+ } finally {
962
+ timer?.dispose();
963
+ }
964
+ }
965
+
966
+ async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
967
+ await this.awaitReferencesLinked(ctx.source);
748
968
  return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
749
969
  }
750
970
 
751
971
  async resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined> {
972
+ await this.awaitReferencesLinked(ref.source);
752
973
  const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
753
974
  if (!resolved) {
754
975
  return undefined;
@@ -764,7 +985,14 @@ export class DataServer<
764
985
  // synthetic source — and the create-element flow driving this method is
765
986
  // the one that produces directory URIs, on which a bare
766
987
  // `getServices(uri)` throws while `findReferenceCandidates` succeeds.
767
- const nameProvider = this.resolveReferenceServices(ReferenceSource.synthetic(args.uri, args.type)).NameProvider;
988
+ const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
989
+ // Mid-rebuild the names of documents not yet re-indexed are absent from
990
+ // the taken set, and the caller PERSISTS what it is handed. Nothing
991
+ // reserves the answer either, so a name is free of the collisions the
992
+ // index knows about and of nothing else — two callers racing get the same
993
+ // proposal, which only uniqueness at the write can catch.
994
+ await this.awaitReferencesLinked(source);
995
+ const nameProvider = this.resolveReferenceServices(source).NameProvider;
768
996
  const tier = args.tier ?? 'project';
769
997
  if (tier === 'public') {
770
998
  return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
@@ -811,6 +1039,9 @@ export class DataServer<
811
1039
  /**
812
1040
  * Pick the language that owns a reference source, in order:
813
1041
  *
1042
+ * 0. A {@link isSyntheticSource} naming its own `language` routes there.
1043
+ * First because every step below infers, and an inference must not
1044
+ * override a caller that has said which grammar it means.
814
1045
  * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
815
1046
  * whose URI resolves to a registered language routes by URI.
816
1047
  * 2. A single-language workspace always routes to that one language — so
@@ -829,6 +1060,15 @@ export class DataServer<
829
1060
  */
830
1061
  protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined {
831
1062
  const registry = this.services.ServiceRegistry;
1063
+ if (isSyntheticSource(source) && source.language !== undefined) {
1064
+ const declared = registry.getServicesById(source.language);
1065
+ if (declared) {
1066
+ return declared;
1067
+ }
1068
+ // Falling through on an UNREGISTERED id rather than failing: the id
1069
+ // crosses the wire, so a client built against a head with one more
1070
+ // grammar would otherwise lose queries the steps below can answer.
1071
+ }
832
1072
  // `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
833
1073
  // an extensionless / unregistered URI falls through to the steps below
834
1074
  // rather than throwing "no services for the extension ''".
@@ -945,14 +1185,9 @@ export class DataServer<
945
1185
  // decides policy at its own layer; `root` is optional on the envelope
946
1186
  // so the compiler forces that decision. Adopters preferring to throw
947
1187
  // override `envelope`.
948
- return {
949
- uri: uri.toString(),
950
- version: 0,
951
- root: undefined,
952
- diagnostics: [] as TDiagnostic[]
953
- };
1188
+ return TransferDocument.absent<TTransfer, TDiagnostic>(uri.toString());
954
1189
  }
955
- return this.encoder.toTransferDocument<AstNode>(document) as unknown as TransferDocument<TTransfer, TDiagnostic>;
1190
+ return this.encoder.toTransferDocument(document) as unknown as TransferDocument<TTransfer, TDiagnostic>;
956
1191
  }
957
1192
 
958
1193
  /**
@@ -967,6 +1202,57 @@ export class DataServer<
967
1202
  this.dispatchPhaseEvent(document, cancelToken)
968
1203
  )
969
1204
  );
1205
+ // The BUILD-phase hook, not the per-document one: this notification is one
1206
+ // message per build rather than one per document, and Langium hands the
1207
+ // whole batch over here. It also does not fire for a cancelled build,
1208
+ // which is what the per-document dispatch has to check by hand.
1209
+ this.disposables.push(
1210
+ this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built))
1211
+ );
1212
+ }
1213
+
1214
+ /**
1215
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
1216
+ * and that NOBODY on this
1217
+ * connection is watching — the ones a client was not told about through
1218
+ * {@link dispatchPhaseEvent}, which is gated per URI.
1219
+ *
1220
+ * **The gap this closes is the one no other source can observe.** A document
1221
+ * the client watches, it hears about already. A file changed on disk, the
1222
+ * host's own filesystem watcher reports — and on a browser host, where the
1223
+ * workspace lives behind this head, an external change cannot happen at all.
1224
+ * What is left, and what nothing outside the server can see, is a document
1225
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
1226
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
1227
+ * the update channel is silent by design. A consumer displaying data derived
1228
+ * from that document — a tree label, a decorator — otherwise goes stale with
1229
+ * no signal from any source, and repairs itself the moment someone opens the
1230
+ * file to investigate, which is what makes it expensive to diagnose later.
1231
+ *
1232
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
1233
+ * rather than being handed transfer documents it did not ask for. That is the
1234
+ * property the subscription map protects, and it is preserved here by
1235
+ * carrying no document rather than by gating the message.
1236
+ *
1237
+ * Quiet in the common case. Editing a document that an editor has open leaves
1238
+ * that URI watched and therefore out of this set, so a build with no
1239
+ * dependents produces nothing at all, and workspace initialisation produces
1240
+ * nothing because it does not build to this phase. The ceiling is a
1241
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
1242
+ *
1243
+ * The URI is canonicalised for the same reason the subscription map is keyed
1244
+ * that way, and is untested for the same reason as its twin in
1245
+ * {@link dispatchDeleteEvents}: the builder reports URIs out of its own
1246
+ * store, so a non-canonical one cannot be produced without a fixture
1247
+ * asserting a shape the real system never emits.
1248
+ */
1249
+ protected dispatchBuiltEvent(built: readonly LangiumDocument[]): void {
1250
+ const uris = built.map(document => this.canonicalKey(document.uri.toString())).filter(uri => !this.subscriptions.has(uri));
1251
+ if (uris.length === 0) {
1252
+ return;
1253
+ }
1254
+ this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
1255
+ this.clientProxy.onDocumentsBuilt({ uris });
970
1256
  }
971
1257
 
972
1258
  /**
@@ -988,22 +1274,71 @@ export class DataServer<
988
1274
  }
989
1275
 
990
1276
  /**
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.
1277
+ * Mark each document the store releases after its last close (see
1278
+ * {@link pendingRevertBroadcasts}). A release, not the close itself: a
1279
+ * document whose last client lost its connection is released only once
1280
+ * the revert grace runs out, or when another client opens it meanwhile, and
1281
+ * not at all when a client lost from it opens it again within its own
1282
+ * grace.
995
1283
  */
996
1284
  protected subscribeToTextDocumentCloses(): void {
997
- const textDocuments = this.services.workspace.TextDocuments;
998
1285
  this.disposables.push(
999
- textDocuments.onDidClose(event => {
1000
- if (!textDocuments.isOpenInAnyClient(event.document.uri)) {
1001
- this.pendingRevertBroadcasts.add(this.canonicalKey(event.document.uri));
1002
- }
1286
+ this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
1287
+ this.pendingRevertBroadcasts.add(this.canonicalKey(event.uri));
1003
1288
  })
1004
1289
  );
1005
1290
  }
1006
1291
 
1292
+ /**
1293
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
1294
+ * rather than only to the ones watching that URI.
1295
+ *
1296
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
1297
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
1298
+ * fire on every build, so the subscription map is what keeps bandwidth
1299
+ * proportional to what a client asked for. A deletion is neither: it is one
1300
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
1301
+ * document's content. Gating it forces any consumer that displays the
1302
+ * workspace — a model tree, a file decorator — to learn about disappearances
1303
+ * from a filesystem watcher instead, which a client hosted in a browser has
1304
+ * no way to run: its workspace lives behind the head. A client that does not
1305
+ * care filters on the URI, which costs it a comparison.
1306
+ *
1307
+ * The precedent is the last-close revert broadcast (see
1308
+ * {@link pendingRevertBroadcasts}), where the same judgement was already made
1309
+ * in the other direction: a transition that matters enough is delivered
1310
+ * without a subscription.
1311
+ *
1312
+ * Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
1313
+ * listener, which is the only place a deletion is observable: `update`
1314
+ * removes the document before deriving the rebuild set, so it is never built.
1315
+ * That ordering also puts this notification ahead of the `'rebuilt'` events
1316
+ * for the dependents whose references the deletion just broke.
1317
+ *
1318
+ * The `deleted` list arrives already expanded to concrete document URIs —
1319
+ * `deleteDocuments` resolves a directory URI to the documents beneath it — so
1320
+ * no caller has to handle a directory here.
1321
+ *
1322
+ * Per-URI derived state is dropped for the same reason it is dropped
1323
+ * anywhere: it describes a document that no longer exists.
1324
+ * {@link lastEmittedFingerprint} in particular can outlive its subscriptions
1325
+ * through the last-close revert path — left behind, it is adopted as the
1326
+ * baseline by the next {@link watchModelDocument} and suppresses the first
1327
+ * emit after the file returns with its previous content.
1328
+ *
1329
+ * The subscription itself SURVIVES: a recreated file resumes delivering to
1330
+ * the same watchers with no re-subscription, and a client that answers the
1331
+ * deletion by closing releases the watch through `closeModelDocument` anyway.
1332
+ */
1333
+ protected dispatchDeleteEvents(deleted: readonly URI[]): void {
1334
+ for (const removed of deleted) {
1335
+ const uri = this.canonicalKey(removed.toString());
1336
+ this.lastEmittedFingerprint.delete(uri);
1337
+ this.pendingRevertBroadcasts.delete(uri);
1338
+ this.clientProxy.onDocumentDeleted({ uri });
1339
+ }
1340
+ }
1341
+
1007
1342
  /** Fan out a save event for the document's URI, gated by the subscription map. */
1008
1343
  protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void {
1009
1344
  // The save event arrives under the CLIENT URI the text store keys by (e.g. a
@@ -1122,26 +1457,19 @@ export class DataServer<
1122
1457
  /**
1123
1458
  * Discriminate the reason for a phase-event-driven update notification.
1124
1459
  * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
1125
- * - URI in the `deleted` list → `'deleted'`
1126
1460
  * - URI in the `changed` list → `'changed'` (the URI was passed to
1127
1461
  * `documentBuilder.update(changed, deleted)`, which spans `didChange`
1128
1462
  * text-document events and programmatic `update([uri], [])` calls).
1129
1463
  * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
1130
1464
  * because something it depends on changed; its own text wasn't flagged).
1131
1465
  *
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.
1466
+ * `'saved'` is NOT emitted here — saves take the dedicated
1467
+ * `DataClientProtocol.onDocumentSaved` channel, and adopters wanting a
1468
+ * unified stream synthesise it in their bridge layer. A deletion is not a
1469
+ * reason at all; see {@link dispatchDeleteEvents}.
1135
1470
  */
1136
1471
  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';
1472
+ return this.lastBuildUpdate?.changed.some(changed => UriUtils.equals(changed, uri)) ? 'changed' : 'rebuilt';
1145
1473
  }
1146
1474
 
1147
1475
  /**
@@ -1243,7 +1571,7 @@ export class DataServer<
1243
1571
 
1244
1572
  async stopProfiling(args: StopProfilingArgs): Promise<string> {
1245
1573
  if (!this.activeProfile) {
1246
- throw new Error('No profiling capture is active; call startProfiling first.');
1574
+ throw noActiveProfileError();
1247
1575
  }
1248
1576
  const capture = this.activeProfile;
1249
1577
  this.activeProfile = undefined;
@@ -1276,7 +1604,8 @@ export class DataServer<
1276
1604
  methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
1277
1605
  additionalMethods,
1278
1606
  excludedMethods: partial.excludedMethods ?? [],
1279
- diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
1607
+ diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
1608
+ referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
1280
1609
  };
1281
1610
  }
1282
1611
  }