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