@hydranium/data-server 1.0.0-next.32 → 1.0.0-next.321
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 +57 -73
- package/lib/browser/index.d.ts +10 -0
- package/lib/browser/index.d.ts.map +1 -0
- package/lib/browser/index.js +15 -0
- package/lib/browser/index.js.map +1 -0
- package/lib/browser/start-data-server-in-worker.d.ts +23 -0
- package/lib/browser/start-data-server-in-worker.d.ts.map +1 -0
- package/lib/browser/start-data-server-in-worker.js +29 -0
- package/lib/browser/start-data-server-in-worker.js.map +1 -0
- package/lib/data-server.d.ts +440 -286
- package/lib/data-server.d.ts.map +1 -1
- package/lib/data-server.js +743 -501
- package/lib/data-server.js.map +1 -1
- package/lib/messages/index.d.ts +1 -1
- package/lib/messages/index.d.ts.map +1 -1
- package/lib/messages/index.js +1 -1
- package/lib/messages/index.js.map +1 -1
- package/lib/node/node-diagnostics-provider.d.ts.map +1 -1
- package/lib/node/node-diagnostics-provider.js +2 -1
- package/lib/node/node-diagnostics-provider.js.map +1 -1
- package/lib/testing/data-server-harness.d.ts +31 -14
- package/lib/testing/data-server-harness.d.ts.map +1 -1
- package/lib/testing/data-server-harness.js +8 -3
- package/lib/testing/data-server-harness.js.map +1 -1
- package/lib/testing/index.d.ts +1 -0
- package/lib/testing/index.d.ts.map +1 -1
- package/lib/testing/index.js.map +1 -1
- package/package.json +35 -43
- package/src/browser/index.ts +15 -0
- package/src/browser/start-data-server-in-worker.ts +35 -0
- package/src/data-server.ts +899 -540
- package/src/messages/index.ts +8 -1
- package/src/node/node-diagnostics-provider.ts +2 -8
- package/src/testing/data-server-harness.ts +55 -26
- package/src/testing/index.ts +5 -2
package/src/data-server.ts
CHANGED
|
@@ -8,16 +8,25 @@
|
|
|
8
8
|
********************************************************************************/
|
|
9
9
|
|
|
10
10
|
import {
|
|
11
|
+
asModelVersion,
|
|
11
12
|
createRpcProxy,
|
|
12
13
|
defineMessage,
|
|
14
|
+
describeErrorWithStack,
|
|
13
15
|
DisposableCollection,
|
|
16
|
+
HYDRANIUM_ERROR_CODES,
|
|
14
17
|
isDocumentSource,
|
|
15
18
|
isElementSource,
|
|
19
|
+
isResponseError,
|
|
16
20
|
isSyntheticSource,
|
|
21
|
+
messageData,
|
|
17
22
|
messageError,
|
|
18
23
|
ReferenceSource,
|
|
24
|
+
SessionClosedError,
|
|
25
|
+
TIMED_OUT,
|
|
19
26
|
type CloseModelArgs,
|
|
27
|
+
type HydraniumMessageData,
|
|
20
28
|
type HydraniumResponseError,
|
|
29
|
+
type CanonicalUri,
|
|
21
30
|
type Disposable,
|
|
22
31
|
type ElementSource,
|
|
23
32
|
type FindNextNameArgs,
|
|
@@ -29,10 +38,18 @@ import {
|
|
|
29
38
|
type ReferenceContext,
|
|
30
39
|
type ReferenceRequest,
|
|
31
40
|
type ReferenceTarget,
|
|
41
|
+
type TransferModelSnapshot,
|
|
42
|
+
type ModelVersion,
|
|
43
|
+
type TextState,
|
|
32
44
|
type Tracer,
|
|
33
45
|
type TransferDiagnostic,
|
|
34
|
-
|
|
35
|
-
type
|
|
46
|
+
TransferDocument,
|
|
47
|
+
type TransferCreatedDocument,
|
|
48
|
+
type TransferSavedDocument,
|
|
49
|
+
type TransferWatchedDocument,
|
|
50
|
+
type TransferElement,
|
|
51
|
+
UNKNOWN_CLIENT_ID,
|
|
52
|
+
textHash
|
|
36
53
|
} from '@hydranium/protocol';
|
|
37
54
|
import {
|
|
38
55
|
DATA_SERVER_DIAGNOSTICS_METHODS,
|
|
@@ -45,15 +62,22 @@ import {
|
|
|
45
62
|
type StartProfilingArgs,
|
|
46
63
|
type StopProfilingArgs,
|
|
47
64
|
type WriteServerHeapSnapshotArgs,
|
|
65
|
+
type CloseSessionArgs,
|
|
66
|
+
type CreateModelDocumentArgs,
|
|
67
|
+
type CreateSessionArgs,
|
|
48
68
|
type GetModelDocumentArgs,
|
|
49
69
|
type GetProjectForUriArgs,
|
|
70
|
+
type ProjectChangeReason,
|
|
71
|
+
type TransferDeleteDocumentArgs,
|
|
72
|
+
type TransferPersistDocumentArgs,
|
|
50
73
|
type TransferSaveDocumentArgs,
|
|
51
74
|
type WatchModelDocumentArgs,
|
|
52
75
|
type TransferDocumentSavedEvent,
|
|
53
76
|
type TransferDocumentUpdatedEvent,
|
|
54
|
-
type TransferUpdateDocumentArgs
|
|
77
|
+
type TransferUpdateDocumentArgs,
|
|
78
|
+
type TransferUpdateDocumentsArgs
|
|
55
79
|
} from '@hydranium/protocol/data';
|
|
56
|
-
import {
|
|
80
|
+
import { DOCUMENT_RELEASE_CLIENT_ID } from '@hydranium/core';
|
|
57
81
|
import { defaultDataServerDiagnostics } from './default-diagnostics.js';
|
|
58
82
|
|
|
59
83
|
/**
|
|
@@ -73,23 +97,54 @@ export const NO_ACTIVE_PROFILE = defineMessage(
|
|
|
73
97
|
* The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
|
|
74
98
|
* survives reconstruction and is what a caller switches on.
|
|
75
99
|
*/
|
|
76
|
-
export const NO_ACTIVE_PROFILE_CODE =
|
|
100
|
+
export const NO_ACTIVE_PROFILE_CODE = HYDRANIUM_ERROR_CODES.noActiveProfile;
|
|
77
101
|
|
|
78
102
|
export const noActiveProfileError = (): HydraniumResponseError => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
|
|
79
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Raised when a reference question's wait for the build exceeds
|
|
106
|
+
* {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
107
|
+
*
|
|
108
|
+
* A `ResponseError` because a class name does not cross RPC: without the code a
|
|
109
|
+
* wire client cannot tell a wedged build from a reference that resolves to
|
|
110
|
+
* nothing, which is the distinction the wait exists to keep.
|
|
111
|
+
*/
|
|
112
|
+
export const REFERENCE_SETTLE_TIMEOUT = defineMessage(
|
|
113
|
+
'hydranium/data-server/reference-settle-timeout',
|
|
114
|
+
'The model is still being processed; try again in a moment.'
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
/** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
|
|
118
|
+
export const REFERENCE_SETTLE_TIMEOUT_CODE = HYDRANIUM_ERROR_CODES.referenceSettleTimeout;
|
|
119
|
+
|
|
120
|
+
/** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */
|
|
121
|
+
export const referenceSettleTimeoutError = (elapsedMs: number): ResponseError<HydraniumMessageData & { readonly elapsedMs: number }> =>
|
|
122
|
+
new ResponseError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT.format(), {
|
|
123
|
+
elapsedMs,
|
|
124
|
+
...messageData(REFERENCE_SETTLE_TIMEOUT)
|
|
125
|
+
});
|
|
126
|
+
|
|
80
127
|
import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
|
|
81
128
|
import type {
|
|
82
|
-
|
|
129
|
+
ClientSession,
|
|
130
|
+
ClientSessionWriteArgs,
|
|
83
131
|
HydraniumLanguageServices,
|
|
84
132
|
LogNameOptions,
|
|
133
|
+
AstDiagnostic,
|
|
134
|
+
AstDocument,
|
|
135
|
+
AstDocumentSavedEvent,
|
|
136
|
+
EncodedTransferDocument,
|
|
137
|
+
ModelDeletedEvent,
|
|
138
|
+
ModelDirtyChangedEvent,
|
|
85
139
|
ModelService,
|
|
140
|
+
ModelUpdatedEvent,
|
|
86
141
|
ProjectChangeEvent,
|
|
87
142
|
ServerSharedServices,
|
|
143
|
+
SessionEndCause,
|
|
88
144
|
TransferEncoder
|
|
89
145
|
} from '@hydranium/core';
|
|
90
|
-
import type
|
|
91
|
-
import { type
|
|
92
|
-
import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
|
|
146
|
+
import { type AstNode, DocumentState, UriUtils, type URI } from '@hydranium/langium';
|
|
147
|
+
import { type MessageConnection, ResponseError } from 'vscode-jsonrpc';
|
|
93
148
|
|
|
94
149
|
/**
|
|
95
150
|
* Domain separator between text and diagnostics inputs of
|
|
@@ -100,34 +155,11 @@ import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
|
|
|
100
155
|
const FINGERPRINT_SEPARATOR = '\0';
|
|
101
156
|
|
|
102
157
|
/**
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
* **A cryptographic hash via `node:crypto` is the wrong trade**: the
|
|
107
|
-
* fingerprint only needs a stable signal that `(text, diagnostics)` changed
|
|
108
|
-
* between emissions, and a `node:*` import would cost
|
|
109
|
-
* `@hydranium/data-server` its browser-portability. Parts are fed
|
|
110
|
-
* incrementally, char by char, so multi-MB document text is never
|
|
111
|
-
* concatenated into one string.
|
|
158
|
+
* `LSPErrorCodes.ServerCancelled`, with which Langium's document wait rejects
|
|
159
|
+
* for a URI that has no document; `vscode-languageserver-protocol` is not a
|
|
160
|
+
* dependency of this package.
|
|
112
161
|
*/
|
|
113
|
-
|
|
114
|
-
let h1 = 0xdeadbeef;
|
|
115
|
-
let h2 = 0x41c6ce57;
|
|
116
|
-
for (const part of parts) {
|
|
117
|
-
for (let i = 0; i < part.length; i++) {
|
|
118
|
-
const ch = part.charCodeAt(i);
|
|
119
|
-
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
120
|
-
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
|
|
124
|
-
h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
125
|
-
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
|
|
126
|
-
h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
127
|
-
const high = (h2 >>> 0).toString(16).padStart(8, '0');
|
|
128
|
-
const low = (h1 >>> 0).toString(16).padStart(8, '0');
|
|
129
|
-
return high + low;
|
|
130
|
-
}
|
|
162
|
+
const SERVER_CANCELLED = -32802;
|
|
131
163
|
|
|
132
164
|
/**
|
|
133
165
|
* Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
|
|
@@ -140,26 +172,32 @@ function fingerprintHash(parts: readonly string[]): string {
|
|
|
140
172
|
* folded in on a cascade rebuild that leaves the document's own text
|
|
141
173
|
* untouched. Safe for any adopter whose AST extensions fold derived state
|
|
142
174
|
* into the transfer projection (the framework norm).
|
|
143
|
-
* - `'text-diagnostics'` — the cheaper
|
|
144
|
-
* opt-DOWN for adopters that fold no derived state and want to avoid
|
|
145
|
-
* transfer
|
|
175
|
+
* - `'text-diagnostics'` — the cheaper parsed-text + diagnostics hash. An
|
|
176
|
+
* opt-DOWN for adopters that fold no derived state and want to avoid
|
|
177
|
+
* stringifying the transfer root per phase event.
|
|
146
178
|
*/
|
|
147
179
|
export type FingerprintStrategy = 'transfer-document' | 'text-diagnostics';
|
|
148
180
|
|
|
149
|
-
/**
|
|
150
|
-
|
|
151
|
-
|
|
181
|
+
/**
|
|
182
|
+
* Hash `text`, the text the model was parsed from, + `model`'s diagnostics — the `'text-diagnostics'` strategy.
|
|
183
|
+
* The text comes from the root's ledger record or CST, as the document's own may have moved on,
|
|
184
|
+
* and a repair in place leaves the CST on the unrepaired text;
|
|
185
|
+
* a root built without a CST hashes as `'transfer-document'`.
|
|
186
|
+
* Absent diagnostics must hash apart from `[]`, as in {@link transferDocumentFingerprint}.
|
|
187
|
+
*/
|
|
188
|
+
function textDiagnosticsFingerprint(text: string | undefined, model: EncodedTransferDocument<TransferElement, unknown>['model']): string {
|
|
189
|
+
return text === undefined
|
|
190
|
+
? transferDocumentFingerprint(model)
|
|
191
|
+
: textHash([text, FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
|
|
152
192
|
}
|
|
153
193
|
|
|
154
|
-
/**
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
JSON.stringify(transferDocument.diagnostics)
|
|
162
|
-
]);
|
|
194
|
+
/**
|
|
195
|
+
* Hash an encoded model's root + diagnostics — the `'transfer-document'` strategy.
|
|
196
|
+
* Absent diagnostics must hash apart from `[]`: a client skipping a render on an
|
|
197
|
+
* equal hash would otherwise miss a validation that found nothing.
|
|
198
|
+
*/
|
|
199
|
+
function transferDocumentFingerprint(model: EncodedTransferDocument<TransferElement, unknown>['model']): string {
|
|
200
|
+
return textHash([JSON.stringify(model.root), FINGERPRINT_SEPARATOR, JSON.stringify(model.diagnostics ?? null)]);
|
|
163
201
|
}
|
|
164
202
|
/**
|
|
165
203
|
* `logAfterMs` threshold passed to {@link Tracer.time} around
|
|
@@ -180,12 +218,14 @@ export interface DataServerOptions extends LogNameOptions {
|
|
|
180
218
|
* (`DataClientProtocol.onDocumentUpdated`).
|
|
181
219
|
*
|
|
182
220
|
* **Subscription dispatch only** — distinct from the synchronous RPC
|
|
183
|
-
* response phase.
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
221
|
+
* response phase. A read (`getModelDocument`) settles at the
|
|
222
|
+
* integrity-settled landmark (`IntegrityService.SettledState`), or at
|
|
223
|
+
* `Validated` when {@link GetModelDocumentArgs.includeDiagnostics} is set.
|
|
224
|
+
* A write (`updateModelDocument` / `updateModelDocuments` /
|
|
225
|
+
* `saveModelDocument`) answers once its document is validated, as a
|
|
226
|
+
* session's write does; a save then also waits for
|
|
227
|
+
* `ModelService.settleLanguageClient`. This option controls only the async
|
|
228
|
+
* notification phase.
|
|
189
229
|
*
|
|
190
230
|
* Default: `DocumentState.Validated` — validation is the last builder
|
|
191
231
|
* phase and produces the full diagnostic set, so subscription events fired
|
|
@@ -226,6 +266,22 @@ export interface DataServerOptions extends LogNameOptions {
|
|
|
226
266
|
*/
|
|
227
267
|
readonly fingerprintStrategy?: FingerprintStrategy;
|
|
228
268
|
|
|
269
|
+
/**
|
|
270
|
+
* How long a reference question waits for the build to reach `Linked` before
|
|
271
|
+
* failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the
|
|
272
|
+
* wait resolves off a build-phase notification, so a build cancelled below
|
|
273
|
+
* `Linked` with nothing after it leaves the request unanswered for the life
|
|
274
|
+
* of the server.
|
|
275
|
+
*
|
|
276
|
+
* Expiry rejects rather than reading the index anyway: the unsettled index
|
|
277
|
+
* is what the wait keeps the caller away from, so falling through to it on a
|
|
278
|
+
* slow build reinstates the fault — and on a name proposal persists it.
|
|
279
|
+
*
|
|
280
|
+
* Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace
|
|
281
|
+
* still reaching `Linked` for the first time.
|
|
282
|
+
*/
|
|
283
|
+
readonly referenceSettleTimeoutMs?: number;
|
|
284
|
+
|
|
229
285
|
/**
|
|
230
286
|
* Wire-method namespace for both inbound request handlers and the
|
|
231
287
|
* outbound notification client proxy. Defaults to
|
|
@@ -283,15 +339,20 @@ export interface DataServerOptions extends LogNameOptions {
|
|
|
283
339
|
* When supplied, every inbound data-server RPC is timed into this collector
|
|
284
340
|
* (via the `createRpcProxy` binding) and exposed through
|
|
285
341
|
* {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an
|
|
286
|
-
* LSP connection can pass the SAME collector to
|
|
287
|
-
*
|
|
288
|
-
*
|
|
342
|
+
* LSP connection can pass the SAME collector through `lspLatencyOptions` to
|
|
343
|
+
* that connection, so one report covers both heads. Absent by default (no
|
|
344
|
+
* timing overhead).
|
|
289
345
|
*/
|
|
290
346
|
readonly latency?: LatencyCollector;
|
|
291
347
|
}
|
|
292
348
|
|
|
293
|
-
/**
|
|
294
|
-
|
|
349
|
+
/**
|
|
350
|
+
* Fully-resolved variant of {@link DataServerOptions} — every field set, after
|
|
351
|
+
* merging defaults. Returned by the `protected`
|
|
352
|
+
* {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so
|
|
353
|
+
* an adopter changing how defaults resolve has to name it.
|
|
354
|
+
*/
|
|
355
|
+
export interface ResolvedDataServerOptions {
|
|
295
356
|
readonly subscriptionPhase: DocumentState;
|
|
296
357
|
readonly fingerprintStrategy: FingerprintStrategy;
|
|
297
358
|
readonly methodNamespace: string;
|
|
@@ -299,6 +360,41 @@ interface ResolvedDataServerOptions {
|
|
|
299
360
|
readonly excludedMethods: readonly string[];
|
|
300
361
|
/** Always resolved — to the caller's, or to the platform default. */
|
|
301
362
|
readonly diagnostics: DataServerDiagnosticsProvider;
|
|
363
|
+
readonly referenceSettleTimeoutMs: number;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* What a {@link DataServer} keeps per canonical URI, in the `protected`
|
|
368
|
+
* {@link DataServer.uriWatchRecords}. A record lives while it has a watcher
|
|
369
|
+
* or a release mark; {@link DataServer.pruneUriWatchRecord} enforces that on
|
|
370
|
+
* every path that removes either, so a record with no watcher has a release
|
|
371
|
+
* broadcast pending. Test the size of {@link DataServerUriWatchRecord.watchers}, not the
|
|
372
|
+
* record's presence, for "watched".
|
|
373
|
+
*/
|
|
374
|
+
export interface DataServerUriWatchRecord {
|
|
375
|
+
/** The client ids watching the URI; save, dirty and phase events go out only while it is non-empty, a pending release mark aside. */
|
|
376
|
+
readonly watchers: Set<string>;
|
|
377
|
+
/** Digest of the last emitted state, or of the state a first watch found; see {@link DataServer.dispatchPhaseEvent} for why it de-duplicates, {@link DataServer.computeDocumentFingerprint} for its inputs. */
|
|
378
|
+
fingerprint?: string;
|
|
379
|
+
/**
|
|
380
|
+
* The version {@link DataServerUriWatchRecord.fingerprint} was taken at; an
|
|
381
|
+
* event goes out when either moves. Not {@link DataServerUriWatchRecord.sentVersion}:
|
|
382
|
+
* a first watch sets this and sends nothing, so the next event at its
|
|
383
|
+
* version still carries the manager's attribution.
|
|
384
|
+
*/
|
|
385
|
+
fingerprintVersion?: ModelVersion;
|
|
386
|
+
/** Set by {@link DataServer.subscribeToModelReleases} once a release happened: its broadcast, the next phase event, goes out even without a watcher. */
|
|
387
|
+
releaseBroadcastPending?: boolean;
|
|
388
|
+
/**
|
|
389
|
+
* The version of an open document the last event sent was built at. The
|
|
390
|
+
* version sent again goes out as `'rebuilt'` from no client: the manager
|
|
391
|
+
* counts a version delivered only once its `Validated` listeners ran, so a
|
|
392
|
+
* build cancelled after the subscription phase would send it as a change
|
|
393
|
+
* twice. Only while the store has the document open: without it, a
|
|
394
|
+
* document can keep one version through changes of its file, so its events
|
|
395
|
+
* keep the manager's attribution.
|
|
396
|
+
*/
|
|
397
|
+
sentVersion?: number;
|
|
302
398
|
}
|
|
303
399
|
|
|
304
400
|
/**
|
|
@@ -322,13 +418,19 @@ interface ResolvedDataServerOptions {
|
|
|
322
418
|
* adopters subclass ONLY when they need to decorate wire returns or
|
|
323
419
|
* notifications. The usual adoption path is DI rebinds alone.
|
|
324
420
|
*
|
|
421
|
+
* **`TTransfer` is not checked.** It declares the union of the transfer roots
|
|
422
|
+
* the workspace's languages produce. Which root a document has is known only
|
|
423
|
+
* at runtime, from its language, so a `TTransfer` missing a language compiles.
|
|
424
|
+
*
|
|
325
425
|
* Lifecycle: the constructor registers framework request handlers (plus
|
|
326
426
|
* any names supplied via {@link DataServerOptions.additionalMethods}) and
|
|
327
427
|
* builds the {@link DataClientProtocol} notification proxy on the same
|
|
328
428
|
* connection in one {@link createRpcProxy} call (binding `this` as its
|
|
329
|
-
* `localTarget`) under the configured namespace, and
|
|
330
|
-
* `
|
|
331
|
-
* dispatches
|
|
429
|
+
* `localTarget`) under the configured namespace, and follows documents
|
|
430
|
+
* through `ModelService`'s events: at the configured phase, `onModelUpdated`
|
|
431
|
+
* dispatches per-document `clientProxy.onDocumentUpdated` for watched URIs and
|
|
432
|
+
* `onModelsBuilt` a single `clientProxy.onDocumentsBuilt` naming the batch's
|
|
433
|
+
* unwatched documents.
|
|
332
434
|
*
|
|
333
435
|
* The data-server requires the full {@link ServerSharedServices}
|
|
334
436
|
* shape — `HydraniumTextDocuments` for client-attributed updates,
|
|
@@ -356,87 +458,42 @@ export class DataServer<
|
|
|
356
458
|
* Framework defaults, exposed so an adopter can spread them when
|
|
357
459
|
* extending rather than restate a value the framework may change.
|
|
358
460
|
*/
|
|
359
|
-
static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>> = {
|
|
360
|
-
subscriptionPhase: DocumentState.Validated
|
|
461
|
+
static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>> = {
|
|
462
|
+
subscriptionPhase: DocumentState.Validated,
|
|
463
|
+
referenceSettleTimeoutMs: 60_000
|
|
361
464
|
};
|
|
362
465
|
|
|
363
466
|
protected readonly options: ResolvedDataServerOptions;
|
|
364
|
-
/**
|
|
365
|
-
protected readonly
|
|
467
|
+
/** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
|
|
468
|
+
protected readonly uriWatchRecords = new Map<string, DataServerUriWatchRecord>();
|
|
366
469
|
/**
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
* Kept because the document store releases a client's hold only from an
|
|
371
|
-
* explicit close, and a client that dies without closing would otherwise keep
|
|
372
|
-
* the document open forever — resident, and with its last-close revert
|
|
373
|
-
* suppressed. The store has no notion of which connection a clientId reached
|
|
374
|
-
* it over, so the connection-scoped set has to live here; teaching it a client
|
|
375
|
-
* identity is the more robust and much larger alternative.
|
|
470
|
+
* Per client id, the key each URI it watched resolved to when it watched.
|
|
471
|
+
* An unwatch looks the key up here: once a file is gone, a symlink to it
|
|
472
|
+
* no longer resolves to the key the watch is under.
|
|
376
473
|
*/
|
|
377
|
-
protected readonly
|
|
378
|
-
/** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
|
|
379
|
-
protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
|
|
380
|
-
protected readonly disposables = new DisposableCollection();
|
|
474
|
+
protected readonly watchKeys = new Map<string, Map<string, string>>();
|
|
381
475
|
/**
|
|
382
|
-
*
|
|
383
|
-
*
|
|
384
|
-
*
|
|
385
|
-
* `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
|
|
386
|
-
* URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
|
|
387
|
-
* the LSP side, so reason fidelity stays consistent between heads.
|
|
476
|
+
* The position of the last update or deletion event sent, which each
|
|
477
|
+
* such event carries, and a watch's answer carries as of the moment it
|
|
478
|
+
* took whether its document exists: an event past it was sent after.
|
|
388
479
|
*/
|
|
389
|
-
protected
|
|
480
|
+
protected eventSequence = 0;
|
|
390
481
|
/**
|
|
391
|
-
*
|
|
392
|
-
*
|
|
393
|
-
*
|
|
394
|
-
*
|
|
395
|
-
*
|
|
396
|
-
* Two scenarios routinely produce such rebuilds:
|
|
397
|
-
* 1. **Refresh-triggered rebuilds.** When a second client attaches to a
|
|
398
|
-
* document already open in another client,
|
|
399
|
-
* `HydraniumTextDocuments.refreshContent` fires `onDidChangeContent`
|
|
400
|
-
* purely to re-trigger the build pipeline — the text and diagnostics
|
|
401
|
-
* are identical to the prior emit.
|
|
402
|
-
* 2. **Cascade rebuilds with no diagnostic delta.** Langium rebuilds a
|
|
403
|
-
* document when a dependency changes; if the rebuild produces the
|
|
404
|
-
* same diagnostics, there is nothing new to communicate to subscribers.
|
|
405
|
-
*
|
|
406
|
-
* Without this filter, both scenarios reach subscribers as wire-side
|
|
407
|
-
* `'changed'` events. A subscriber that interprets `'changed'` as
|
|
408
|
-
* "another client wrote new content" and resets its in-memory root to
|
|
409
|
-
* the server view then misreads the spurious event as a concurrent
|
|
410
|
-
* third-party write and loses the user's edits.
|
|
411
|
-
*
|
|
412
|
-
* Initialised on {@link watchModelDocument} to the current
|
|
413
|
-
* document fingerprint so the FIRST phase event after a fresh
|
|
414
|
-
* subscription is also de-duplicated against the state subscribers
|
|
415
|
-
* obtained via `getModelDocument` — they do not need a redundant phase
|
|
416
|
-
* notification for the state they just fetched.
|
|
417
|
-
*
|
|
418
|
-
* Cleared in {@link unwatchModelDocument} when the last
|
|
419
|
-
* subscriber for a URI leaves so memory does not accumulate.
|
|
420
|
-
*
|
|
421
|
-
* Stored as a cyrb53 hex digest (16 chars per URI) rather than the raw
|
|
422
|
-
* text + diagnostics serialisation so the memory cost is constant in
|
|
423
|
-
* document size. See {@link computeDocumentFingerprint} for the inputs.
|
|
482
|
+
* The live client sessions this connection registered, by client id. A
|
|
483
|
+
* document request carrying one of these ids acts as that session; one
|
|
484
|
+
* carrying any other id fails. A session leaves once it ends, so a
|
|
485
|
+
* connection that registers many over its life does not accumulate them.
|
|
424
486
|
*/
|
|
425
|
-
protected readonly
|
|
487
|
+
protected readonly clientSessions = new Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer>>();
|
|
426
488
|
/**
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
432
|
-
* discarded state forever. Marked on the last-close transition (see
|
|
433
|
-
* {@link subscribeToTextDocumentCloses}) and consumed by
|
|
434
|
-
* {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
|
|
435
|
-
* phase event even without a subscription — de-duplicated against
|
|
436
|
-
* {@link lastEmittedFingerprint} where an entry survives, so a close
|
|
437
|
-
* whose disk state equals the last emitted state stays silent.
|
|
489
|
+
* Typed client proxy — sends `data-server/on*` notifications back over the same wire.
|
|
490
|
+
* The proxy sends any `on[A-Z]*` name other than `onDidOpenConnection` and
|
|
491
|
+
* `onDidCloseConnection`, for which it returns its own events, so a subclass
|
|
492
|
+
* with notifications of its own narrows only the type:
|
|
493
|
+
* `declare protected readonly clientProxy: TheirClient`.
|
|
438
494
|
*/
|
|
439
|
-
protected readonly
|
|
495
|
+
protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
|
|
496
|
+
protected readonly disposables = new DisposableCollection();
|
|
440
497
|
protected readonly tracer: Tracer;
|
|
441
498
|
/** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
|
|
442
499
|
protected activeProfile?: DataServerProfileCapture;
|
|
@@ -445,27 +502,23 @@ export class DataServer<
|
|
|
445
502
|
/** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */
|
|
446
503
|
protected readonly latency?: LatencyCollector;
|
|
447
504
|
/** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */
|
|
448
|
-
protected readonly encoder: TransferEncoder<
|
|
505
|
+
protected readonly encoder: TransferEncoder<TDiagnostic>;
|
|
449
506
|
/**
|
|
450
507
|
* In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
|
|
451
|
-
*
|
|
452
|
-
*
|
|
453
|
-
* while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
|
|
454
|
-
* `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
|
|
455
|
-
* to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
|
|
508
|
+
* Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
|
|
509
|
+
* {@link encoder} converts one into the other on the way out.
|
|
456
510
|
*/
|
|
457
|
-
protected readonly modelService: ModelService<AstNode,
|
|
511
|
+
protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
|
|
458
512
|
|
|
459
513
|
constructor(
|
|
460
514
|
protected readonly connection: MessageConnection,
|
|
461
|
-
protected readonly services: ServerSharedServices<TProject>,
|
|
515
|
+
protected readonly services: ServerSharedServices<TProject, TDiagnostic>,
|
|
462
516
|
options: DataServerOptions = {}
|
|
463
517
|
) {
|
|
464
518
|
this.options = this.resolveOptions(options);
|
|
465
519
|
this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
|
|
466
520
|
// DI-bound: adopters rebind `services.model.TransferEncoder` /
|
|
467
|
-
// `services.model.ModelService` with their own subclasses.
|
|
468
|
-
// framework upper bounds; the casts below narrow to this instance's generics.
|
|
521
|
+
// `services.model.ModelService` with their own subclasses.
|
|
469
522
|
const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
|
|
470
523
|
if (!encoder || !modelService) {
|
|
471
524
|
throw new Error(
|
|
@@ -473,8 +526,8 @@ export class DataServer<
|
|
|
473
526
|
'Did you compose `createServerSharedModule(ctx)` into your shared module?'
|
|
474
527
|
);
|
|
475
528
|
}
|
|
476
|
-
this.encoder = encoder
|
|
477
|
-
this.modelService = modelService
|
|
529
|
+
this.encoder = encoder;
|
|
530
|
+
this.modelService = modelService;
|
|
478
531
|
const excluded = new Set<string>(this.options.excludedMethods);
|
|
479
532
|
const registeredMethods = [
|
|
480
533
|
...DATA_SERVER_PROTOCOL_METHODS,
|
|
@@ -496,36 +549,37 @@ export class DataServer<
|
|
|
496
549
|
// framework's own rejections.
|
|
497
550
|
renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
|
|
498
551
|
});
|
|
499
|
-
this.disposables.push(
|
|
500
|
-
|
|
501
|
-
this.lastBuildUpdate = { changed, deleted };
|
|
502
|
-
})
|
|
503
|
-
);
|
|
504
|
-
this.subscribeToDocumentBuilder();
|
|
552
|
+
this.disposables.push(this.modelService.onModelDeleted(event => this.dispatchDeleteEvent(event)));
|
|
553
|
+
this.subscribeToModelUpdates();
|
|
505
554
|
this.subscribeToTextDocumentSaves();
|
|
506
|
-
this.
|
|
555
|
+
this.subscribeToDirtyChanges();
|
|
556
|
+
this.subscribeToModelReleases();
|
|
507
557
|
this.subscribeToProjectManager();
|
|
508
558
|
// Self-register teardown so an adopter that keeps no reference to the
|
|
509
559
|
// server still releases per-connection state, with no lifecycle hook of
|
|
510
|
-
// its own.
|
|
511
|
-
|
|
560
|
+
// its own. The client did not close anything itself, so its sessions end
|
|
561
|
+
// as lost and each document it was the last to have open waits out the
|
|
562
|
+
// store's release grace. See `dispose`.
|
|
563
|
+
this.disposables.push(connection.onClose(() => this.dispose('lost')));
|
|
512
564
|
}
|
|
513
565
|
|
|
514
566
|
/**
|
|
515
567
|
* Release everything the constructor wired up — the bound protocol
|
|
516
|
-
* handlers and every listener — and clear
|
|
517
|
-
*
|
|
518
|
-
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
521
|
-
* this server's and so outlives the connection unless released here.
|
|
568
|
+
* handlers and every listener — and clear {@link uriWatchRecords}, so a
|
|
569
|
+
* long-lived shared services bundle does not retain per-connection memory
|
|
570
|
+
* after the connection closes. Also ends every session this connection registered, which closes
|
|
571
|
+
* every document it has open: the SHARED store's state rather than this
|
|
572
|
+
* server's, which outlives the connection unless released here.
|
|
522
573
|
*
|
|
523
|
-
* Idempotent: subsequent calls are no-ops.
|
|
524
|
-
*
|
|
525
|
-
*
|
|
526
|
-
*
|
|
574
|
+
* Idempotent: subsequent calls are no-ops. Runs by itself when the
|
|
575
|
+
* connection closes, so adopters who don't hold a reference still get
|
|
576
|
+
* per-connection cleanup; adopters that DO hold a reference may call
|
|
577
|
+
* `dispose()` directly for early teardown. The sessions end with `cause`:
|
|
578
|
+
* `'closed'` releases every document whose last open they close at once,
|
|
579
|
+
* and `'lost'`, the connection's own close, lets each wait out the release
|
|
580
|
+
* grace.
|
|
527
581
|
*/
|
|
528
|
-
dispose(): void {
|
|
582
|
+
dispose(cause: SessionEndCause = 'closed'): void {
|
|
529
583
|
this.disposed = true;
|
|
530
584
|
// Release an in-flight interactive capture so the process-wide inspector
|
|
531
585
|
// singleton is not left active after the connection closes.
|
|
@@ -534,104 +588,151 @@ export class DataServer<
|
|
|
534
588
|
this.activeProfile = undefined;
|
|
535
589
|
void capture.stop({}).catch(() => undefined);
|
|
536
590
|
}
|
|
537
|
-
// AFTER `disposables.dispose()`, deliberately:
|
|
538
|
-
//
|
|
539
|
-
//
|
|
591
|
+
// AFTER `disposables.dispose()`, deliberately: ending a session releases
|
|
592
|
+
// each document it was the last to hold, and this server's own
|
|
593
|
+
// `onModelReleased` subscription would otherwise mark a release broadcast
|
|
594
|
+
// for a connection that is already gone.
|
|
540
595
|
this.disposables.dispose();
|
|
541
|
-
this.
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
this.
|
|
596
|
+
for (const [clientId, session] of this.clientSessions) {
|
|
597
|
+
this.endSession(clientId, session, cause);
|
|
598
|
+
}
|
|
599
|
+
this.uriWatchRecords.clear();
|
|
600
|
+
this.watchKeys.clear();
|
|
545
601
|
}
|
|
546
602
|
|
|
547
603
|
// ============================================================
|
|
548
|
-
// DataServerProtocol implementation
|
|
604
|
+
// DataServerProtocol implementation
|
|
549
605
|
// ============================================================
|
|
550
606
|
//
|
|
551
|
-
//
|
|
552
|
-
//
|
|
553
|
-
// the wire boundary via
|
|
554
|
-
//
|
|
555
|
-
//
|
|
556
|
-
//
|
|
557
|
-
|
|
558
|
-
async
|
|
559
|
-
//
|
|
560
|
-
//
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
await this.modelService.open(args);
|
|
564
|
-
// Record the hold so `dispose` can release it for a client that never
|
|
565
|
-
// closes. Keyed by the URI as given, because that is what `close` takes.
|
|
566
|
-
let holders = this.openedDocuments.get(args.uri);
|
|
567
|
-
if (!holders) {
|
|
568
|
-
holders = new Set<string>();
|
|
569
|
-
this.openedDocuments.set(args.uri, holders);
|
|
607
|
+
// Reads go to `ModelService`; a request that opens or writes a document
|
|
608
|
+
// goes to the session this connection registered under its `clientId`.
|
|
609
|
+
// Each answer is encoded on the wire boundary via
|
|
610
|
+
// `encoder.astDocumentToTransferDocument`. To change how documents are
|
|
611
|
+
// read, override on the ModelService subclass; to change how they are
|
|
612
|
+
// written, on the session class the bound `ClientSessionFactory` builds.
|
|
613
|
+
|
|
614
|
+
async createSession(args: CreateSessionArgs): Promise<void> {
|
|
615
|
+
// After teardown nothing would ever end a session registered now, and its
|
|
616
|
+
// id would stay taken for the life of the process.
|
|
617
|
+
if (this.disposed) {
|
|
618
|
+
throw new SessionClosedError(args.clientId);
|
|
570
619
|
}
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
//
|
|
574
|
-
//
|
|
575
|
-
//
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
620
|
+
const session = this.modelService.createSession(args.label, args.clientId, { resumeToken: args.resumeToken });
|
|
621
|
+
this.clientSessions.set(args.clientId, session);
|
|
622
|
+
// A session also ends without closeSession, as when a client registers
|
|
623
|
+
// again on another connection, and its watches and entry here would
|
|
624
|
+
// otherwise outlive it.
|
|
625
|
+
session.onDidDispose(cause => {
|
|
626
|
+
// A session class may report its end late, once a replacement holds
|
|
627
|
+
// the id here; the replacement's entry and watches stay.
|
|
628
|
+
if (this.clientSessions.get(args.clientId) !== session) {
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
this.dropWatches(args.clientId);
|
|
632
|
+
this.clientSessions.delete(args.clientId);
|
|
633
|
+
this.tracer.debug(`Forget session ${args.clientId}: it ended as ${cause}`);
|
|
634
|
+
});
|
|
584
635
|
}
|
|
585
636
|
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
637
|
+
/** End a session this connection registered. */
|
|
638
|
+
async closeSession(args: CloseSessionArgs): Promise<void> {
|
|
639
|
+
const session = this.clientSessions.get(args.clientId);
|
|
640
|
+
if (session) {
|
|
641
|
+
this.endSession(args.clientId, session);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
|
|
646
|
+
protected endSession(
|
|
647
|
+
clientId: string,
|
|
648
|
+
session: ClientSession<AstNode, AstDiagnostic, TTransfer>,
|
|
649
|
+
cause: SessionEndCause = 'closed'
|
|
650
|
+
): void {
|
|
651
|
+
this.dropWatches(clientId);
|
|
652
|
+
session.dispose(cause);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
protected dropWatches(clientId: string): void {
|
|
656
|
+
this.watchKeys.delete(clientId);
|
|
657
|
+
for (const [uri, record] of this.uriWatchRecords) {
|
|
658
|
+
if (record.watchers.delete(clientId)) {
|
|
659
|
+
this.pruneUriWatchRecord(uri);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
async createModelDocument(args: CreateModelDocumentArgs): Promise<TransferCreatedDocument<TTransfer, TDiagnostic>> {
|
|
665
|
+
const session = this.requireSession(args.clientId);
|
|
666
|
+
const version = await session.create(args.uri, args.text);
|
|
667
|
+
const snapshot = await this.openedSnapshot(args.uri, () => session.close(args.uri));
|
|
668
|
+
return { ...snapshot, created: { version: asModelVersion(version) } };
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
async updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>[]> {
|
|
672
|
+
const astDocuments = await this.requireSession(args.clientId).updateAll({
|
|
673
|
+
updates: args.updates.map(update => this.toSessionWrite(update))
|
|
674
|
+
});
|
|
675
|
+
return astDocuments.map(astDocument => this.encodeDocument(astDocument));
|
|
593
676
|
}
|
|
594
677
|
|
|
595
678
|
/**
|
|
596
|
-
*
|
|
597
|
-
*
|
|
679
|
+
* The session write a wire write request carries. Only the fields a session
|
|
680
|
+
* takes: a field an adopter adds to a request reaches the session only
|
|
681
|
+
* through an override of this.
|
|
598
682
|
*/
|
|
599
|
-
protected
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
683
|
+
protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer> {
|
|
684
|
+
return { uri: request.uri, model: request.model, baseVersion: request.baseVersion };
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* The session this connection registered under `clientId`, which every
|
|
689
|
+
* document request acts as. An id that is not one fails with the
|
|
690
|
+
* closed-session code: opening or writing under it would leave an open that
|
|
691
|
+
* no session end ever closes.
|
|
692
|
+
*/
|
|
693
|
+
protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer> {
|
|
694
|
+
const session = this.clientSessions.get(clientId);
|
|
695
|
+
if (!session) {
|
|
696
|
+
throw new SessionClosedError(clientId, 'The client session is not registered on this connection.');
|
|
607
697
|
}
|
|
698
|
+
return session;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
async openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
702
|
+
const session = this.requireSession(args.clientId);
|
|
703
|
+
const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
|
|
704
|
+
await session.open(args.uri, args.options);
|
|
705
|
+
// A repeat open keeps the earlier one, which is still in use.
|
|
706
|
+
return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
|
|
608
707
|
}
|
|
609
708
|
|
|
610
709
|
/**
|
|
611
|
-
*
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
*
|
|
615
|
-
* without this a client that dies mid-session keeps its documents open for the
|
|
616
|
-
* lifetime of the process: `isOpenInAnyClient` stays true, the document stays
|
|
617
|
-
* resident, and the last-close revert never runs. A long-lived multi-client
|
|
618
|
-
* head is the configuration where a dead client is normal rather than
|
|
619
|
-
* exceptional, so the leak accumulates there.
|
|
620
|
-
*
|
|
621
|
-
* Runs from {@link dispose}, which is synchronous, so each close is fired and
|
|
622
|
-
* its failure swallowed — a teardown must not reject, and a URI whose close
|
|
623
|
-
* fails is no worse off than it was before this drain existed.
|
|
710
|
+
* The snapshot a session's open or create answers with. When the read
|
|
711
|
+
* fails, `rollback` undoes the open this call made before the failure is
|
|
712
|
+
* rethrown: the caller sees no open, so nothing on its side would ever close
|
|
713
|
+
* it.
|
|
624
714
|
*/
|
|
625
|
-
protected
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
715
|
+
protected async openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
716
|
+
try {
|
|
717
|
+
return await this.getModelDocument({ uri });
|
|
718
|
+
} catch (error: unknown) {
|
|
719
|
+
// The open's failure is the one the caller needs, not the cleanup's.
|
|
720
|
+
await rollback?.().catch(() => undefined);
|
|
721
|
+
throw error;
|
|
632
722
|
}
|
|
633
723
|
}
|
|
634
724
|
|
|
725
|
+
async closeModelDocument(args: CloseModelArgs): Promise<void> {
|
|
726
|
+
// Through the handle, so a close under an ended session fails as that
|
|
727
|
+
// session's calls do, and a session class's own close is honoured.
|
|
728
|
+
const session = this.requireSession(args.clientId);
|
|
729
|
+
// Closing also releases the watch for (uri, clientId) — a forgotten
|
|
730
|
+
// unwatch would otherwise leak phase-event dispatch until the connection
|
|
731
|
+
// closes. Idempotent: a close without a prior watch is a no-op.
|
|
732
|
+
await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
|
|
733
|
+
await session.close(args.uri);
|
|
734
|
+
}
|
|
735
|
+
|
|
635
736
|
async getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
636
737
|
// Smart dispatch: a warm document (already in LangiumDocuments) is
|
|
637
738
|
// returned at its settle phase without a redundant build; a cold URI
|
|
@@ -644,77 +745,149 @@ export class DataServer<
|
|
|
644
745
|
// unsubscribed caller that needs diagnostics inline passes
|
|
645
746
|
// `includeDiagnostics: true` to settle at `Validated` instead.
|
|
646
747
|
const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
|
|
647
|
-
|
|
648
|
-
|
|
748
|
+
try {
|
|
749
|
+
return this.encodeDocument(await this.modelService.ensureDocumentState(args.uri, state));
|
|
750
|
+
} catch (error: unknown) {
|
|
751
|
+
// The protocol answers a read of a URI with no document with an
|
|
752
|
+
// envelope that has no model.
|
|
753
|
+
if (this.isMissingDocument(error, args.uri)) {
|
|
754
|
+
return this.envelope(UriUtils.toUri(args.uri));
|
|
755
|
+
}
|
|
756
|
+
throw error;
|
|
757
|
+
}
|
|
649
758
|
}
|
|
650
759
|
|
|
651
760
|
async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
652
|
-
const astDocument = await this.
|
|
653
|
-
return this.
|
|
761
|
+
const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
|
|
762
|
+
return this.encodeDocument(astDocument);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferSavedDocument<TTransfer, TDiagnostic>> {
|
|
766
|
+
const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
|
|
767
|
+
await this.modelService.settleLanguageClient(args.uri);
|
|
768
|
+
return { ...this.encodeDocument(astDocument), persisted: astDocument.persisted };
|
|
654
769
|
}
|
|
655
770
|
|
|
656
|
-
async
|
|
657
|
-
const
|
|
658
|
-
|
|
771
|
+
async persistModelDocument(args: TransferPersistDocumentArgs): Promise<TransferSavedDocument<TTransfer, TDiagnostic>> {
|
|
772
|
+
const version = await this.requireSession(args.clientId).persist({ uri: args.uri, baseVersion: args.baseVersion });
|
|
773
|
+
await this.modelService.settleLanguageClient(args.uri);
|
|
774
|
+
const astDocument = await this.modelService.ensureDocumentState(args.uri, this.services.workspace.DocumentBuilder.finalBuildState());
|
|
775
|
+
return { ...this.encodeDocument(astDocument), persisted: { version } };
|
|
659
776
|
}
|
|
660
777
|
|
|
661
778
|
/**
|
|
662
|
-
*
|
|
663
|
-
*
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
|
|
779
|
+
* Delete the document through the session, then release the session's
|
|
780
|
+
* watch of it, as {@link closeModelDocument} does. Released only after the
|
|
781
|
+
* delete: one that fails leaves the session its open and its watch. Other
|
|
782
|
+
* sessions' watches survive, as for any deletion.
|
|
783
|
+
*/
|
|
784
|
+
async deleteModelDocument(args: TransferDeleteDocumentArgs): Promise<void> {
|
|
785
|
+
const session = this.requireSession(args.clientId);
|
|
786
|
+
// Keyed before the delete: once the file is gone, a symlink to it no
|
|
787
|
+
// longer resolves to the key the watch is under.
|
|
788
|
+
const uri = this.canonicalKey(args.uri);
|
|
789
|
+
await session.delete({ uri: args.uri, baseVersion: args.baseVersion });
|
|
790
|
+
await this.unwatchModelDocument({ uri, clientId: args.clientId });
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/**
|
|
794
|
+
* Record a watch for `(uri, clientId)` in {@link uriWatchRecords}.
|
|
795
|
+
* Subsequent phase events on `uri` fan out to the wired
|
|
796
|
+
* `clientProxy.onDocumentUpdated`. The bidirectional pattern means the
|
|
797
|
+
* event channel is the client notification surface, not a returned
|
|
798
|
+
* handle.
|
|
799
|
+
*
|
|
800
|
+
* Also baselines the URI's emission fingerprint (see
|
|
801
|
+
* {@link dispatchPhaseEvent}) to the document's current state when the
|
|
802
|
+
* first watcher for the URI registers. This guarantees that any phase event firing immediately after
|
|
803
|
+
* the watch with no observable change is suppressed — watchers obtain
|
|
804
|
+
* initial state via `getModelDocument` (or {@link openModelDocument}) and
|
|
805
|
+
* do not need a redundant phase notification for that same state.
|
|
667
806
|
*
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
*
|
|
671
|
-
* phase event firing immediately after the watch with no observable
|
|
672
|
-
* change is suppressed — watchers obtain initial state via
|
|
673
|
-
* `getModelDocument` (or {@link openModelDocument}) and do not need a
|
|
674
|
-
* redundant phase notification for that same state.
|
|
807
|
+
* Answers once the document is loaded as a read loads it, with the key
|
|
808
|
+
* events name it by and whether a document exists, taken after the watch
|
|
809
|
+
* is in place and the load, so an event sent while it loads is older.
|
|
675
810
|
*/
|
|
676
|
-
async watchModelDocument(args: WatchModelDocumentArgs): Promise<
|
|
811
|
+
async watchModelDocument(args: WatchModelDocumentArgs): Promise<TransferWatchedDocument> {
|
|
677
812
|
const uri = this.canonicalKey(args.uri);
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
813
|
+
const keys = this.watchKeys.get(args.clientId) ?? new Map<string, string>();
|
|
814
|
+
this.watchKeys.set(args.clientId, keys.set(args.uri, uri));
|
|
815
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
|
|
816
|
+
this.uriWatchRecords.set(uri, record);
|
|
817
|
+
record.watchers.add(args.clientId);
|
|
818
|
+
if (record.fingerprint === undefined) {
|
|
819
|
+
const document = this.modelService.getDocument(args.uri);
|
|
820
|
+
if (document && !this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
|
|
821
|
+
record.fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
|
|
822
|
+
record.fingerprintVersion = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
|
|
688
823
|
}
|
|
689
824
|
}
|
|
825
|
+
// As for a read, only a missing document counts as none. A file briefly
|
|
826
|
+
// unreadable leaves the builder's placeholder, and is there all the same.
|
|
827
|
+
// Whether it exists, the text held and the position of the last event
|
|
828
|
+
// sent are read in one synchronous run, so an event sent after is past
|
|
829
|
+
// the position and moves the text past the state answered.
|
|
830
|
+
const answer = (exists: boolean): TransferWatchedDocument => {
|
|
831
|
+
const text = exists ? this.serverTextState(args.uri) : undefined;
|
|
832
|
+
return { uri, exists, sequence: this.eventSequence, ...(text ? { text } : {}) };
|
|
833
|
+
};
|
|
834
|
+
return this.modelService.ensureDocumentState(args.uri).then(
|
|
835
|
+
() => answer(this.modelService.getDocument(args.uri) !== undefined),
|
|
836
|
+
(error: unknown) => answer(!this.isMissingDocument(error, args.uri))
|
|
837
|
+
);
|
|
690
838
|
}
|
|
691
839
|
|
|
692
840
|
/**
|
|
693
841
|
* Remove a watch for `(uri, clientId)` previously created by
|
|
694
842
|
* {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
|
|
695
|
-
* Dispatch for `uri` stops once no watchers remain,
|
|
696
|
-
*
|
|
697
|
-
*
|
|
698
|
-
*
|
|
843
|
+
* Dispatch for `uri` stops once no watchers remain, and the emission
|
|
844
|
+
* fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
|
|
845
|
+
*
|
|
846
|
+
* A URI the client watched is unwatched under the key it resolved to then,
|
|
847
|
+
* from {@link watchKeys}, which still holds once its file is gone.
|
|
699
848
|
*/
|
|
700
849
|
async unwatchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
|
|
701
|
-
const
|
|
702
|
-
const
|
|
703
|
-
|
|
850
|
+
const keys = this.watchKeys.get(args.clientId);
|
|
851
|
+
const uri = keys?.get(args.uri) ?? this.canonicalKey(args.uri);
|
|
852
|
+
// Every spelling the client watched it under was this one watch.
|
|
853
|
+
keys?.forEach((key, spelling) => {
|
|
854
|
+
if (key === uri) {
|
|
855
|
+
keys.delete(spelling);
|
|
856
|
+
}
|
|
857
|
+
});
|
|
858
|
+
if (keys?.size === 0) {
|
|
859
|
+
this.watchKeys.delete(args.clientId);
|
|
860
|
+
}
|
|
861
|
+
if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
|
|
862
|
+
this.pruneUriWatchRecord(uri);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
/**
|
|
867
|
+
* Drop what `uri` no longer needs: the
|
|
868
|
+
* {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
|
|
869
|
+
* and the whole record once it holds no
|
|
870
|
+
* {@link DataServerUriWatchRecord.releaseBroadcastPending} mark either.
|
|
871
|
+
* Every path that removes a watcher or consumes a mark ends here.
|
|
872
|
+
*/
|
|
873
|
+
protected pruneUriWatchRecord(uri: string): void {
|
|
874
|
+
const record = this.uriWatchRecords.get(uri);
|
|
875
|
+
if (!record || record.watchers.size > 0) {
|
|
704
876
|
return;
|
|
705
877
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
878
|
+
if (record.releaseBroadcastPending) {
|
|
879
|
+
record.fingerprint = undefined;
|
|
880
|
+
record.fingerprintVersion = undefined;
|
|
881
|
+
} else {
|
|
882
|
+
this.uriWatchRecords.delete(uri);
|
|
710
883
|
}
|
|
711
884
|
}
|
|
712
885
|
|
|
713
886
|
/**
|
|
714
|
-
* Canonicalise a URI string for use as a
|
|
715
|
-
*
|
|
716
|
-
*
|
|
717
|
-
*
|
|
887
|
+
* Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
|
|
888
|
+
* shared `DocumentUriPolicy`. Callers may send non-canonical URIs
|
|
889
|
+
* (drive-letter casing, percent-encoding differences, or a symlink path)
|
|
890
|
+
* over the wire; the dispatch side keys by
|
|
718
891
|
* `document.uri.toString()` from `LangiumDocuments`, so writer keys must
|
|
719
892
|
* canonicalise to the same form or events silently fail to deliver.
|
|
720
893
|
* Routing through the seam (rather than a bare `UriUtils.normalize`)
|
|
@@ -724,26 +897,24 @@ export class DataServer<
|
|
|
724
897
|
* LSP head resolves.
|
|
725
898
|
*
|
|
726
899
|
* Adopters can still override for head-specific URI policy by subclassing.
|
|
900
|
+
* The result keys watches only; a document is looked up by its own URI.
|
|
727
901
|
*/
|
|
728
902
|
protected canonicalKey(uri: string): string {
|
|
729
903
|
return this.services.workspace.DocumentUriPolicy.canonicalUri(uri);
|
|
730
904
|
}
|
|
731
905
|
|
|
732
906
|
async getProjects(): Promise<readonly TProject[]> {
|
|
733
|
-
// Pass-through: `ProjectManager<TProject>` already produces `TProject`
|
|
734
|
-
// (the shared services are parameterised over the same generic).
|
|
735
907
|
// The framework reads `id` for registry identity and `dependencies`
|
|
736
908
|
// for the visibility closure; every other field rides on the
|
|
737
909
|
// JSON-RPC envelope as adopter-defined wire metadata.
|
|
738
|
-
return this.services.workspace.ProjectManager.getProjects();
|
|
910
|
+
return this.services.workspace.ProjectManager.getProjects().map(project => this.encodeProject(project));
|
|
739
911
|
}
|
|
740
912
|
|
|
741
913
|
async getProjectForUri(args: GetProjectForUriArgs): Promise<TProject | undefined> {
|
|
742
|
-
//
|
|
743
|
-
//
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
return this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
|
|
914
|
+
// Membership logic belongs to the adopter's `ProjectManager`; the
|
|
915
|
+
// data-server forwards the URI without interpretation.
|
|
916
|
+
const project = this.services.workspace.ProjectManager.getProject(UriUtils.toUri(args.uri));
|
|
917
|
+
return project && this.encodeProject(project);
|
|
747
918
|
}
|
|
748
919
|
|
|
749
920
|
/**
|
|
@@ -763,27 +934,60 @@ export class DataServer<
|
|
|
763
934
|
// (see resolveReferenceServices) and delegate.
|
|
764
935
|
// ============================================================
|
|
765
936
|
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
937
|
+
/**
|
|
938
|
+
* Settle the build before a reference question is answered from the index.
|
|
939
|
+
*
|
|
940
|
+
* A query issued right after a model update otherwise races the rebuild and
|
|
941
|
+
* reads an index missing the symbols it asks about. The cost is not confined
|
|
942
|
+
* to this call: a scope built inside that window is cached, and the build's
|
|
943
|
+
* remaining documents link against it.
|
|
944
|
+
*
|
|
945
|
+
* Waits the source document specifically, but ONLY when one is loaded at
|
|
946
|
+
* that URI: a synthetic source can address a URI with no document (a
|
|
947
|
+
* directory URI, typically), where a per-URI `waitUntil` throws "No document
|
|
948
|
+
* found". Falls back to a global settle, matching the id-based
|
|
949
|
+
* `ElementSource` path.
|
|
950
|
+
*
|
|
951
|
+
* Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
952
|
+
*/
|
|
953
|
+
protected async awaitReferencesLinked(source: ReferenceSource): Promise<void> {
|
|
954
|
+
const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
|
|
775
955
|
const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
|
|
776
|
-
|
|
956
|
+
const stopwatch = this.services.Clock.stopwatch();
|
|
957
|
+
const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
|
|
958
|
+
if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
const elapsedMs = Math.round(stopwatch.elapsedMs);
|
|
962
|
+
// A per-URI wait resolves off a document-phase notification, so a
|
|
963
|
+
// missed one strands a wait on a document that HAS reached the
|
|
964
|
+
// phase. Re-read before failing; the workspace-wide wait has no
|
|
965
|
+
// equivalent reading and can only reject.
|
|
966
|
+
const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
|
|
967
|
+
if (waitUri && document && document.state >= DocumentState.Linked) {
|
|
968
|
+
this.tracer
|
|
969
|
+
.withUri(waitUri.toString())
|
|
970
|
+
.warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
throw referenceSettleTimeoutError(elapsedMs);
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
|
|
977
|
+
await this.awaitReferencesLinked(ctx.source);
|
|
777
978
|
return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
|
|
778
979
|
}
|
|
779
980
|
|
|
780
|
-
async resolveReference
|
|
981
|
+
async resolveReference<TElement extends TransferElement = TransferElement>(
|
|
982
|
+
ref: ReferenceRequest
|
|
983
|
+
): Promise<ReferenceTarget<TElement> | undefined> {
|
|
984
|
+
await this.awaitReferencesLinked(ref.source);
|
|
781
985
|
const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
|
|
782
986
|
if (!resolved) {
|
|
783
987
|
return undefined;
|
|
784
988
|
}
|
|
785
|
-
|
|
786
|
-
return { ...resolved.candidate, element };
|
|
989
|
+
// `TElement` is the caller's claim about the target's type; nothing checks it.
|
|
990
|
+
return { ...resolved.candidate, element: this.encoder.toTransfer(resolved.node) as TElement };
|
|
787
991
|
}
|
|
788
992
|
|
|
789
993
|
async findNextName(args: FindNextNameArgs): Promise<string> {
|
|
@@ -793,15 +997,31 @@ export class DataServer<
|
|
|
793
997
|
// synthetic source — and the create-element flow driving this method is
|
|
794
998
|
// the one that produces directory URIs, on which a bare
|
|
795
999
|
// `getServices(uri)` throws while `findReferenceCandidates` succeeds.
|
|
796
|
-
const
|
|
1000
|
+
const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
|
|
1001
|
+
// Mid-rebuild the names of documents not yet re-indexed are absent from
|
|
1002
|
+
// the taken set, and the caller PERSISTS what it is handed. Nothing
|
|
1003
|
+
// reserves the answer either, so a name is free of the collisions the
|
|
1004
|
+
// index knows about and of nothing else — two callers racing get the same
|
|
1005
|
+
// proposal, which only uniqueness at the write can catch.
|
|
1006
|
+
await this.awaitReferencesLinked(source);
|
|
1007
|
+
const nameProvider = this.resolveReferenceServices(source).NameProvider;
|
|
797
1008
|
const tier = args.tier ?? 'project';
|
|
798
1009
|
if (tier === 'public') {
|
|
799
1010
|
return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
|
|
800
1011
|
}
|
|
801
1012
|
if (tier === 'local') {
|
|
802
|
-
// Document-scoped uniqueness: the document root is the container.
|
|
803
|
-
|
|
804
|
-
|
|
1013
|
+
// Document-scoped uniqueness: the document root is the container. A
|
|
1014
|
+
// URI with no document has nothing to collide with, like a document
|
|
1015
|
+
// with no root.
|
|
1016
|
+
try {
|
|
1017
|
+
const document = await this.modelService.ensureDocumentState(args.uri);
|
|
1018
|
+
return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
|
|
1019
|
+
} catch (error: unknown) {
|
|
1020
|
+
if (this.isMissingDocument(error, args.uri)) {
|
|
1021
|
+
return args.proposal;
|
|
1022
|
+
}
|
|
1023
|
+
throw error;
|
|
1024
|
+
}
|
|
805
1025
|
}
|
|
806
1026
|
const project = this.services.workspace.ProjectManager.getProject(uri);
|
|
807
1027
|
if (!project) {
|
|
@@ -838,67 +1058,32 @@ export class DataServer<
|
|
|
838
1058
|
}
|
|
839
1059
|
|
|
840
1060
|
/**
|
|
841
|
-
* Pick the language that owns a reference source
|
|
1061
|
+
* Pick the language that owns a reference source: the registry's
|
|
1062
|
+
* `getLanguageFor` over the source's declared language, URI and AST type,
|
|
1063
|
+
* with an {@link isElementSource} routed by the document that holds the
|
|
1064
|
+
* element (see {@link findElementDocumentUri}) before its type, and
|
|
1065
|
+
* {@link fallbackReferenceLanguage}, adopter policy, last.
|
|
842
1066
|
*
|
|
843
|
-
*
|
|
844
|
-
*
|
|
845
|
-
*
|
|
846
|
-
* single-language adopters never reach the steps below, and never pay
|
|
847
|
-
* for them.
|
|
848
|
-
* 3. An {@link isElementSource} source carries no URI, so in a
|
|
849
|
-
* multi-language workspace it is routed via the document that holds the
|
|
850
|
-
* element (see {@link findElementDocumentUri}).
|
|
851
|
-
* 4. A source carrying an AST type is routed by that type when exactly one
|
|
852
|
-
* registered grammar can produce it (see
|
|
853
|
-
* {@link resolveReferenceLanguageByType}, over the registry's own type
|
|
854
|
-
* index). This is what resolves a create-element flow's synthetic source
|
|
855
|
-
* on a bare directory URI without asking the adopter.
|
|
856
|
-
* 5. Anything still unresolved falls to {@link fallbackReferenceLanguage},
|
|
857
|
-
* which is adopter policy.
|
|
1067
|
+
* An unregistered declared language falls through rather than failing: the
|
|
1068
|
+
* id crosses the wire, so a client built against a head with one more
|
|
1069
|
+
* grammar would otherwise lose queries the other signals answer.
|
|
858
1070
|
*/
|
|
859
1071
|
protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined {
|
|
860
1072
|
const registry = this.services.ServiceRegistry;
|
|
861
|
-
// `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
|
|
862
|
-
// an extensionless / unregistered URI falls through to the steps below
|
|
863
|
-
// rather than throwing "no services for the extension ''".
|
|
864
|
-
const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
|
|
865
|
-
const byUri = uri && registry.getServicesFor(uri);
|
|
866
|
-
if (byUri) {
|
|
867
|
-
return byUri;
|
|
868
|
-
}
|
|
869
|
-
const all = registry.all;
|
|
870
|
-
if (all.length === 1) {
|
|
871
|
-
return all[0] as HydraniumLanguageServices;
|
|
872
|
-
}
|
|
873
1073
|
if (isElementSource(source)) {
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
1074
|
+
// The index lookup runs only once the cheaper signals abstained.
|
|
1075
|
+
return (
|
|
1076
|
+
registry.getLanguageFor({}) ??
|
|
1077
|
+
registry.getLanguageFor({ target: this.findElementDocumentUri(source), type: source.type }) ??
|
|
1078
|
+
this.fallbackReferenceLanguage(source)
|
|
1079
|
+
);
|
|
879
1080
|
}
|
|
880
|
-
const
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
* {@link isSyntheticSource}'s `type` (the transient node being created) or an
|
|
887
|
-
* {@link isElementSource}'s optional narrowing `type`.
|
|
888
|
-
*
|
|
889
|
-
* Answers only when EXACTLY ONE registered grammar can produce the type.
|
|
890
|
-
* Several can when the type comes from a grammar both import, and then the
|
|
891
|
-
* type genuinely does not identify a language — that is a fall-through to
|
|
892
|
-
* adopter policy, not a coin toss. Note this asks which grammar can *produce*
|
|
893
|
-
* the type, not which mentions it: a grammar that merely cross-references a
|
|
894
|
-
* type can never hold a node of it.
|
|
895
|
-
*/
|
|
896
|
-
protected resolveReferenceLanguageByType(source: ReferenceSource): HydraniumLanguageServices | undefined {
|
|
897
|
-
const type = isSyntheticSource(source) ? source.type : isElementSource(source) ? source.type : undefined;
|
|
898
|
-
// The registry owns the type index — it is the one place that knows when
|
|
899
|
-
// the registered set changed, so unlike a private memo here it cannot go
|
|
900
|
-
// stale on a language registered after the first lookup.
|
|
901
|
-
return type ? this.services.ServiceRegistry.soleServicesByType(type) : undefined;
|
|
1081
|
+
const hint = isSyntheticSource(source)
|
|
1082
|
+
? { languageId: source.language, target: source.uri, type: source.type }
|
|
1083
|
+
: isDocumentSource(source)
|
|
1084
|
+
? { target: source.uri }
|
|
1085
|
+
: {};
|
|
1086
|
+
return registry.getLanguageFor(hint) ?? this.fallbackReferenceLanguage(source);
|
|
902
1087
|
}
|
|
903
1088
|
|
|
904
1089
|
/**
|
|
@@ -908,15 +1093,14 @@ export class DataServer<
|
|
|
908
1093
|
* disambiguates names that repeat across types (honouring grammar
|
|
909
1094
|
* subtyping through `AstReflection.isSubtype`).
|
|
910
1095
|
*
|
|
911
|
-
* Only reached
|
|
912
|
-
*
|
|
913
|
-
* step 2.
|
|
1096
|
+
* Only reached in a multi-language workspace, once the declared language
|
|
1097
|
+
* and the URI have abstained.
|
|
914
1098
|
*
|
|
915
1099
|
* Abstains when the name matches elements in more than one DOCUMENT — the
|
|
916
1100
|
* index spans every language and is filled in build order, so "the
|
|
917
|
-
* first match" would be file-watch order rather than an answer.
|
|
918
|
-
* then falls through to the type
|
|
919
|
-
*
|
|
1101
|
+
* first match" would be file-watch order rather than an answer. Routing
|
|
1102
|
+
* then falls through to the element's type, which abstains on ties in the
|
|
1103
|
+
* same way, and finally to adopter policy.
|
|
920
1104
|
*/
|
|
921
1105
|
protected findElementDocumentUri(source: ElementSource): URI | undefined {
|
|
922
1106
|
const matches = this.services.workspace.IndexManager.getElementsByName(source.name, source.type);
|
|
@@ -951,61 +1135,164 @@ export class DataServer<
|
|
|
951
1135
|
// Internal plumbing
|
|
952
1136
|
// ============================================================
|
|
953
1137
|
|
|
1138
|
+
/**
|
|
1139
|
+
* Whether `error`, from waiting on `uri`'s document, means that `uri` has
|
|
1140
|
+
* no document: a URI with neither a file nor text builds nothing, and
|
|
1141
|
+
* Langium's wait after the build rejects for want of one, with a
|
|
1142
|
+
* `ServerCancelled` response error. Any other failure, such as a read
|
|
1143
|
+
* that fails before a document is registered, a cancelled wait or a
|
|
1144
|
+
* `ReentrantWriteLockError`, is the caller's to see.
|
|
1145
|
+
*/
|
|
1146
|
+
protected isMissingDocument(error: unknown, uri: string): boolean {
|
|
1147
|
+
return isResponseError(error) && error.code === SERVER_CANCELLED && this.modelService.getDocument(uri) === undefined;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
954
1150
|
/**
|
|
955
1151
|
* Build a {@link TransferDocument} envelope from the current document state,
|
|
956
1152
|
* delegating root + diagnostic encoding to {@link encoder} (see
|
|
957
|
-
* `TransferEncoder.toTransferDocument` for the walk).
|
|
958
|
-
*
|
|
959
|
-
*
|
|
960
|
-
* `Record<string, TransferElement>` at the framework-default level, and an
|
|
961
|
-
* adopter supplying a typed-overlay encoder narrows the runtime shape to
|
|
962
|
-
* its wire types. The cast on the return is where that invariant — the
|
|
963
|
-
* adopter's `TTransfer` matches its encoder's overlay — is asserted, at a
|
|
964
|
-
* single boundary point rather than spread across the callers.
|
|
1153
|
+
* `TransferEncoder.toTransferDocument` for the walk). `fingerprint` is the
|
|
1154
|
+
* caller's {@link computeDocumentFingerprint} of that same state, which
|
|
1155
|
+
* spares hashing it twice.
|
|
965
1156
|
*/
|
|
966
|
-
protected envelope(uri: URI): TransferDocument<TTransfer, TDiagnostic> {
|
|
1157
|
+
protected envelope(uri: URI, fingerprint?: string): TransferDocument<TTransfer, TDiagnostic> {
|
|
967
1158
|
// Resolve through the model service's canonicalizing gateway rather than
|
|
968
1159
|
// reaching into `LangiumDocuments` directly, so a divergent (symlink) URI
|
|
969
1160
|
// still finds the document the build keys by its real path — and so the
|
|
970
1161
|
// data-server never has to remember to canonicalize this lookup itself.
|
|
971
1162
|
const document = this.modelService.getDocument(uri.toString());
|
|
972
|
-
if (!document) {
|
|
1163
|
+
if (!document || this.services.workspace.ModelLedger.isPlaceholder(document.parseResult.value)) {
|
|
973
1164
|
// No document — a shaped envelope rather than a throw, so the caller
|
|
974
|
-
// decides policy at its own layer; `
|
|
1165
|
+
// decides policy at its own layer; `model` is optional on the envelope
|
|
975
1166
|
// so the compiler forces that decision. Adopters preferring to throw
|
|
976
|
-
// override `envelope`.
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
version: 0,
|
|
980
|
-
root: undefined,
|
|
981
|
-
diagnostics: [] as TDiagnostic[]
|
|
982
|
-
};
|
|
1167
|
+
// override `envelope`. The builder's unparsed placeholder is no
|
|
1168
|
+
// document either: its root parses no text.
|
|
1169
|
+
return TransferDocument.absent<TTransfer, TDiagnostic>(uri.toString());
|
|
983
1170
|
}
|
|
984
|
-
|
|
1171
|
+
const encoded = this.encoder.toTransferDocument(document);
|
|
1172
|
+
return this.withServerState(encoded, fingerprint ?? this.computeDocumentFingerprint(document.parseResult.value, encoded));
|
|
985
1173
|
}
|
|
986
1174
|
|
|
987
1175
|
/**
|
|
988
|
-
*
|
|
989
|
-
*
|
|
990
|
-
*
|
|
991
|
-
*
|
|
1176
|
+
* The transfer document a request answers with for `astDocument`, its model
|
|
1177
|
+
* hashed and the text stamped on it by {@link withServerState}. Every
|
|
1178
|
+
* document a request answers with goes through here, so none goes out
|
|
1179
|
+
* without them.
|
|
992
1180
|
*/
|
|
993
|
-
protected
|
|
994
|
-
this.
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
1181
|
+
protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
|
|
1182
|
+
const encoded = this.encoder.astDocumentToTransferDocument(astDocument);
|
|
1183
|
+
return this.withServerState(encoded, this.computeDocumentFingerprint(astDocument.root, encoded));
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/**
|
|
1187
|
+
* The project a client receives for `project`, unchanged by default. Every
|
|
1188
|
+
* project a request answers with or a change notification carries goes
|
|
1189
|
+
* through here, so a field derived for clients cannot miss one path. The
|
|
1190
|
+
* result crosses as JSON, so a value a client reads goes in a data field,
|
|
1191
|
+
* not a getter.
|
|
1192
|
+
*/
|
|
1193
|
+
protected encodeProject(project: TProject): TProject {
|
|
1194
|
+
return project;
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
/**
|
|
1198
|
+
* `encoded` with `hash` on its model and the text the server holds for it:
|
|
1199
|
+
* the store's while it holds the document, the build's otherwise. The text
|
|
1200
|
+
* is read when the document is sent rather than kept with the build: a save
|
|
1201
|
+
* changes `text.dirty` without a rebuild, and the store's text moves on before
|
|
1202
|
+
* the build that follows it.
|
|
1203
|
+
*/
|
|
1204
|
+
protected withServerState(
|
|
1205
|
+
encoded: EncodedTransferDocument<TransferElement, TDiagnostic>,
|
|
1206
|
+
hash: string
|
|
1207
|
+
): TransferDocument<TTransfer, TDiagnostic> {
|
|
1208
|
+
const text = this.serverTextState(encoded.uri);
|
|
1209
|
+
if (text && text.version > encoded.model.version) {
|
|
1210
|
+
this.tracer.withUri(encoded.uri).debug(`Send a model behind its text: model v${encoded.model.version} / text v${text.version}`);
|
|
1211
|
+
}
|
|
1212
|
+
return {
|
|
1213
|
+
uri: encoded.uri,
|
|
1214
|
+
// The encoder returns the structural base; `TTransfer` is the adopter's
|
|
1215
|
+
// declaration of the roots its languages produce, and nothing checks it.
|
|
1216
|
+
model: { ...encoded.model, hash } as TransferModelSnapshot<TTransfer, TDiagnostic>,
|
|
1217
|
+
...(text ? { text } : {})
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
/**
|
|
1222
|
+
* The text the server holds for `uri`, as every envelope and a watch's
|
|
1223
|
+
* answer carry it: the store's while it holds the document, the build's
|
|
1224
|
+
* otherwise, and none for a document it has neither of.
|
|
1225
|
+
*/
|
|
1226
|
+
protected serverTextState(uri: string): TextState | undefined {
|
|
1227
|
+
return this.services.workspace.TextDocuments.textState(uri) ?? this.builtTextState(uri);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/**
|
|
1231
|
+
* The text a build read for a document the store never held, which is
|
|
1232
|
+
* clean: the store holds every text a client gave it.
|
|
1233
|
+
*/
|
|
1234
|
+
protected builtTextState(uri: string): TextState | undefined {
|
|
1235
|
+
const textDocument = this.modelService.getDocument(uri)?.textDocument;
|
|
1236
|
+
return textDocument && { version: textDocument.version, hash: textHash(textDocument.getText()), dirty: false };
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
/**
|
|
1240
|
+
* Follow every document at the configured
|
|
1241
|
+
* {@link DataServerOptions.subscriptionPhase}, once per connection rather
|
|
1242
|
+
* than once per watch, so the cost stays flat in the number of watches.
|
|
1243
|
+
*/
|
|
1244
|
+
protected subscribeToModelUpdates(): void {
|
|
1245
|
+
const phase = this.options.subscriptionPhase;
|
|
1246
|
+
this.disposables.push(this.modelService.onModelUpdated(event => this.dispatchPhaseEvent(event), { phase }));
|
|
1247
|
+
// One message per build rather than one per document.
|
|
1248
|
+
this.disposables.push(this.modelService.onModelsBuilt(event => this.dispatchBuiltEvent(event.uris), { phase }));
|
|
999
1249
|
}
|
|
1000
1250
|
|
|
1001
1251
|
/**
|
|
1002
|
-
*
|
|
1003
|
-
*
|
|
1004
|
-
*
|
|
1005
|
-
*
|
|
1006
|
-
*
|
|
1252
|
+
* Report the documents that reached {@link DataServerOptions.subscriptionPhase}
|
|
1253
|
+
* and that NOBODY on this
|
|
1254
|
+
* connection is watching — the ones a client was not told about through
|
|
1255
|
+
* {@link dispatchPhaseEvent}, which is gated per URI.
|
|
1256
|
+
*
|
|
1257
|
+
* **The gap this closes is the one no other source can observe.** A document
|
|
1258
|
+
* the client watches, it hears about already. A file changed on disk, the
|
|
1259
|
+
* host's own filesystem watcher reports — and on a browser host, where the
|
|
1260
|
+
* workspace lives behind this head, an external change cannot happen at all.
|
|
1261
|
+
* What is left, and what nothing outside the server can see, is a document
|
|
1262
|
+
* rebuilt because something it DEPENDS ON changed: its file never changed, so
|
|
1263
|
+
* a filesystem watcher is silent by construction, and it has no subscriber, so
|
|
1264
|
+
* the update channel is silent by design. A consumer displaying data derived
|
|
1265
|
+
* from that document — a tree label, a decorator — otherwise goes stale with
|
|
1266
|
+
* no signal from any source, and repairs itself the moment someone opens the
|
|
1267
|
+
* file to investigate, which is what makes it expensive to diagnose later.
|
|
1007
1268
|
*
|
|
1008
|
-
*
|
|
1269
|
+
* Payload-free on purpose: URIs only, so a client re-reads what it displays
|
|
1270
|
+
* rather than being handed transfer documents it did not ask for. That is the
|
|
1271
|
+
* property the watcher gate protects, and it is preserved here by
|
|
1272
|
+
* carrying no document rather than by gating the message.
|
|
1273
|
+
*
|
|
1274
|
+
* Quiet in the common case. Editing a document that an editor has open leaves
|
|
1275
|
+
* that URI watched and therefore out of this set, so a build with no
|
|
1276
|
+
* dependents produces nothing at all, and workspace initialisation produces
|
|
1277
|
+
* nothing because it does not build to this phase. The ceiling is a
|
|
1278
|
+
* whole-workspace rebuild at the subscription phase: one message, URIs only.
|
|
1279
|
+
*/
|
|
1280
|
+
protected dispatchBuiltEvent(built: readonly CanonicalUri[]): void {
|
|
1281
|
+
const uris = built.map(uri => this.canonicalKey(uri)).filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
|
|
1282
|
+
if (uris.length === 0) {
|
|
1283
|
+
return;
|
|
1284
|
+
}
|
|
1285
|
+
this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
|
|
1286
|
+
this.clientProxy.onDocumentsBuilt({ uris });
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
/**
|
|
1290
|
+
* Follow every save so a single `onDocumentSaved` wire notification fires
|
|
1291
|
+
* for ANY save of a subscribed URI — regardless of whether the save
|
|
1292
|
+
* originated from the data-server's RPC `saveModelDocument`, the LSP head's
|
|
1293
|
+
* text-editor save, or any other client.
|
|
1294
|
+
*
|
|
1295
|
+
* Architectural symmetry with {@link subscribeToModelUpdates}: every
|
|
1009
1296
|
* subscribed client sees every state change to documents they care about,
|
|
1010
1297
|
* regardless of which client triggered it. Firing `onDocumentSaved` only
|
|
1011
1298
|
* from the data-server's own RPC path is a bug, not an optimisation: an
|
|
@@ -1013,41 +1300,115 @@ export class DataServer<
|
|
|
1013
1300
|
* clients, which never clear their dirty state.
|
|
1014
1301
|
*/
|
|
1015
1302
|
protected subscribeToTextDocumentSaves(): void {
|
|
1016
|
-
this.disposables.push(this.
|
|
1303
|
+
this.disposables.push(this.modelService.onModelSaved(event => this.dispatchSaveEvent(event)));
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
/** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
|
|
1307
|
+
protected subscribeToDirtyChanges(): void {
|
|
1308
|
+
this.disposables.push(this.modelService.onDirtyChanged(event => this.dispatchDirtyEvent(event)));
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
/**
|
|
1312
|
+
* Send a dirty flip to the connection, gated on the URI's watchers as
|
|
1313
|
+
* {@link dispatchSaveEvent} is: the answer at any one moment travels on
|
|
1314
|
+
* every document sent, so a client that watches nothing reads it there.
|
|
1315
|
+
*/
|
|
1316
|
+
protected dispatchDirtyEvent(event: ModelDirtyChangedEvent): void {
|
|
1317
|
+
const uri = this.canonicalKey(event.uri);
|
|
1318
|
+
if (this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
1319
|
+
this.clientProxy.onDocumentDirtyChanged({ uri, text: event.text });
|
|
1320
|
+
}
|
|
1017
1321
|
}
|
|
1018
1322
|
|
|
1019
1323
|
/**
|
|
1020
|
-
* Mark the
|
|
1021
|
-
*
|
|
1022
|
-
*
|
|
1023
|
-
*
|
|
1324
|
+
* Mark each document the store releases, so {@link dispatchPhaseEvent}
|
|
1325
|
+
* broadcasts the build that follows even without a watcher. By default
|
|
1326
|
+
* that build reverts the document to its disk content, discarding unsaved
|
|
1327
|
+
* in-session edits, and the last close typically also
|
|
1328
|
+
* removed the last watcher: without the broadcast, a consumer that only
|
|
1329
|
+
* ever fetches via `getModelDocument` keeps showing the discarded state.
|
|
1330
|
+
* The broadcast is de-duplicated against the fingerprint while a watcher
|
|
1331
|
+
* holds one, so a close whose disk state equals the last emitted state
|
|
1332
|
+
* stays silent; with no watcher there is no fingerprint, and every release
|
|
1333
|
+
* build is sent. The first build after the release consumes the mark, and
|
|
1334
|
+
* goes out as the release unless it is stamped past the version a client
|
|
1335
|
+
* opened the document at again: a client's write or an integrity repair
|
|
1336
|
+
* that rides it keeps its author.
|
|
1337
|
+
*
|
|
1338
|
+
* A release, not the close itself: a document whose last client lost its
|
|
1339
|
+
* connection is released only once the release grace runs out, or when
|
|
1340
|
+
* another client opens it meanwhile, and not at all when a client lost
|
|
1341
|
+
* from it opens it again within its own grace.
|
|
1024
1342
|
*/
|
|
1025
|
-
protected
|
|
1026
|
-
const textDocuments = this.services.workspace.TextDocuments;
|
|
1343
|
+
protected subscribeToModelReleases(): void {
|
|
1027
1344
|
this.disposables.push(
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1345
|
+
this.modelService.onModelReleased(event => {
|
|
1346
|
+
const uri = this.canonicalKey(event.uri);
|
|
1347
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
|
|
1348
|
+
record.releaseBroadcastPending = true;
|
|
1349
|
+
this.uriWatchRecords.set(uri, record);
|
|
1350
|
+
this.tracer.withUri(uri).debug('Release marked: the first build after it is broadcast, watched or not');
|
|
1032
1351
|
})
|
|
1033
1352
|
);
|
|
1034
1353
|
}
|
|
1035
1354
|
|
|
1036
|
-
/**
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1355
|
+
/**
|
|
1356
|
+
* Fan out a deletion for each removed URI, to EVERY client on the connection
|
|
1357
|
+
* rather than only to the ones watching that URI.
|
|
1358
|
+
*
|
|
1359
|
+
* **Deliberately ungated, where {@link dispatchPhaseEvent} and
|
|
1360
|
+
* {@link dispatchSaveEvent} are gated.** Those two carry a built document and
|
|
1361
|
+
* fire on every build, so the watcher gate is what keeps bandwidth
|
|
1362
|
+
* proportional to what a client asked for. A deletion is neither: it is one
|
|
1363
|
+
* URI, it is rare, and it reports the workspace's STRUCTURE rather than a
|
|
1364
|
+
* document's content. Gating it forces any consumer that displays the
|
|
1365
|
+
* workspace — a model tree, a file decorator — to learn about disappearances
|
|
1366
|
+
* from a filesystem watcher instead, which a client hosted in a browser has
|
|
1367
|
+
* no way to run: its workspace lives behind the head. A client that does not
|
|
1368
|
+
* care filters on the URI, which costs it a comparison.
|
|
1369
|
+
*
|
|
1370
|
+
* The precedent is the release broadcast (see
|
|
1371
|
+
* {@link subscribeToModelReleases}), where the same judgement was already made
|
|
1372
|
+
* in the other direction: a transition that matters enough is delivered
|
|
1373
|
+
* without a subscription.
|
|
1374
|
+
*
|
|
1375
|
+
* A deletion is announced before the build that follows it, so this goes
|
|
1376
|
+
* out ahead of the `'rebuilt'` events for the dependents whose references
|
|
1377
|
+
* the deletion just broke.
|
|
1378
|
+
*
|
|
1379
|
+
* The URI's fingerprint and release mark are dropped: they describe a
|
|
1380
|
+
* document that no longer exists. A kept fingerprint is adopted as the
|
|
1381
|
+
* baseline and suppresses the first emit after the file returns with its
|
|
1382
|
+
* previous content.
|
|
1383
|
+
*
|
|
1384
|
+
* The watchers SURVIVE: a recreated file resumes delivering to them with no
|
|
1385
|
+
* re-subscription, and a client that answers the deletion by closing
|
|
1386
|
+
* releases the watch through `closeModelDocument` anyway. A session that
|
|
1387
|
+
* deleted the document has its own released by {@link deleteModelDocument}.
|
|
1388
|
+
*/
|
|
1389
|
+
protected dispatchDeleteEvent(event: ModelDeletedEvent): void {
|
|
1390
|
+
const uri = this.canonicalKey(event.uri);
|
|
1391
|
+
const record = this.uriWatchRecords.get(uri);
|
|
1392
|
+
if (record) {
|
|
1393
|
+
record.fingerprint = undefined;
|
|
1394
|
+
record.fingerprintVersion = undefined;
|
|
1395
|
+
record.releaseBroadcastPending = undefined;
|
|
1396
|
+
record.sentVersion = undefined;
|
|
1397
|
+
this.pruneUriWatchRecord(uri);
|
|
1398
|
+
}
|
|
1399
|
+
this.clientProxy.onDocumentDeleted({ uri, sourceClientId: event.sourceClientId, sequence: ++this.eventSequence });
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/** Fan out a save event for the document's URI, gated on the URI's watchers. */
|
|
1403
|
+
protected dispatchSaveEvent(event: AstDocumentSavedEvent<AstNode>): void {
|
|
1043
1404
|
const uri = this.canonicalKey(event.document.uri);
|
|
1044
|
-
if (!this.
|
|
1405
|
+
if (!this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
1045
1406
|
return;
|
|
1046
1407
|
}
|
|
1047
|
-
const response = this.envelope(UriUtils.toUri(uri));
|
|
1408
|
+
const response = this.envelope(UriUtils.toUri(event.document.uri));
|
|
1048
1409
|
const wireEvent: TransferDocumentSavedEvent<TTransfer, TDiagnostic> = {
|
|
1049
1410
|
document: response,
|
|
1050
|
-
sourceClientId: event.
|
|
1411
|
+
sourceClientId: event.sourceClientId
|
|
1051
1412
|
};
|
|
1052
1413
|
this.clientProxy.onDocumentSaved(wireEvent);
|
|
1053
1414
|
}
|
|
@@ -1061,116 +1422,115 @@ export class DataServer<
|
|
|
1061
1422
|
* out to multiple local subscribers with an `Emitter<T>` — the
|
|
1062
1423
|
* framework deliberately does NOT promise multi-listener semantics.
|
|
1063
1424
|
*
|
|
1064
|
-
*
|
|
1065
|
-
*
|
|
1066
|
-
*
|
|
1067
|
-
*
|
|
1068
|
-
*
|
|
1069
|
-
*
|
|
1070
|
-
*
|
|
1425
|
+
* An event for a URI no client watches is NOT sent over the wire, so
|
|
1426
|
+
* bandwidth scales with watched URIs rather than with phase events; a
|
|
1427
|
+
* pending release mark is the exception (see
|
|
1428
|
+
* {@link subscribeToModelReleases}).
|
|
1429
|
+
*
|
|
1430
|
+
* An event for a rebuild with no observable change since the last emit is
|
|
1431
|
+
* suppressed against the URI's fingerprint and the version it was taken at;
|
|
1432
|
+
* a new version with the same fingerprint goes out with the same
|
|
1433
|
+
* `model.hash`, so a watcher still learns the version. Such rebuilds are routine: a
|
|
1434
|
+
* second client attaching to an open document makes
|
|
1435
|
+
* `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
|
|
1436
|
+
* to re-trigger the build, and Langium rebuilds a document when a
|
|
1437
|
+
* dependency changes even if its diagnostics come out the same. Sent at a
|
|
1438
|
+
* version this head has not sent, they reach watchers as `'changed'`, and a
|
|
1439
|
+
* watcher that reads `'changed'` as another client's write and resets its
|
|
1440
|
+
* root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
|
|
1441
|
+
* fingerprint, so the first event after a watch is de-duplicated against
|
|
1442
|
+
* the state the watcher just fetched; it goes with the last watcher, so the
|
|
1443
|
+
* next first watch re-baselines rather than adopting a stale digest. A
|
|
1444
|
+
* digest keeps its memory constant in document size; see
|
|
1445
|
+
* {@link computeDocumentFingerprint} for the inputs.
|
|
1071
1446
|
*/
|
|
1072
|
-
protected dispatchPhaseEvent(
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
// A pending revert mark is deliberately NOT consumed here: the
|
|
1078
|
-
// follow-up build re-fires this phase and broadcasts then.
|
|
1447
|
+
protected dispatchPhaseEvent(event: ModelUpdatedEvent<AstNode>): void {
|
|
1448
|
+
const uri = this.canonicalKey(event.document.uri);
|
|
1449
|
+
const record = this.uriWatchRecords.get(uri);
|
|
1450
|
+
const afterRelease = record?.releaseBroadcastPending === true;
|
|
1451
|
+
if (!record || (record.watchers.size === 0 && !afterRelease)) {
|
|
1079
1452
|
return;
|
|
1080
1453
|
}
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1454
|
+
if (afterRelease) {
|
|
1455
|
+
// Consumed even when watchers exist — the regular dispatch below
|
|
1456
|
+
// serves them, and the mark's attribution is more precise than the
|
|
1457
|
+
// post-close unknown client the manager's attribution would yield.
|
|
1458
|
+
// With no watcher the record goes now, so the fingerprint written
|
|
1459
|
+
// below lands on a detached record and the next first watch
|
|
1460
|
+
// re-baselines instead of adopting it.
|
|
1461
|
+
record.releaseBroadcastPending = undefined;
|
|
1462
|
+
this.pruneUriWatchRecord(uri);
|
|
1463
|
+
}
|
|
1464
|
+
// The encoder reads the built document, which the event's holds for this
|
|
1465
|
+
// synchronous run.
|
|
1466
|
+
const document = this.modelService.getDocument(event.document.uri);
|
|
1467
|
+
if (!document) {
|
|
1088
1468
|
return;
|
|
1089
1469
|
}
|
|
1090
|
-
const fingerprint = this.computeDocumentFingerprint(document);
|
|
1091
|
-
|
|
1470
|
+
const fingerprint = this.computeDocumentFingerprint(document.parseResult.value, this.encoder.toTransferDocument(document));
|
|
1471
|
+
const stamped = this.services.workspace.ModelLedger.versionOf(document.parseResult.value);
|
|
1472
|
+
if (record.fingerprint === fingerprint && record.fingerprintVersion === stamped) {
|
|
1092
1473
|
// A rebuild that produced no observable change since the last emit —
|
|
1093
1474
|
// suppressed so RPC subscribers don't see a no-op broadcast. Logged at
|
|
1094
1475
|
// debug so a *needed* re-broadcast wrongly suppressed by this dedup
|
|
1095
1476
|
// (the failure mode the fingerprint strategy must avoid) is visible.
|
|
1096
|
-
this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${
|
|
1477
|
+
this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${stamped}: fingerprint and version unchanged`);
|
|
1097
1478
|
return;
|
|
1098
1479
|
}
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1480
|
+
record.fingerprint = fingerprint;
|
|
1481
|
+
record.fingerprintVersion = stamped;
|
|
1482
|
+
// The event's attribution, so this head names the same client as the
|
|
1483
|
+
// in-process heads do for one build, except for a version this head
|
|
1484
|
+
// already sent; see `DataServerUriWatchRecord.sentVersion`.
|
|
1485
|
+
const version = this.modelService.isOpen(event.document.uri) ? document.textDocument.version : undefined;
|
|
1486
|
+
const { reason, sourceClientId } =
|
|
1487
|
+
version !== undefined && record.sentVersion === version
|
|
1488
|
+
? { reason: 'rebuilt' as const, sourceClientId: UNKNOWN_CLIENT_ID }
|
|
1489
|
+
: event;
|
|
1490
|
+
record.sentVersion = version;
|
|
1491
|
+
// The stamp, not the live version: a write after the build's parse moves
|
|
1492
|
+
// only the latter. At the opened version too, which a reopen with the
|
|
1493
|
+
// released text keeps.
|
|
1494
|
+
const openedVersion = afterRelease ? this.modelService.openedVersion(event.document.uri) : undefined;
|
|
1495
|
+
const releaseBuild = afterRelease && (openedVersion === undefined || stamped <= openedVersion);
|
|
1496
|
+
const wireEvent: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> = {
|
|
1497
|
+
document: this.envelope(document.uri, fingerprint),
|
|
1498
|
+
sourceClientId: releaseBuild ? DOCUMENT_RELEASE_CLIENT_ID : sourceClientId,
|
|
1499
|
+
reason,
|
|
1500
|
+
sequence: ++this.eventSequence
|
|
1104
1501
|
};
|
|
1502
|
+
const mark = afterRelease ? `, release mark: opened v${openedVersion ?? '-'}, attributed ${sourceClientId}` : '';
|
|
1105
1503
|
this.tracer
|
|
1106
1504
|
.withUri(uri)
|
|
1107
|
-
.debug(`Emit onDocumentUpdated v${
|
|
1108
|
-
this.clientProxy.onDocumentUpdated(
|
|
1505
|
+
.debug(`Emit onDocumentUpdated v${stamped} (reason=${wireEvent.reason}, sourceClientId=${wireEvent.sourceClientId}${mark})`);
|
|
1506
|
+
this.clientProxy.onDocumentUpdated(wireEvent);
|
|
1109
1507
|
}
|
|
1110
1508
|
|
|
1111
1509
|
/**
|
|
1112
|
-
* Fingerprint of the
|
|
1113
|
-
* `onDocumentUpdated` emissions
|
|
1114
|
-
*
|
|
1115
|
-
* {@link
|
|
1510
|
+
* Fingerprint of the snapshot `root` and its encoding `encoded`, used to
|
|
1511
|
+
* de-dup `onDocumentUpdated` emissions and sent as every document's
|
|
1512
|
+
* `model.hash`, so it must not depend on the version or on live state. The
|
|
1513
|
+
* {@link FingerprintStrategy} option selects what is hashed (default
|
|
1514
|
+
* `'transfer-document'` — see the type).
|
|
1116
1515
|
*
|
|
1117
|
-
*
|
|
1118
|
-
*
|
|
1119
|
-
*
|
|
1120
|
-
* `envelope` share a single encode walk.
|
|
1516
|
+
* {@link TransferEncoder.toTransferDocument} is cached per build, so within
|
|
1517
|
+
* one phase event the fingerprint and the subsequently-emitted `envelope`
|
|
1518
|
+
* share a single encode walk.
|
|
1121
1519
|
*
|
|
1122
1520
|
* Wrapped in {@link Tracer.time} against {@link FINGERPRINT_LOG_AFTER_MS}.
|
|
1123
1521
|
*/
|
|
1124
|
-
protected computeDocumentFingerprint(
|
|
1125
|
-
return this.tracer
|
|
1126
|
-
|
|
1127
|
-
(
|
|
1128
|
-
|
|
1522
|
+
protected computeDocumentFingerprint(root: AstNode, encoded: EncodedTransferDocument<TransferElement, TDiagnostic>): string {
|
|
1523
|
+
return this.tracer
|
|
1524
|
+
.withUri(encoded.uri)
|
|
1525
|
+
.time(
|
|
1526
|
+
'Compute fingerprint',
|
|
1527
|
+
() =>
|
|
1129
1528
|
this.options.fingerprintStrategy === 'text-diagnostics'
|
|
1130
|
-
? textDiagnosticsFingerprint(
|
|
1131
|
-
: transferDocumentFingerprint(
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
'debug',
|
|
1136
|
-
{ logAfterMs: FINGERPRINT_LOG_AFTER_MS }
|
|
1137
|
-
);
|
|
1138
|
-
}
|
|
1139
|
-
|
|
1140
|
-
/**
|
|
1141
|
-
* Extra inputs folded into {@link computeDocumentFingerprint} alongside the
|
|
1142
|
-
* chosen {@link FingerprintStrategy}. Default: none. Override to contribute a
|
|
1143
|
-
* signal that lives outside the document's text / root / diagnostics — each
|
|
1144
|
-
* entry need only be stable across equivalent emissions and
|
|
1145
|
-
* JSON-serialisable.
|
|
1146
|
-
*/
|
|
1147
|
-
protected additionalFingerprintInputs(_document: LangiumDocument): readonly unknown[] {
|
|
1148
|
-
return [];
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
/**
|
|
1152
|
-
* Discriminate the reason for a phase-event-driven update notification.
|
|
1153
|
-
* Uses the most recent `DocumentBuilder.onUpdate` snapshot:
|
|
1154
|
-
* - URI in the `deleted` list → `'deleted'`
|
|
1155
|
-
* - URI in the `changed` list → `'changed'` (the URI was passed to
|
|
1156
|
-
* `documentBuilder.update(changed, deleted)`, which spans `didChange`
|
|
1157
|
-
* text-document events and programmatic `update([uri], [])` calls).
|
|
1158
|
-
* - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
|
|
1159
|
-
* because something it depends on changed; its own text wasn't flagged).
|
|
1160
|
-
*
|
|
1161
|
-
* `'saved'` is NOT emitted from this code path — saves take the dedicated
|
|
1162
|
-
* `DataClientProtocol.onDocumentSaved` channel; adopters that want a
|
|
1163
|
-
* unified update stream synthesise `'saved'` in their bridge layer.
|
|
1164
|
-
*/
|
|
1165
|
-
protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'] {
|
|
1166
|
-
const last = this.lastBuildUpdate;
|
|
1167
|
-
if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
|
|
1168
|
-
return 'deleted';
|
|
1169
|
-
}
|
|
1170
|
-
if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
|
|
1171
|
-
return 'changed';
|
|
1172
|
-
}
|
|
1173
|
-
return 'rebuilt';
|
|
1529
|
+
? textDiagnosticsFingerprint(this.services.workspace.ModelLedger.textOf(root), encoded.model)
|
|
1530
|
+
: transferDocumentFingerprint(encoded.model),
|
|
1531
|
+
'debug',
|
|
1532
|
+
{ logAfterMs: FINGERPRINT_LOG_AFTER_MS }
|
|
1533
|
+
);
|
|
1174
1534
|
}
|
|
1175
1535
|
|
|
1176
1536
|
/**
|
|
@@ -1196,40 +1556,38 @@ export class DataServer<
|
|
|
1196
1556
|
/**
|
|
1197
1557
|
* Fan one internal {@link ProjectChangeEvent} out to per-project wire
|
|
1198
1558
|
* notifications. Each `removed` entry pairs the id with the pre-removal
|
|
1199
|
-
* snapshot needed for the `'removed'` wire payload.
|
|
1559
|
+
* snapshot needed for the `'removed'` wire payload. A project whose
|
|
1560
|
+
* {@link encodeProject} throws is logged and skipped, so the rest of the
|
|
1561
|
+
* batch still reaches the client.
|
|
1200
1562
|
*/
|
|
1201
1563
|
protected dispatchProjectChangeEvent(event: ProjectChangeEvent<TProject>): void {
|
|
1564
|
+
const send = (project: TProject, reason: ProjectChangeReason): void => {
|
|
1565
|
+
let encoded: TProject;
|
|
1566
|
+
try {
|
|
1567
|
+
encoded = this.encodeProject(project);
|
|
1568
|
+
} catch (error: unknown) {
|
|
1569
|
+
this.tracer.error(`Project ${project.id} not sent as ${reason}: encodeProject threw: ${describeErrorWithStack(error)}`);
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
this.clientProxy.onProjectsChanged({ project: encoded, reason });
|
|
1573
|
+
};
|
|
1202
1574
|
for (const id of event.added) {
|
|
1203
1575
|
const project = this.services.workspace.ProjectManager.getProjectById(id);
|
|
1204
1576
|
if (project) {
|
|
1205
|
-
|
|
1577
|
+
send(project, 'added');
|
|
1206
1578
|
}
|
|
1207
1579
|
}
|
|
1208
1580
|
for (const id of event.updated) {
|
|
1209
1581
|
const project = this.services.workspace.ProjectManager.getProjectById(id);
|
|
1210
1582
|
if (project) {
|
|
1211
|
-
|
|
1583
|
+
send(project, 'updated');
|
|
1212
1584
|
}
|
|
1213
1585
|
}
|
|
1214
1586
|
for (const entry of event.removed) {
|
|
1215
|
-
|
|
1587
|
+
send(entry.snapshot, 'removed');
|
|
1216
1588
|
}
|
|
1217
1589
|
}
|
|
1218
1590
|
|
|
1219
|
-
/**
|
|
1220
|
-
* Resolve the wire-level `sourceClientId` for `document`'s events — the client
|
|
1221
|
-
* that authored its current version, from the version-author history on
|
|
1222
|
-
* `HydraniumTextDocuments`. The protocol-level counterpart of the internal
|
|
1223
|
-
* `AstDocumentManager.getAuthor`: a framework-internal rebuild has no author,
|
|
1224
|
-
* so this surfaces the {@link UNKNOWN_CLIENT_ID} presentation default. Adopters
|
|
1225
|
-
* that rebuild through non-text-document channels override to derive a
|
|
1226
|
-
* source id of their own.
|
|
1227
|
-
*/
|
|
1228
|
-
protected resolveSourceClientId(document: LangiumDocument): string {
|
|
1229
|
-
const author = this.services.workspace.TextDocuments.getAuthor(document.textDocument.uri, document.textDocument.version);
|
|
1230
|
-
return author ?? UNKNOWN_CLIENT_ID;
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
1591
|
// --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
|
|
1234
1592
|
// Computed in THIS process: the data-server child holds the model store, so
|
|
1235
1593
|
// these snapshots reflect the heap that actually carries the workspace
|
|
@@ -1291,11 +1649,11 @@ export class DataServer<
|
|
|
1291
1649
|
/** Resolve a partial options object into a fully-defaulted form. */
|
|
1292
1650
|
protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions {
|
|
1293
1651
|
const additionalMethods = partial.additionalMethods ?? [];
|
|
1294
|
-
const builtIn = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS]
|
|
1652
|
+
const builtIn: readonly string[] = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS];
|
|
1295
1653
|
const overlap = additionalMethods.filter(name => builtIn.includes(name));
|
|
1296
1654
|
if (overlap.length > 0) {
|
|
1297
1655
|
throw new Error(
|
|
1298
|
-
`
|
|
1656
|
+
`DataServerOptions.additionalMethods overlaps with built-in data-server methods: ${overlap.join(', ')}. ` +
|
|
1299
1657
|
'Adopter protocols must not redeclare framework method names; rename the adopter method or remove it from additionalMethods.'
|
|
1300
1658
|
);
|
|
1301
1659
|
}
|
|
@@ -1305,7 +1663,8 @@ export class DataServer<
|
|
|
1305
1663
|
methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
|
|
1306
1664
|
additionalMethods,
|
|
1307
1665
|
excludedMethods: partial.excludedMethods ?? [],
|
|
1308
|
-
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
|
|
1666
|
+
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
|
|
1667
|
+
referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
|
|
1309
1668
|
};
|
|
1310
1669
|
}
|
|
1311
1670
|
}
|