@hydranium/data-server 1.0.0-next.12 → 1.0.0-next.127
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/lib/data-server.d.ts +285 -74
- package/lib/data-server.d.ts.map +1 -1
- package/lib/data-server.js +430 -153
- package/lib/data-server.js.map +1 -1
- package/lib/messages/index.d.ts +18 -0
- package/lib/messages/index.d.ts.map +1 -0
- package/lib/messages/index.js +18 -0
- package/lib/messages/index.js.map +1 -0
- package/lib/testing/data-server-harness.d.ts +7 -1
- package/lib/testing/data-server-harness.d.ts.map +1 -1
- package/lib/testing/data-server-harness.js +5 -2
- package/lib/testing/data-server-harness.js.map +1 -1
- package/package.json +17 -8
- package/src/data-server.ts +526 -165
- package/src/messages/index.ts +19 -0
- package/src/testing/data-server-harness.ts +16 -1
package/src/data-server.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
*
|
|
263
|
-
*
|
|
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
|
-
/**
|
|
269
|
-
|
|
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
|
|
305
|
-
* `DocumentBuilder.onDocumentPhase`
|
|
306
|
-
*
|
|
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
|
-
*
|
|
343
|
-
*
|
|
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
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
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
|
|
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'`,
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
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
|
|
403
|
-
* document from its disk content (discarding unsaved
|
|
404
|
-
* but {@link dispatchPhaseEvent} gates on the
|
|
405
|
-
* last close typically also removed the last
|
|
406
|
-
* only ever fetch via `getModelDocument` would
|
|
407
|
-
* discarded state forever. Marked on the
|
|
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,7 +514,7 @@ 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<
|
|
517
|
+
protected readonly encoder: TransferEncoder<TDiagnostic>;
|
|
424
518
|
/**
|
|
425
519
|
* In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
|
|
426
520
|
* The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
|
|
@@ -429,7 +523,7 @@ export class DataServer<
|
|
|
429
523
|
* `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
|
|
430
524
|
* to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
|
|
431
525
|
*/
|
|
432
|
-
protected readonly modelService: ModelService<AstNode,
|
|
526
|
+
protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
|
|
433
527
|
|
|
434
528
|
constructor(
|
|
435
529
|
protected readonly connection: MessageConnection,
|
|
@@ -448,8 +542,8 @@ export class DataServer<
|
|
|
448
542
|
'Did you compose `createServerSharedModule(ctx)` into your shared module?'
|
|
449
543
|
);
|
|
450
544
|
}
|
|
451
|
-
this.encoder = encoder as TransferEncoder<
|
|
452
|
-
this.modelService = modelService as ModelService<AstNode,
|
|
545
|
+
this.encoder = encoder as TransferEncoder<TDiagnostic>;
|
|
546
|
+
this.modelService = modelService as ModelService<AstNode, AstDiagnostic, TTransfer>;
|
|
453
547
|
const excluded = new Set<string>(this.options.excludedMethods);
|
|
454
548
|
const registeredMethods = [
|
|
455
549
|
...DATA_SERVER_PROTOCOL_METHODS,
|
|
@@ -465,21 +559,29 @@ export class DataServer<
|
|
|
465
559
|
methodNamespace: this.options.methodNamespace,
|
|
466
560
|
localTarget: this,
|
|
467
561
|
localMethods: registeredMethods as readonly (keyof this & string)[],
|
|
468
|
-
latency: this.latency
|
|
562
|
+
latency: this.latency,
|
|
563
|
+
// Bound at the chokepoint rather than per handler, so an adopter's
|
|
564
|
+
// `additionalMethods` are rendered on the same terms as the
|
|
565
|
+
// framework's own rejections.
|
|
566
|
+
renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
|
|
469
567
|
});
|
|
470
568
|
this.disposables.push(
|
|
471
569
|
this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
|
|
472
570
|
this.lastBuildUpdate = { changed, deleted };
|
|
571
|
+
this.dispatchDeleteEvents(deleted);
|
|
473
572
|
})
|
|
474
573
|
);
|
|
475
574
|
this.subscribeToDocumentBuilder();
|
|
476
575
|
this.subscribeToTextDocumentSaves();
|
|
576
|
+
this.subscribeToDirtyChanges();
|
|
477
577
|
this.subscribeToTextDocumentCloses();
|
|
478
578
|
this.subscribeToProjectManager();
|
|
479
579
|
// Self-register teardown so an adopter that keeps no reference to the
|
|
480
580
|
// server still releases per-connection state, with no lifecycle hook of
|
|
481
|
-
// its own.
|
|
482
|
-
|
|
581
|
+
// its own. The client did not close anything itself, so its sessions end
|
|
582
|
+
// as lost and each document it was the last to have open waits out the
|
|
583
|
+
// store's revert grace. See `dispose`.
|
|
584
|
+
this.disposables.push(connection.onClose(() => this.dispose('lost')));
|
|
483
585
|
}
|
|
484
586
|
|
|
485
587
|
/**
|
|
@@ -487,16 +589,19 @@ export class DataServer<
|
|
|
487
589
|
* handlers and every listener — and clear the subscription map and the
|
|
488
590
|
* per-URI emission-fingerprint cache, so a long-lived shared services
|
|
489
591
|
* bundle does not retain per-connection memory after the connection
|
|
490
|
-
* closes. Also
|
|
491
|
-
*
|
|
492
|
-
*
|
|
592
|
+
* closes. Also ends every session this connection registered, which closes
|
|
593
|
+
* every document it has open: the SHARED store's state rather than this
|
|
594
|
+
* server's, which outlives the connection unless released here.
|
|
493
595
|
*
|
|
494
|
-
* Idempotent: subsequent calls are no-ops.
|
|
495
|
-
*
|
|
496
|
-
*
|
|
497
|
-
*
|
|
596
|
+
* Idempotent: subsequent calls are no-ops. Runs by itself when the
|
|
597
|
+
* connection closes, so adopters who don't hold a reference still get
|
|
598
|
+
* per-connection cleanup; adopters that DO hold a reference may call
|
|
599
|
+
* `dispose()` directly for early teardown. The sessions end with `cause`:
|
|
600
|
+
* `'closed'` reverts every document whose last open they close at once,
|
|
601
|
+
* and `'lost'`, the connection's own close, lets each wait out the revert
|
|
602
|
+
* grace.
|
|
498
603
|
*/
|
|
499
|
-
dispose(): void {
|
|
604
|
+
dispose(cause: SessionEndCause = 'closed'): void {
|
|
500
605
|
this.disposed = true;
|
|
501
606
|
// Release an in-flight interactive capture so the process-wide inspector
|
|
502
607
|
// singleton is not left active after the connection closes.
|
|
@@ -505,102 +610,181 @@ export class DataServer<
|
|
|
505
610
|
this.activeProfile = undefined;
|
|
506
611
|
void capture.stop({}).catch(() => undefined);
|
|
507
612
|
}
|
|
508
|
-
// AFTER `disposables.dispose()`, deliberately:
|
|
509
|
-
//
|
|
510
|
-
//
|
|
613
|
+
// AFTER `disposables.dispose()`, deliberately: ending a session releases
|
|
614
|
+
// each document it was the last to hold, and this server's own
|
|
615
|
+
// `onDidCloseLastOpen` listener would otherwise mark a revert broadcast
|
|
616
|
+
// for a connection that is already gone.
|
|
511
617
|
this.disposables.dispose();
|
|
512
|
-
this.
|
|
618
|
+
for (const [clientId, session] of this.clientSessions) {
|
|
619
|
+
this.endSession(clientId, session, cause);
|
|
620
|
+
}
|
|
513
621
|
this.subscriptions.clear();
|
|
514
622
|
this.lastEmittedFingerprint.clear();
|
|
515
623
|
this.pendingRevertBroadcasts.clear();
|
|
516
624
|
}
|
|
517
625
|
|
|
518
626
|
// ============================================================
|
|
519
|
-
// DataServerProtocol implementation
|
|
627
|
+
// DataServerProtocol implementation
|
|
520
628
|
// ============================================================
|
|
521
629
|
//
|
|
522
|
-
//
|
|
523
|
-
//
|
|
524
|
-
// the wire boundary via
|
|
525
|
-
//
|
|
526
|
-
//
|
|
527
|
-
//
|
|
528
|
-
|
|
529
|
-
async
|
|
530
|
-
//
|
|
531
|
-
//
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
630
|
+
// Reads go to `ModelService`; a request that opens or writes a document
|
|
631
|
+
// goes to the session this connection registered under its `clientId`.
|
|
632
|
+
// Each answer is encoded on the wire boundary via
|
|
633
|
+
// `encoder.astDocumentToTransferDocument`. To change how documents are
|
|
634
|
+
// read, override on the ModelService subclass; to change how they are
|
|
635
|
+
// written, on the session class the bound `ClientSessionFactory` builds.
|
|
636
|
+
|
|
637
|
+
async createSession(args: CreateSessionArgs): Promise<void> {
|
|
638
|
+
// After teardown nothing would ever end a session registered now, and its
|
|
639
|
+
// id would stay taken for the life of the process.
|
|
640
|
+
if (this.disposed) {
|
|
641
|
+
throw new SessionClosedError(args.clientId);
|
|
642
|
+
}
|
|
643
|
+
const resumable = this.resumableSessions();
|
|
644
|
+
const previous = resumable.get(args.clientId);
|
|
645
|
+
if (previous && args.resumeToken !== undefined && previous.token === args.resumeToken) {
|
|
646
|
+
previous.end();
|
|
647
|
+
}
|
|
648
|
+
const session = this.modelService.createSession(args.label, args.clientId);
|
|
649
|
+
this.clientSessions.set(args.clientId, session);
|
|
650
|
+
if (args.resumeToken !== undefined) {
|
|
651
|
+
// Taken over by a client registering again after its connection
|
|
652
|
+
// dropped, so the old session ends as lost: the documents it was the
|
|
653
|
+
// last to have open wait out the grace, and the new session's opens
|
|
654
|
+
// find their unsaved text.
|
|
655
|
+
resumable.set(args.clientId, { token: args.resumeToken, end: () => this.endSession(args.clientId, session, 'lost') });
|
|
541
656
|
}
|
|
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
657
|
}
|
|
556
658
|
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
659
|
+
/**
|
|
660
|
+
* End a session this connection registered. The ended handle stays in
|
|
661
|
+
* {@link clientSessions}, as it does after {@link dispose}, so a request for
|
|
662
|
+
* the id still arriving fails with the ended session's own error.
|
|
663
|
+
*/
|
|
664
|
+
async closeSession(args: CloseSessionArgs): Promise<void> {
|
|
665
|
+
const session = this.clientSessions.get(args.clientId);
|
|
666
|
+
if (session) {
|
|
667
|
+
this.endSession(args.clientId, session);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
|
|
672
|
+
protected endSession(
|
|
673
|
+
clientId: string,
|
|
674
|
+
session: ClientSession<AstNode, AstDiagnostic, TTransfer>,
|
|
675
|
+
cause: SessionEndCause = 'closed'
|
|
676
|
+
): void {
|
|
677
|
+
for (const [uri, watchers] of this.subscriptions) {
|
|
678
|
+
if (watchers.delete(clientId) && watchers.size === 0) {
|
|
679
|
+
this.subscriptions.delete(uri);
|
|
680
|
+
this.lastEmittedFingerprint.delete(uri);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
session.dispose(cause);
|
|
564
684
|
}
|
|
565
685
|
|
|
566
686
|
/**
|
|
567
|
-
*
|
|
568
|
-
*
|
|
687
|
+
* The resumable sessions of this services tree, by client id, across all of
|
|
688
|
+
* its data connections: a client resumes on another connection than the one
|
|
689
|
+
* that registered it. An entry leaves when its session ends, by any path, so
|
|
690
|
+
* it keeps no ended connection alive.
|
|
691
|
+
*
|
|
692
|
+
* A takeover by resume token ends the old session even when its connection
|
|
693
|
+
* is still alive, so two clients that shared an id and its token would end
|
|
694
|
+
* each other's sessions. And the token is a guard against colliding with a
|
|
695
|
+
* session the server has not yet seen end, not a secret: the wire carries no
|
|
696
|
+
* authentication, and a peer that learns the token can end the session.
|
|
569
697
|
*/
|
|
570
|
-
protected
|
|
571
|
-
|
|
572
|
-
if (!
|
|
573
|
-
|
|
698
|
+
protected resumableSessions(): Map<string, ResumableSession> {
|
|
699
|
+
let sessions = resumableByModelService.get(this.modelService);
|
|
700
|
+
if (!sessions) {
|
|
701
|
+
const created = new Map<string, ResumableSession>();
|
|
702
|
+
// Subscribed once per services tree, and never disposed: it lives as
|
|
703
|
+
// long as the text store it listens to.
|
|
704
|
+
this.services.workspace.TextDocuments.onDidCloseSession(event => created.delete(event.clientId));
|
|
705
|
+
resumableByModelService.set(this.modelService, created);
|
|
706
|
+
sessions = created;
|
|
574
707
|
}
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
708
|
+
return sessions;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
async createModelDocument(args: CreateModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
712
|
+
const session = this.requireSession(args.clientId);
|
|
713
|
+
await session.create(args.uri, args.text);
|
|
714
|
+
return this.openedSnapshot(args.uri, () => session.close(args.uri));
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
async updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>[]> {
|
|
718
|
+
const astDocuments = await this.requireSession(args.clientId).updateAll({
|
|
719
|
+
updates: args.updates.map(update => this.toSessionWrite(update))
|
|
720
|
+
});
|
|
721
|
+
return astDocuments.map(astDocument => this.encodeDocument(astDocument));
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* The session write a wire write request carries. Only the fields a session
|
|
726
|
+
* takes: a field an adopter adds to a request reaches the session only
|
|
727
|
+
* through an override of this.
|
|
728
|
+
*/
|
|
729
|
+
protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer> {
|
|
730
|
+
return { uri: request.uri, model: request.model, basedOn: request.basedOn };
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* The session this connection registered under `clientId`, which every
|
|
735
|
+
* document request acts as. An id that is not one fails with the
|
|
736
|
+
* closed-session code: opening or writing under it would leave an open that
|
|
737
|
+
* no session end ever closes.
|
|
738
|
+
*/
|
|
739
|
+
protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer> {
|
|
740
|
+
const session = this.clientSessions.get(clientId);
|
|
741
|
+
if (!session) {
|
|
742
|
+
throw new SessionClosedError(clientId, 'The client session was never registered on this connection.');
|
|
578
743
|
}
|
|
744
|
+
return session;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
async openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
748
|
+
const session = this.requireSession(args.clientId);
|
|
749
|
+
const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
|
|
750
|
+
await session.open(args.uri, args.options);
|
|
751
|
+
// A repeat open keeps the earlier one, which is still in use.
|
|
752
|
+
return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
|
|
579
753
|
}
|
|
580
754
|
|
|
581
755
|
/**
|
|
582
|
-
*
|
|
583
|
-
*
|
|
756
|
+
* The snapshot a session's open or create answers with. When the read
|
|
757
|
+
* fails, `rollback` undoes the open this call made before the failure is
|
|
758
|
+
* rethrown: the caller sees no open, so nothing on its side would ever close
|
|
759
|
+
* it.
|
|
584
760
|
*
|
|
585
|
-
*
|
|
586
|
-
*
|
|
587
|
-
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
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.
|
|
761
|
+
* Versioned with the store's shared version rather than the snapshot's own:
|
|
762
|
+
* the built document's `textDocument.version` lags the store's whenever the
|
|
763
|
+
* store assigned the version, and the store's is what a write's `basedOn` is
|
|
764
|
+
* compared against, so reporting the snapshot's would make the caller's
|
|
765
|
+
* first based-on write conflict with itself.
|
|
595
766
|
*/
|
|
596
|
-
protected
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
767
|
+
protected async openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
768
|
+
let document: TransferDocument<TTransfer, TDiagnostic>;
|
|
769
|
+
try {
|
|
770
|
+
document = await this.getModelDocument({ uri });
|
|
771
|
+
} catch (error: unknown) {
|
|
772
|
+
// The open's failure is the one the caller needs, not the cleanup's.
|
|
773
|
+
await rollback?.().catch(() => undefined);
|
|
774
|
+
throw error;
|
|
603
775
|
}
|
|
776
|
+
return { ...document, version: asSnapshotVersion(this.services.workspace.TextDocuments.version(uri)) };
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
async closeModelDocument(args: CloseModelArgs): Promise<void> {
|
|
780
|
+
// Through the handle, so a close under an ended session fails as that
|
|
781
|
+
// session's calls do, and a session class's own close is honoured.
|
|
782
|
+
const session = this.requireSession(args.clientId);
|
|
783
|
+
// Closing also releases the watch for (uri, clientId) — a forgotten
|
|
784
|
+
// unwatch would otherwise leak phase-event dispatch until the connection
|
|
785
|
+
// closes. Idempotent: a close without a prior watch is a no-op.
|
|
786
|
+
await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
|
|
787
|
+
await session.close(args.uri);
|
|
604
788
|
}
|
|
605
789
|
|
|
606
790
|
async getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
@@ -616,17 +800,17 @@ export class DataServer<
|
|
|
616
800
|
// `includeDiagnostics: true` to settle at `Validated` instead.
|
|
617
801
|
const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
|
|
618
802
|
const astDocument = await this.modelService.ensureDocumentState(args.uri, state);
|
|
619
|
-
return this.
|
|
803
|
+
return this.encodeDocument(astDocument);
|
|
620
804
|
}
|
|
621
805
|
|
|
622
806
|
async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
623
|
-
const astDocument = await this.
|
|
624
|
-
return this.
|
|
807
|
+
const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
|
|
808
|
+
return this.encodeDocument(astDocument);
|
|
625
809
|
}
|
|
626
810
|
|
|
627
811
|
async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
628
|
-
const astDocument = await this.
|
|
629
|
-
return this.
|
|
812
|
+
const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
|
|
813
|
+
return this.encodeDocument(astDocument);
|
|
630
814
|
}
|
|
631
815
|
|
|
632
816
|
/**
|
|
@@ -734,21 +918,52 @@ export class DataServer<
|
|
|
734
918
|
// (see resolveReferenceServices) and delegate.
|
|
735
919
|
// ============================================================
|
|
736
920
|
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
921
|
+
/**
|
|
922
|
+
* Settle the build before a reference question is answered from the index.
|
|
923
|
+
*
|
|
924
|
+
* A query issued right after a model update otherwise races the rebuild and
|
|
925
|
+
* reads an index missing the symbols it asks about. The cost is not confined
|
|
926
|
+
* to this call: a scope built inside that window is cached, and the build's
|
|
927
|
+
* remaining documents link against it.
|
|
928
|
+
*
|
|
929
|
+
* Waits the source document specifically, but ONLY when one is loaded at
|
|
930
|
+
* that URI: a synthetic source can address a URI with no document (a
|
|
931
|
+
* directory URI, typically), where a per-URI `waitUntil` throws "No document
|
|
932
|
+
* found". Falls back to a global settle, matching the id-based
|
|
933
|
+
* `ElementSource` path.
|
|
934
|
+
*
|
|
935
|
+
* Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
936
|
+
*/
|
|
937
|
+
protected async awaitReferencesLinked(source: ReferenceSource): Promise<void> {
|
|
938
|
+
const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
|
|
746
939
|
const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
|
|
747
|
-
|
|
940
|
+
const stopwatch = this.services.Clock.stopwatch();
|
|
941
|
+
const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
|
|
942
|
+
if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
const elapsedMs = Math.round(stopwatch.elapsedMs);
|
|
946
|
+
// A per-URI wait resolves off a document-phase notification, so a
|
|
947
|
+
// missed one strands a wait on a document that HAS reached the
|
|
948
|
+
// phase. Re-read before failing; the workspace-wide wait has no
|
|
949
|
+
// equivalent reading and can only reject.
|
|
950
|
+
const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
|
|
951
|
+
if (waitUri && document && document.state >= DocumentState.Linked) {
|
|
952
|
+
this.tracer
|
|
953
|
+
.withUri(waitUri.toString())
|
|
954
|
+
.warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
throw referenceSettleTimeoutError(elapsedMs);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
|
|
961
|
+
await this.awaitReferencesLinked(ctx.source);
|
|
748
962
|
return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
|
|
749
963
|
}
|
|
750
964
|
|
|
751
965
|
async resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined> {
|
|
966
|
+
await this.awaitReferencesLinked(ref.source);
|
|
752
967
|
const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
|
|
753
968
|
if (!resolved) {
|
|
754
969
|
return undefined;
|
|
@@ -764,7 +979,14 @@ export class DataServer<
|
|
|
764
979
|
// synthetic source — and the create-element flow driving this method is
|
|
765
980
|
// the one that produces directory URIs, on which a bare
|
|
766
981
|
// `getServices(uri)` throws while `findReferenceCandidates` succeeds.
|
|
767
|
-
const
|
|
982
|
+
const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
|
|
983
|
+
// Mid-rebuild the names of documents not yet re-indexed are absent from
|
|
984
|
+
// the taken set, and the caller PERSISTS what it is handed. Nothing
|
|
985
|
+
// reserves the answer either, so a name is free of the collisions the
|
|
986
|
+
// index knows about and of nothing else — two callers racing get the same
|
|
987
|
+
// proposal, which only uniqueness at the write can catch.
|
|
988
|
+
await this.awaitReferencesLinked(source);
|
|
989
|
+
const nameProvider = this.resolveReferenceServices(source).NameProvider;
|
|
768
990
|
const tier = args.tier ?? 'project';
|
|
769
991
|
if (tier === 'public') {
|
|
770
992
|
return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
|
|
@@ -811,6 +1033,9 @@ export class DataServer<
|
|
|
811
1033
|
/**
|
|
812
1034
|
* Pick the language that owns a reference source, in order:
|
|
813
1035
|
*
|
|
1036
|
+
* 0. A {@link isSyntheticSource} naming its own `language` routes there.
|
|
1037
|
+
* First because every step below infers, and an inference must not
|
|
1038
|
+
* override a caller that has said which grammar it means.
|
|
814
1039
|
* 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
|
|
815
1040
|
* whose URI resolves to a registered language routes by URI.
|
|
816
1041
|
* 2. A single-language workspace always routes to that one language — so
|
|
@@ -829,6 +1054,15 @@ export class DataServer<
|
|
|
829
1054
|
*/
|
|
830
1055
|
protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined {
|
|
831
1056
|
const registry = this.services.ServiceRegistry;
|
|
1057
|
+
if (isSyntheticSource(source) && source.language !== undefined) {
|
|
1058
|
+
const declared = registry.getServicesById(source.language);
|
|
1059
|
+
if (declared) {
|
|
1060
|
+
return declared;
|
|
1061
|
+
}
|
|
1062
|
+
// Falling through on an UNREGISTERED id rather than failing: the id
|
|
1063
|
+
// crosses the wire, so a client built against a head with one more
|
|
1064
|
+
// grammar would otherwise lose queries the steps below can answer.
|
|
1065
|
+
}
|
|
832
1066
|
// `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
|
|
833
1067
|
// an extensionless / unregistered URI falls through to the steps below
|
|
834
1068
|
// rather than throwing "no services for the extension ''".
|
|
@@ -945,14 +1179,30 @@ export class DataServer<
|
|
|
945
1179
|
// decides policy at its own layer; `root` is optional on the envelope
|
|
946
1180
|
// so the compiler forces that decision. Adopters preferring to throw
|
|
947
1181
|
// override `envelope`.
|
|
948
|
-
return
|
|
949
|
-
uri: uri.toString(),
|
|
950
|
-
version: 0,
|
|
951
|
-
root: undefined,
|
|
952
|
-
diagnostics: [] as TDiagnostic[]
|
|
953
|
-
};
|
|
1182
|
+
return TransferDocument.absent<TTransfer, TDiagnostic>(uri.toString());
|
|
954
1183
|
}
|
|
955
|
-
return this.encoder.toTransferDocument
|
|
1184
|
+
return this.withDirtyState(this.encoder.toTransferDocument(document) as unknown as TransferDocument<TTransfer, TDiagnostic>);
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
/**
|
|
1188
|
+
* The transfer document a request answers with for `astDocument`, the
|
|
1189
|
+
* store's current `dirty` stamped on it by {@link withDirtyState}. Every
|
|
1190
|
+
* document a request answers with goes through here, so none goes out
|
|
1191
|
+
* without the stamp.
|
|
1192
|
+
*/
|
|
1193
|
+
protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
|
|
1194
|
+
return this.withDirtyState(
|
|
1195
|
+
this.encoder.astDocumentToTransferDocument(astDocument as never) as unknown as TransferDocument<TTransfer, TDiagnostic>
|
|
1196
|
+
);
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/**
|
|
1200
|
+
* `document` with the store's current {@link TransferDocument.dirty}. Read
|
|
1201
|
+
* when the document is sent rather than kept with the build: a save changes
|
|
1202
|
+
* the answer without a rebuild.
|
|
1203
|
+
*/
|
|
1204
|
+
protected withDirtyState(document: TransferDocument<TTransfer, TDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
|
|
1205
|
+
return { ...document, dirty: this.services.workspace.TextDocuments.isDirty(document.uri) };
|
|
956
1206
|
}
|
|
957
1207
|
|
|
958
1208
|
/**
|
|
@@ -967,6 +1217,57 @@ export class DataServer<
|
|
|
967
1217
|
this.dispatchPhaseEvent(document, cancelToken)
|
|
968
1218
|
)
|
|
969
1219
|
);
|
|
1220
|
+
// The BUILD-phase hook, not the per-document one: this notification is one
|
|
1221
|
+
// message per build rather than one per document, and Langium hands the
|
|
1222
|
+
// whole batch over here. It also does not fire for a cancelled build,
|
|
1223
|
+
// which is what the per-document dispatch has to check by hand.
|
|
1224
|
+
this.disposables.push(
|
|
1225
|
+
this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built))
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/**
|
|
1230
|
+
* Report the documents that reached {@link DataServerOptions.subscriptionPhase}
|
|
1231
|
+
* and that NOBODY on this
|
|
1232
|
+
* connection is watching — the ones a client was not told about through
|
|
1233
|
+
* {@link dispatchPhaseEvent}, which is gated per URI.
|
|
1234
|
+
*
|
|
1235
|
+
* **The gap this closes is the one no other source can observe.** A document
|
|
1236
|
+
* the client watches, it hears about already. A file changed on disk, the
|
|
1237
|
+
* host's own filesystem watcher reports — and on a browser host, where the
|
|
1238
|
+
* workspace lives behind this head, an external change cannot happen at all.
|
|
1239
|
+
* What is left, and what nothing outside the server can see, is a document
|
|
1240
|
+
* rebuilt because something it DEPENDS ON changed: its file never changed, so
|
|
1241
|
+
* a filesystem watcher is silent by construction, and it has no subscriber, so
|
|
1242
|
+
* the update channel is silent by design. A consumer displaying data derived
|
|
1243
|
+
* from that document — a tree label, a decorator — otherwise goes stale with
|
|
1244
|
+
* no signal from any source, and repairs itself the moment someone opens the
|
|
1245
|
+
* file to investigate, which is what makes it expensive to diagnose later.
|
|
1246
|
+
*
|
|
1247
|
+
* Payload-free on purpose: URIs only, so a client re-reads what it displays
|
|
1248
|
+
* rather than being handed transfer documents it did not ask for. That is the
|
|
1249
|
+
* property the subscription map protects, and it is preserved here by
|
|
1250
|
+
* carrying no document rather than by gating the message.
|
|
1251
|
+
*
|
|
1252
|
+
* Quiet in the common case. Editing a document that an editor has open leaves
|
|
1253
|
+
* that URI watched and therefore out of this set, so a build with no
|
|
1254
|
+
* dependents produces nothing at all, and workspace initialisation produces
|
|
1255
|
+
* nothing because it does not build to this phase. The ceiling is a
|
|
1256
|
+
* whole-workspace rebuild at the subscription phase: one message, URIs only.
|
|
1257
|
+
*
|
|
1258
|
+
* The URI is canonicalised for the same reason the subscription map is keyed
|
|
1259
|
+
* that way, and is untested for the same reason as its twin in
|
|
1260
|
+
* {@link dispatchDeleteEvents}: the builder reports URIs out of its own
|
|
1261
|
+
* store, so a non-canonical one cannot be produced without a fixture
|
|
1262
|
+
* asserting a shape the real system never emits.
|
|
1263
|
+
*/
|
|
1264
|
+
protected dispatchBuiltEvent(built: readonly LangiumDocument[]): void {
|
|
1265
|
+
const uris = built.map(document => this.canonicalKey(document.uri.toString())).filter(uri => !this.subscriptions.has(uri));
|
|
1266
|
+
if (uris.length === 0) {
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
|
|
1270
|
+
this.clientProxy.onDocumentsBuilt({ uris });
|
|
970
1271
|
}
|
|
971
1272
|
|
|
972
1273
|
/**
|
|
@@ -987,23 +1288,89 @@ export class DataServer<
|
|
|
987
1288
|
this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
|
|
988
1289
|
}
|
|
989
1290
|
|
|
1291
|
+
/** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
|
|
1292
|
+
protected subscribeToDirtyChanges(): void {
|
|
1293
|
+
this.disposables.push(this.services.workspace.TextDocuments.onDidChangeDirty(event => this.dispatchDirtyEvent(event)));
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/**
|
|
1297
|
+
* Send a dirty flip to the connection, gated by the subscription map as
|
|
1298
|
+
* {@link dispatchSaveEvent} is: the answer at any one moment travels on
|
|
1299
|
+
* every document sent, so a client that watches nothing reads it there.
|
|
1300
|
+
*/
|
|
1301
|
+
protected dispatchDirtyEvent(event: DocumentDirtyChangedEvent): void {
|
|
1302
|
+
const uri = this.canonicalKey(event.uri);
|
|
1303
|
+
if (this.subscriptions.has(uri)) {
|
|
1304
|
+
this.clientProxy.onDocumentDirtyChanged({ uri, dirty: event.dirty });
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
990
1308
|
/**
|
|
991
|
-
* Mark the
|
|
992
|
-
* {@link pendingRevertBroadcasts}).
|
|
993
|
-
*
|
|
994
|
-
*
|
|
1309
|
+
* Mark each document the store releases after its last close (see
|
|
1310
|
+
* {@link pendingRevertBroadcasts}). A release, not the close itself: a
|
|
1311
|
+
* document whose last client lost its connection is released only once
|
|
1312
|
+
* the revert grace runs out, or when another client opens it meanwhile, and
|
|
1313
|
+
* not at all when a client lost from it opens it again within its own
|
|
1314
|
+
* grace.
|
|
995
1315
|
*/
|
|
996
1316
|
protected subscribeToTextDocumentCloses(): void {
|
|
997
|
-
const textDocuments = this.services.workspace.TextDocuments;
|
|
998
1317
|
this.disposables.push(
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
this.pendingRevertBroadcasts.add(this.canonicalKey(event.document.uri));
|
|
1002
|
-
}
|
|
1318
|
+
this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
|
|
1319
|
+
this.pendingRevertBroadcasts.add(this.canonicalKey(event.uri));
|
|
1003
1320
|
})
|
|
1004
1321
|
);
|
|
1005
1322
|
}
|
|
1006
1323
|
|
|
1324
|
+
/**
|
|
1325
|
+
* Fan out a deletion for each removed URI, to EVERY client on the connection
|
|
1326
|
+
* rather than only to the ones watching that URI.
|
|
1327
|
+
*
|
|
1328
|
+
* **Deliberately ungated, where {@link dispatchPhaseEvent} and
|
|
1329
|
+
* {@link dispatchSaveEvent} are gated.** Those two carry a built document and
|
|
1330
|
+
* fire on every build, so the subscription map is what keeps bandwidth
|
|
1331
|
+
* proportional to what a client asked for. A deletion is neither: it is one
|
|
1332
|
+
* URI, it is rare, and it reports the workspace's STRUCTURE rather than a
|
|
1333
|
+
* document's content. Gating it forces any consumer that displays the
|
|
1334
|
+
* workspace — a model tree, a file decorator — to learn about disappearances
|
|
1335
|
+
* from a filesystem watcher instead, which a client hosted in a browser has
|
|
1336
|
+
* no way to run: its workspace lives behind the head. A client that does not
|
|
1337
|
+
* care filters on the URI, which costs it a comparison.
|
|
1338
|
+
*
|
|
1339
|
+
* The precedent is the last-close revert broadcast (see
|
|
1340
|
+
* {@link pendingRevertBroadcasts}), where the same judgement was already made
|
|
1341
|
+
* in the other direction: a transition that matters enough is delivered
|
|
1342
|
+
* without a subscription.
|
|
1343
|
+
*
|
|
1344
|
+
* Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
|
|
1345
|
+
* listener, which is the only place a deletion is observable: `update`
|
|
1346
|
+
* removes the document before deriving the rebuild set, so it is never built.
|
|
1347
|
+
* That ordering also puts this notification ahead of the `'rebuilt'` events
|
|
1348
|
+
* for the dependents whose references the deletion just broke.
|
|
1349
|
+
*
|
|
1350
|
+
* The `deleted` list arrives already expanded to concrete document URIs —
|
|
1351
|
+
* `deleteDocuments` resolves a directory URI to the documents beneath it — so
|
|
1352
|
+
* no caller has to handle a directory here.
|
|
1353
|
+
*
|
|
1354
|
+
* Per-URI derived state is dropped for the same reason it is dropped
|
|
1355
|
+
* anywhere: it describes a document that no longer exists.
|
|
1356
|
+
* {@link lastEmittedFingerprint} in particular can outlive its subscriptions
|
|
1357
|
+
* through the last-close revert path — left behind, it is adopted as the
|
|
1358
|
+
* baseline by the next {@link watchModelDocument} and suppresses the first
|
|
1359
|
+
* emit after the file returns with its previous content.
|
|
1360
|
+
*
|
|
1361
|
+
* The subscription itself SURVIVES: a recreated file resumes delivering to
|
|
1362
|
+
* the same watchers with no re-subscription, and a client that answers the
|
|
1363
|
+
* deletion by closing releases the watch through `closeModelDocument` anyway.
|
|
1364
|
+
*/
|
|
1365
|
+
protected dispatchDeleteEvents(deleted: readonly URI[]): void {
|
|
1366
|
+
for (const removed of deleted) {
|
|
1367
|
+
const uri = this.canonicalKey(removed.toString());
|
|
1368
|
+
this.lastEmittedFingerprint.delete(uri);
|
|
1369
|
+
this.pendingRevertBroadcasts.delete(uri);
|
|
1370
|
+
this.clientProxy.onDocumentDeleted({ uri });
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1007
1374
|
/** Fan out a save event for the document's URI, gated by the subscription map. */
|
|
1008
1375
|
protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void {
|
|
1009
1376
|
// The save event arrives under the CLIENT URI the text store keys by (e.g. a
|
|
@@ -1122,26 +1489,19 @@ export class DataServer<
|
|
|
1122
1489
|
/**
|
|
1123
1490
|
* Discriminate the reason for a phase-event-driven update notification.
|
|
1124
1491
|
* Uses the most recent `DocumentBuilder.onUpdate` snapshot:
|
|
1125
|
-
* - URI in the `deleted` list → `'deleted'`
|
|
1126
1492
|
* - URI in the `changed` list → `'changed'` (the URI was passed to
|
|
1127
1493
|
* `documentBuilder.update(changed, deleted)`, which spans `didChange`
|
|
1128
1494
|
* text-document events and programmatic `update([uri], [])` calls).
|
|
1129
1495
|
* - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
|
|
1130
1496
|
* because something it depends on changed; its own text wasn't flagged).
|
|
1131
1497
|
*
|
|
1132
|
-
* `'saved'` is NOT emitted
|
|
1133
|
-
* `DataClientProtocol.onDocumentSaved` channel
|
|
1134
|
-
* unified
|
|
1498
|
+
* `'saved'` is NOT emitted here — saves take the dedicated
|
|
1499
|
+
* `DataClientProtocol.onDocumentSaved` channel, and adopters wanting a
|
|
1500
|
+
* unified stream synthesise it in their bridge layer. A deletion is not a
|
|
1501
|
+
* reason at all; see {@link dispatchDeleteEvents}.
|
|
1135
1502
|
*/
|
|
1136
1503
|
protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'] {
|
|
1137
|
-
|
|
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';
|
|
1504
|
+
return this.lastBuildUpdate?.changed.some(changed => UriUtils.equals(changed, uri)) ? 'changed' : 'rebuilt';
|
|
1145
1505
|
}
|
|
1146
1506
|
|
|
1147
1507
|
/**
|
|
@@ -1243,7 +1603,7 @@ export class DataServer<
|
|
|
1243
1603
|
|
|
1244
1604
|
async stopProfiling(args: StopProfilingArgs): Promise<string> {
|
|
1245
1605
|
if (!this.activeProfile) {
|
|
1246
|
-
throw
|
|
1606
|
+
throw noActiveProfileError();
|
|
1247
1607
|
}
|
|
1248
1608
|
const capture = this.activeProfile;
|
|
1249
1609
|
this.activeProfile = undefined;
|
|
@@ -1276,7 +1636,8 @@ export class DataServer<
|
|
|
1276
1636
|
methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
|
|
1277
1637
|
additionalMethods,
|
|
1278
1638
|
excludedMethods: partial.excludedMethods ?? [],
|
|
1279
|
-
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
|
|
1639
|
+
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
|
|
1640
|
+
referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
|
|
1280
1641
|
};
|
|
1281
1642
|
}
|
|
1282
1643
|
}
|