@hydranium/data-server 1.0.0-next.14 → 1.0.0-next.148
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/lib/data-server.d.ts +363 -191
- package/lib/data-server.d.ts.map +1 -1
- package/lib/data-server.js +542 -315
- package/lib/data-server.js.map +1 -1
- package/lib/messages/index.d.ts +18 -0
- package/lib/messages/index.d.ts.map +1 -0
- package/lib/messages/index.js +18 -0
- package/lib/messages/index.js.map +1 -0
- package/lib/testing/data-server-harness.d.ts +7 -1
- package/lib/testing/data-server-harness.d.ts.map +1 -1
- package/lib/testing/data-server-harness.js +5 -2
- package/lib/testing/data-server-harness.js.map +1 -1
- package/package.json +17 -8
- package/src/data-server.ts +678 -341
- package/src/messages/index.ts +26 -0
- package/src/testing/data-server-harness.ts +16 -1
package/src/data-server.ts
CHANGED
|
@@ -9,12 +9,20 @@
|
|
|
9
9
|
|
|
10
10
|
import {
|
|
11
11
|
createRpcProxy,
|
|
12
|
+
defineMessage,
|
|
12
13
|
DisposableCollection,
|
|
14
|
+
HYDRANIUM_ERROR_CODES,
|
|
13
15
|
isDocumentSource,
|
|
14
16
|
isElementSource,
|
|
15
17
|
isSyntheticSource,
|
|
18
|
+
messageData,
|
|
19
|
+
messageError,
|
|
16
20
|
ReferenceSource,
|
|
21
|
+
SessionClosedError,
|
|
22
|
+
TIMED_OUT,
|
|
17
23
|
type CloseModelArgs,
|
|
24
|
+
type HydraniumMessageData,
|
|
25
|
+
type HydraniumResponseError,
|
|
18
26
|
type Disposable,
|
|
19
27
|
type ElementSource,
|
|
20
28
|
type FindNextNameArgs,
|
|
@@ -28,8 +36,11 @@ import {
|
|
|
28
36
|
type ReferenceTarget,
|
|
29
37
|
type Tracer,
|
|
30
38
|
type TransferDiagnostic,
|
|
31
|
-
|
|
32
|
-
type TransferElement
|
|
39
|
+
TransferDocument,
|
|
40
|
+
type TransferElement,
|
|
41
|
+
UNKNOWN_CLIENT_ID,
|
|
42
|
+
asSnapshotVersion,
|
|
43
|
+
cyrb53
|
|
33
44
|
} from '@hydranium/protocol';
|
|
34
45
|
import {
|
|
35
46
|
DATA_SERVER_DIAGNOSTICS_METHODS,
|
|
@@ -42,29 +53,84 @@ import {
|
|
|
42
53
|
type StartProfilingArgs,
|
|
43
54
|
type StopProfilingArgs,
|
|
44
55
|
type WriteServerHeapSnapshotArgs,
|
|
56
|
+
type CloseSessionArgs,
|
|
57
|
+
type CreateModelDocumentArgs,
|
|
58
|
+
type CreateSessionArgs,
|
|
45
59
|
type GetModelDocumentArgs,
|
|
46
60
|
type GetProjectForUriArgs,
|
|
47
61
|
type TransferSaveDocumentArgs,
|
|
48
62
|
type WatchModelDocumentArgs,
|
|
49
63
|
type TransferDocumentSavedEvent,
|
|
50
64
|
type TransferDocumentUpdatedEvent,
|
|
51
|
-
type TransferUpdateDocumentArgs
|
|
65
|
+
type TransferUpdateDocumentArgs,
|
|
66
|
+
type TransferUpdateDocumentsArgs
|
|
52
67
|
} from '@hydranium/protocol/data';
|
|
53
|
-
import { REVERT_ON_CLOSE_CLIENT_ID,
|
|
68
|
+
import { REVERT_ON_CLOSE_CLIENT_ID, ReentrantWriteLockError } from '@hydranium/core';
|
|
54
69
|
import { defaultDataServerDiagnostics } from './default-diagnostics.js';
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Raised when a profiling command arrives with no capture running.
|
|
73
|
+
*
|
|
74
|
+
* A `ResponseError` rather than a plain `Error` so the identity survives to the
|
|
75
|
+
* response boundary, which is where the message is rendered. An unwrapped throw
|
|
76
|
+
* reaches the client as a generic internal error instead: no code for a caller
|
|
77
|
+
* to switch on, and nothing for the boundary to render from.
|
|
78
|
+
*/
|
|
79
|
+
export const NO_ACTIVE_PROFILE = defineMessage(
|
|
80
|
+
'hydranium/data-server/no-active-profile',
|
|
81
|
+
'No profiling capture is active; call startProfiling first.'
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
|
|
86
|
+
* survives reconstruction and is what a caller switches on.
|
|
87
|
+
*/
|
|
88
|
+
export const NO_ACTIVE_PROFILE_CODE = HYDRANIUM_ERROR_CODES.noActiveProfile;
|
|
89
|
+
|
|
90
|
+
export const noActiveProfileError = (): HydraniumResponseError => messageError(NO_ACTIVE_PROFILE_CODE, NO_ACTIVE_PROFILE);
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Raised when a reference question's wait for the build exceeds
|
|
94
|
+
* {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
95
|
+
*
|
|
96
|
+
* A `ResponseError` because a class name does not cross RPC: without the code a
|
|
97
|
+
* wire client cannot tell a wedged build from a reference that resolves to
|
|
98
|
+
* nothing, which is the distinction the wait exists to keep.
|
|
99
|
+
*/
|
|
100
|
+
export const REFERENCE_SETTLE_TIMEOUT = defineMessage(
|
|
101
|
+
'hydranium/data-server/reference-settle-timeout',
|
|
102
|
+
'The model is still being processed; try again in a moment.'
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
/** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
|
|
106
|
+
export const REFERENCE_SETTLE_TIMEOUT_CODE = HYDRANIUM_ERROR_CODES.referenceSettleTimeout;
|
|
107
|
+
|
|
108
|
+
/** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */
|
|
109
|
+
export const referenceSettleTimeoutError = (elapsedMs: number): ResponseError<HydraniumMessageData & { readonly elapsedMs: number }> =>
|
|
110
|
+
new ResponseError(REFERENCE_SETTLE_TIMEOUT_CODE, REFERENCE_SETTLE_TIMEOUT.format(), {
|
|
111
|
+
elapsedMs,
|
|
112
|
+
...messageData(REFERENCE_SETTLE_TIMEOUT)
|
|
113
|
+
});
|
|
114
|
+
|
|
55
115
|
import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
|
|
56
116
|
import type {
|
|
117
|
+
ClientSession,
|
|
118
|
+
ClientSessionWriteArgs,
|
|
57
119
|
ClientTextDocumentChangeEvent,
|
|
120
|
+
DocumentDirtyChangedEvent,
|
|
58
121
|
HydraniumLanguageServices,
|
|
59
122
|
LogNameOptions,
|
|
123
|
+
AstDiagnostic,
|
|
124
|
+
AstDocument,
|
|
60
125
|
ModelService,
|
|
61
126
|
ProjectChangeEvent,
|
|
62
127
|
ServerSharedServices,
|
|
128
|
+
SessionEndCause,
|
|
63
129
|
TransferEncoder
|
|
64
130
|
} from '@hydranium/core';
|
|
65
131
|
import type { TextDocument } from 'vscode-languageserver-textdocument';
|
|
66
132
|
import { type AstNode, DocumentState, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
|
|
67
|
-
import type
|
|
133
|
+
import { type CancellationToken, type MessageConnection, ResponseError } from 'vscode-jsonrpc';
|
|
68
134
|
|
|
69
135
|
/**
|
|
70
136
|
* Domain separator between text and diagnostics inputs of
|
|
@@ -86,24 +152,22 @@ const FINGERPRINT_SEPARATOR = '\0';
|
|
|
86
152
|
* concatenated into one string.
|
|
87
153
|
*/
|
|
88
154
|
function fingerprintHash(parts: readonly string[]): string {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
for (const part of parts) {
|
|
92
|
-
for (let i = 0; i < part.length; i++) {
|
|
93
|
-
const ch = part.charCodeAt(i);
|
|
94
|
-
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
95
|
-
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
|
|
99
|
-
h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
100
|
-
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
|
|
101
|
-
h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
102
|
-
const high = (h2 >>> 0).toString(16).padStart(8, '0');
|
|
103
|
-
const low = (h1 >>> 0).toString(16).padStart(8, '0');
|
|
104
|
-
return high + low;
|
|
155
|
+
const { high, low } = cyrb53(parts);
|
|
156
|
+
return high.toString(16).padStart(8, '0') + low.toString(16).padStart(8, '0');
|
|
105
157
|
}
|
|
106
158
|
|
|
159
|
+
/**
|
|
160
|
+
* A session a data connection registered with a resume token, and how to end
|
|
161
|
+
* it from another connection. See {@link DataServer.resumableSessions}.
|
|
162
|
+
*/
|
|
163
|
+
export interface ResumableSession {
|
|
164
|
+
readonly token: string;
|
|
165
|
+
/** End the session as its connection closing would. */
|
|
166
|
+
readonly end: () => void;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const resumableByModelService = new WeakMap<object, Map<string, ResumableSession>>();
|
|
170
|
+
|
|
107
171
|
/**
|
|
108
172
|
* Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
|
|
109
173
|
* de-dup `onDocumentUpdated` emissions.
|
|
@@ -155,12 +219,13 @@ export interface DataServerOptions extends LogNameOptions {
|
|
|
155
219
|
* (`DataClientProtocol.onDocumentUpdated`).
|
|
156
220
|
*
|
|
157
221
|
* **Subscription dispatch only** — distinct from the synchronous RPC
|
|
158
|
-
* response phase.
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
* controls only the async notification
|
|
222
|
+
* response phase. A read (`getModelDocument`) settles at the
|
|
223
|
+
* integrity-settled landmark (`IntegrityService.SettledState`), or at
|
|
224
|
+
* `Validated` when {@link GetModelDocumentArgs.includeDiagnostics} is set.
|
|
225
|
+
* A write (`updateModelDocument` / `updateModelDocuments` /
|
|
226
|
+
* `saveModelDocument`) answers once its document is validated, as a
|
|
227
|
+
* session's write does. This option controls only the async notification
|
|
228
|
+
* phase.
|
|
164
229
|
*
|
|
165
230
|
* Default: `DocumentState.Validated` — validation is the last builder
|
|
166
231
|
* phase and produces the full diagnostic set, so subscription events fired
|
|
@@ -201,6 +266,22 @@ export interface DataServerOptions extends LogNameOptions {
|
|
|
201
266
|
*/
|
|
202
267
|
readonly fingerprintStrategy?: FingerprintStrategy;
|
|
203
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
|
+
|
|
204
285
|
/**
|
|
205
286
|
* Wire-method namespace for both inbound request handlers and the
|
|
206
287
|
* outbound notification client proxy. Defaults to
|
|
@@ -258,15 +339,20 @@ export interface DataServerOptions extends LogNameOptions {
|
|
|
258
339
|
* When supplied, every inbound data-server RPC is timed into this collector
|
|
259
340
|
* (via the `createRpcProxy` binding) and exposed through
|
|
260
341
|
* {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an
|
|
261
|
-
* LSP connection can pass the SAME collector to
|
|
262
|
-
*
|
|
263
|
-
*
|
|
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).
|
|
264
345
|
*/
|
|
265
346
|
readonly latency?: LatencyCollector;
|
|
266
347
|
}
|
|
267
348
|
|
|
268
|
-
/**
|
|
269
|
-
|
|
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 {
|
|
270
356
|
readonly subscriptionPhase: DocumentState;
|
|
271
357
|
readonly fingerprintStrategy: FingerprintStrategy;
|
|
272
358
|
readonly methodNamespace: string;
|
|
@@ -274,6 +360,34 @@ interface ResolvedDataServerOptions {
|
|
|
274
360
|
readonly excludedMethods: readonly string[];
|
|
275
361
|
/** Always resolved — to the caller's, or to the platform default. */
|
|
276
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 revert mark; {@link DataServer.pruneUriWatchRecord} enforces that on
|
|
370
|
+
* every path that removes either, so a record with no watcher has a revert
|
|
371
|
+
* 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 revert 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
|
+
/** Set by {@link DataServer.subscribeToTextDocumentCloses}; the next phase event broadcasts even without a watcher. */
|
|
380
|
+
revertPending?: boolean;
|
|
381
|
+
/**
|
|
382
|
+
* The version of an open document the last event sent was built at. The
|
|
383
|
+
* version sent again goes out as `'rebuilt'` from no client: the manager
|
|
384
|
+
* counts a version delivered only once its `Validated` listeners ran, so a
|
|
385
|
+
* build cancelled after the subscription phase would send it as a change
|
|
386
|
+
* twice. Only while the store has the document open: without it, a
|
|
387
|
+
* document can keep one version through changes of its file, so its events
|
|
388
|
+
* keep the manager's attribution.
|
|
389
|
+
*/
|
|
390
|
+
sentVersion?: number;
|
|
277
391
|
}
|
|
278
392
|
|
|
279
393
|
/**
|
|
@@ -301,9 +415,11 @@ interface ResolvedDataServerOptions {
|
|
|
301
415
|
* any names supplied via {@link DataServerOptions.additionalMethods}) and
|
|
302
416
|
* builds the {@link DataClientProtocol} notification proxy on the same
|
|
303
417
|
* connection in one {@link createRpcProxy} call (binding `this` as its
|
|
304
|
-
* `localTarget`) under the configured namespace, and subscribes
|
|
305
|
-
* `DocumentBuilder.onDocumentPhase`
|
|
306
|
-
*
|
|
418
|
+
* `localTarget`) under the configured namespace, and subscribes two listeners
|
|
419
|
+
* at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
|
|
420
|
+
* per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
|
|
421
|
+
* `DocumentBuilder.onBuildPhase` one dispatching a single
|
|
422
|
+
* `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
|
|
307
423
|
*
|
|
308
424
|
* The data-server requires the full {@link ServerSharedServices}
|
|
309
425
|
* shape — `HydraniumTextDocuments` for client-attributed updates,
|
|
@@ -331,87 +447,27 @@ export class DataServer<
|
|
|
331
447
|
* Framework defaults, exposed so an adopter can spread them when
|
|
332
448
|
* extending rather than restate a value the framework may change.
|
|
333
449
|
*/
|
|
334
|
-
static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>> = {
|
|
335
|
-
subscriptionPhase: DocumentState.Validated
|
|
450
|
+
static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>> = {
|
|
451
|
+
subscriptionPhase: DocumentState.Validated,
|
|
452
|
+
referenceSettleTimeoutMs: 60_000
|
|
336
453
|
};
|
|
337
454
|
|
|
338
455
|
protected readonly options: ResolvedDataServerOptions;
|
|
339
|
-
/**
|
|
340
|
-
protected readonly
|
|
456
|
+
/** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
|
|
457
|
+
protected readonly uriWatchRecords = new Map<string, DataServerUriWatchRecord>();
|
|
341
458
|
/**
|
|
342
|
-
*
|
|
343
|
-
*
|
|
459
|
+
* The client sessions this connection registered, by client id. A document
|
|
460
|
+
* request carrying one of these ids acts as that session; one carrying any
|
|
461
|
+
* other id fails.
|
|
344
462
|
*
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
* suppressed. The store has no notion of which connection a clientId reached
|
|
349
|
-
* it over, so the connection-scoped set has to live here; teaching it a client
|
|
350
|
-
* identity is the more robust and much larger alternative.
|
|
463
|
+
* Entries stay after {@link dispose} has ended their sessions, so a request
|
|
464
|
+
* still running from before the connection closed reaches the ended handle
|
|
465
|
+
* and fails with the session's own error.
|
|
351
466
|
*/
|
|
352
|
-
protected readonly
|
|
467
|
+
protected readonly clientSessions = new Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer>>();
|
|
353
468
|
/** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
|
|
354
469
|
protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
|
|
355
470
|
protected readonly disposables = new DisposableCollection();
|
|
356
|
-
/**
|
|
357
|
-
* Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
|
|
358
|
-
* `reason` discrimination on outbound `onDocumentUpdated` notifications:
|
|
359
|
-
* a URI in the `changed` list emits `'changed'`, in `deleted` emits
|
|
360
|
-
* `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
|
|
361
|
-
* URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
|
|
362
|
-
* the LSP side, so reason fidelity stays consistent between heads.
|
|
363
|
-
*/
|
|
364
|
-
protected lastBuildUpdate?: { changed: readonly URI[]; deleted: readonly URI[] };
|
|
365
|
-
/**
|
|
366
|
-
* Per-URI hash of the last emitted (text + diagnostics) state,
|
|
367
|
-
* used by {@link dispatchPhaseEvent} to suppress duplicate
|
|
368
|
-
* `onDocumentUpdated` notifications for rebuilds that produce no
|
|
369
|
-
* observable change since the last emit.
|
|
370
|
-
*
|
|
371
|
-
* Two scenarios routinely produce such rebuilds:
|
|
372
|
-
* 1. **Refresh-triggered rebuilds.** When a second client attaches to a
|
|
373
|
-
* document already open in another client,
|
|
374
|
-
* `HydraniumTextDocuments.refreshContent` fires `onDidChangeContent`
|
|
375
|
-
* purely to re-trigger the build pipeline — the text and diagnostics
|
|
376
|
-
* are identical to the prior emit.
|
|
377
|
-
* 2. **Cascade rebuilds with no diagnostic delta.** Langium rebuilds a
|
|
378
|
-
* document when a dependency changes; if the rebuild produces the
|
|
379
|
-
* same diagnostics, there is nothing new to communicate to subscribers.
|
|
380
|
-
*
|
|
381
|
-
* Without this filter, both scenarios reach subscribers as wire-side
|
|
382
|
-
* `'changed'` events. A subscriber that interprets `'changed'` as
|
|
383
|
-
* "another client wrote new content" and resets its in-memory root to
|
|
384
|
-
* the server view then misreads the spurious event as a concurrent
|
|
385
|
-
* third-party write and loses the user's edits.
|
|
386
|
-
*
|
|
387
|
-
* Initialised on {@link watchModelDocument} to the current
|
|
388
|
-
* document fingerprint so the FIRST phase event after a fresh
|
|
389
|
-
* subscription is also de-duplicated against the state subscribers
|
|
390
|
-
* obtained via `getModelDocument` — they do not need a redundant phase
|
|
391
|
-
* notification for the state they just fetched.
|
|
392
|
-
*
|
|
393
|
-
* Cleared in {@link unwatchModelDocument} when the last
|
|
394
|
-
* subscriber for a URI leaves so memory does not accumulate.
|
|
395
|
-
*
|
|
396
|
-
* Stored as a cyrb53 hex digest (16 chars per URI) rather than the raw
|
|
397
|
-
* text + diagnostics serialisation so the memory cost is constant in
|
|
398
|
-
* document size. See {@link computeDocumentFingerprint} for the inputs.
|
|
399
|
-
*/
|
|
400
|
-
protected readonly lastEmittedFingerprint = new Map<string, string>();
|
|
401
|
-
/**
|
|
402
|
-
* URIs whose LAST client just closed. The update handler rebuilds such a
|
|
403
|
-
* document from its disk content (discarding unsaved in-session edits),
|
|
404
|
-
* but {@link dispatchPhaseEvent} gates on the subscription map — and the
|
|
405
|
-
* last close typically also removed the last watcher, so consumers that
|
|
406
|
-
* only ever fetch via `getModelDocument` would keep showing the
|
|
407
|
-
* discarded state forever. Marked on the last-close transition (see
|
|
408
|
-
* {@link subscribeToTextDocumentCloses}) and consumed by
|
|
409
|
-
* {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
|
|
410
|
-
* phase event even without a subscription — de-duplicated against
|
|
411
|
-
* {@link lastEmittedFingerprint} where an entry survives, so a close
|
|
412
|
-
* whose disk state equals the last emitted state stays silent.
|
|
413
|
-
*/
|
|
414
|
-
protected readonly pendingRevertBroadcasts = new Set<string>();
|
|
415
471
|
protected readonly tracer: Tracer;
|
|
416
472
|
/** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
|
|
417
473
|
protected activeProfile?: DataServerProfileCapture;
|
|
@@ -420,27 +476,23 @@ export class DataServer<
|
|
|
420
476
|
/** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */
|
|
421
477
|
protected readonly latency?: LatencyCollector;
|
|
422
478
|
/** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */
|
|
423
|
-
protected readonly encoder: TransferEncoder<
|
|
479
|
+
protected readonly encoder: TransferEncoder<TDiagnostic>;
|
|
424
480
|
/**
|
|
425
481
|
* In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
|
|
426
|
-
*
|
|
427
|
-
*
|
|
428
|
-
* while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
|
|
429
|
-
* `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
|
|
430
|
-
* to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
|
|
482
|
+
* Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
|
|
483
|
+
* {@link encoder} converts one into the other on the way out.
|
|
431
484
|
*/
|
|
432
|
-
protected readonly modelService: ModelService<AstNode,
|
|
485
|
+
protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
|
|
433
486
|
|
|
434
487
|
constructor(
|
|
435
488
|
protected readonly connection: MessageConnection,
|
|
436
|
-
protected readonly services: ServerSharedServices<TProject>,
|
|
489
|
+
protected readonly services: ServerSharedServices<TProject, TDiagnostic>,
|
|
437
490
|
options: DataServerOptions = {}
|
|
438
491
|
) {
|
|
439
492
|
this.options = this.resolveOptions(options);
|
|
440
493
|
this.tracer = this.services.Tracer.for(options.logName ?? 'DataServer').trace('instantiated');
|
|
441
494
|
// DI-bound: adopters rebind `services.model.TransferEncoder` /
|
|
442
|
-
// `services.model.ModelService` with their own subclasses.
|
|
443
|
-
// framework upper bounds; the casts below narrow to this instance's generics.
|
|
495
|
+
// `services.model.ModelService` with their own subclasses.
|
|
444
496
|
const { TransferEncoder: encoder, ModelService: modelService } = this.services.model;
|
|
445
497
|
if (!encoder || !modelService) {
|
|
446
498
|
throw new Error(
|
|
@@ -448,8 +500,8 @@ export class DataServer<
|
|
|
448
500
|
'Did you compose `createServerSharedModule(ctx)` into your shared module?'
|
|
449
501
|
);
|
|
450
502
|
}
|
|
451
|
-
this.encoder = encoder
|
|
452
|
-
this.modelService = modelService
|
|
503
|
+
this.encoder = encoder;
|
|
504
|
+
this.modelService = modelService;
|
|
453
505
|
const excluded = new Set<string>(this.options.excludedMethods);
|
|
454
506
|
const registeredMethods = [
|
|
455
507
|
...DATA_SERVER_PROTOCOL_METHODS,
|
|
@@ -465,38 +517,43 @@ export class DataServer<
|
|
|
465
517
|
methodNamespace: this.options.methodNamespace,
|
|
466
518
|
localTarget: this,
|
|
467
519
|
localMethods: registeredMethods as readonly (keyof this & string)[],
|
|
468
|
-
latency: this.latency
|
|
520
|
+
latency: this.latency,
|
|
521
|
+
// Bound at the chokepoint rather than per handler, so an adopter's
|
|
522
|
+
// `additionalMethods` are rendered on the same terms as the
|
|
523
|
+
// framework's own rejections.
|
|
524
|
+
renderErrorMessage: error => this.services.MessageRenderer.renderError(error)
|
|
469
525
|
});
|
|
470
|
-
this.disposables.push(
|
|
471
|
-
this.services.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
|
|
472
|
-
this.lastBuildUpdate = { changed, deleted };
|
|
473
|
-
})
|
|
474
|
-
);
|
|
526
|
+
this.disposables.push(this.services.workspace.DocumentBuilder.onUpdate((_changed, deleted) => this.dispatchDeleteEvents(deleted)));
|
|
475
527
|
this.subscribeToDocumentBuilder();
|
|
476
528
|
this.subscribeToTextDocumentSaves();
|
|
529
|
+
this.subscribeToDirtyChanges();
|
|
477
530
|
this.subscribeToTextDocumentCloses();
|
|
478
531
|
this.subscribeToProjectManager();
|
|
479
532
|
// Self-register teardown so an adopter that keeps no reference to the
|
|
480
533
|
// server still releases per-connection state, with no lifecycle hook of
|
|
481
|
-
// its own.
|
|
482
|
-
|
|
534
|
+
// its own. The client did not close anything itself, so its sessions end
|
|
535
|
+
// as lost and each document it was the last to have open waits out the
|
|
536
|
+
// store's revert grace. See `dispose`.
|
|
537
|
+
this.disposables.push(connection.onClose(() => this.dispose('lost')));
|
|
483
538
|
}
|
|
484
539
|
|
|
485
540
|
/**
|
|
486
541
|
* Release everything the constructor wired up — the bound protocol
|
|
487
|
-
* handlers and every listener — and clear
|
|
488
|
-
*
|
|
489
|
-
*
|
|
490
|
-
*
|
|
491
|
-
*
|
|
492
|
-
* this server's and so outlives the connection unless released here.
|
|
542
|
+
* handlers and every listener — and clear {@link uriWatchRecords}, so a
|
|
543
|
+
* long-lived shared services bundle does not retain per-connection memory
|
|
544
|
+
* after the connection closes. Also ends every session this connection registered, which closes
|
|
545
|
+
* every document it has open: the SHARED store's state rather than this
|
|
546
|
+
* server's, which outlives the connection unless released here.
|
|
493
547
|
*
|
|
494
|
-
* Idempotent: subsequent calls are no-ops.
|
|
495
|
-
*
|
|
496
|
-
*
|
|
497
|
-
*
|
|
548
|
+
* Idempotent: subsequent calls are no-ops. Runs by itself when the
|
|
549
|
+
* connection closes, so adopters who don't hold a reference still get
|
|
550
|
+
* per-connection cleanup; adopters that DO hold a reference may call
|
|
551
|
+
* `dispose()` directly for early teardown. The sessions end with `cause`:
|
|
552
|
+
* `'closed'` reverts every document whose last open they close at once,
|
|
553
|
+
* and `'lost'`, the connection's own close, lets each wait out the revert
|
|
554
|
+
* grace.
|
|
498
555
|
*/
|
|
499
|
-
dispose(): void {
|
|
556
|
+
dispose(cause: SessionEndCause = 'closed'): void {
|
|
500
557
|
this.disposed = true;
|
|
501
558
|
// Release an in-flight interactive capture so the process-wide inspector
|
|
502
559
|
// singleton is not left active after the connection closes.
|
|
@@ -505,102 +562,178 @@ export class DataServer<
|
|
|
505
562
|
this.activeProfile = undefined;
|
|
506
563
|
void capture.stop({}).catch(() => undefined);
|
|
507
564
|
}
|
|
508
|
-
// AFTER `disposables.dispose()`, deliberately:
|
|
509
|
-
//
|
|
510
|
-
//
|
|
565
|
+
// AFTER `disposables.dispose()`, deliberately: ending a session releases
|
|
566
|
+
// each document it was the last to hold, and this server's own
|
|
567
|
+
// `onDidCloseLastOpen` listener would otherwise mark a revert broadcast
|
|
568
|
+
// for a connection that is already gone.
|
|
511
569
|
this.disposables.dispose();
|
|
512
|
-
this.
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
this.
|
|
570
|
+
for (const [clientId, session] of this.clientSessions) {
|
|
571
|
+
this.endSession(clientId, session, cause);
|
|
572
|
+
}
|
|
573
|
+
this.uriWatchRecords.clear();
|
|
516
574
|
}
|
|
517
575
|
|
|
518
576
|
// ============================================================
|
|
519
|
-
// DataServerProtocol implementation
|
|
577
|
+
// DataServerProtocol implementation
|
|
520
578
|
// ============================================================
|
|
521
579
|
//
|
|
522
|
-
//
|
|
523
|
-
//
|
|
524
|
-
// the wire boundary via
|
|
525
|
-
//
|
|
526
|
-
//
|
|
527
|
-
//
|
|
528
|
-
|
|
529
|
-
async
|
|
530
|
-
//
|
|
531
|
-
//
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
580
|
+
// Reads go to `ModelService`; a request that opens or writes a document
|
|
581
|
+
// goes to the session this connection registered under its `clientId`.
|
|
582
|
+
// Each answer is encoded on the wire boundary via
|
|
583
|
+
// `encoder.astDocumentToTransferDocument`. To change how documents are
|
|
584
|
+
// read, override on the ModelService subclass; to change how they are
|
|
585
|
+
// written, on the session class the bound `ClientSessionFactory` builds.
|
|
586
|
+
|
|
587
|
+
async createSession(args: CreateSessionArgs): Promise<void> {
|
|
588
|
+
// After teardown nothing would ever end a session registered now, and its
|
|
589
|
+
// id would stay taken for the life of the process.
|
|
590
|
+
if (this.disposed) {
|
|
591
|
+
throw new SessionClosedError(args.clientId);
|
|
592
|
+
}
|
|
593
|
+
const resumable = this.resumableSessions();
|
|
594
|
+
const previous = resumable.get(args.clientId);
|
|
595
|
+
if (previous && args.resumeToken !== undefined && previous.token === args.resumeToken) {
|
|
596
|
+
previous.end();
|
|
597
|
+
}
|
|
598
|
+
const session = this.modelService.createSession(args.label, args.clientId);
|
|
599
|
+
this.clientSessions.set(args.clientId, session);
|
|
600
|
+
if (args.resumeToken !== undefined) {
|
|
601
|
+
// Taken over by a client registering again after its connection
|
|
602
|
+
// dropped, so the old session ends as lost: the documents it was the
|
|
603
|
+
// last to have open wait out the grace, and the new session's opens
|
|
604
|
+
// find their unsaved text.
|
|
605
|
+
resumable.set(args.clientId, { token: args.resumeToken, end: () => this.endSession(args.clientId, session, 'lost') });
|
|
541
606
|
}
|
|
542
|
-
holders.add(args.clientId);
|
|
543
|
-
const document = await this.getModelDocument({ uri: args.uri });
|
|
544
|
-
// Project the authoritative client-facing version onto the open snapshot.
|
|
545
|
-
// `getModelDocument` encodes the freshly-built AST snapshot, whose version
|
|
546
|
-
// is the `LangiumDocument`'s own `textDocument.version`. That lags the
|
|
547
|
-
// multi-client synced version whenever the open seeded the synced document
|
|
548
|
-
// with a caller-supplied version id — and the synced version is what
|
|
549
|
-
// `ModelService.update`'s optimistic-concurrency gate compares
|
|
550
|
-
// `baseVersion` against, so reporting the snapshot's would make the
|
|
551
|
-
// caller's first tagged write self-conflict. A genuine concurrent edit
|
|
552
|
-
// still trips the gate and is reconciled by the caller's replay rather
|
|
553
|
-
// than predicted here.
|
|
554
|
-
return { ...document, version: this.services.workspace.TextDocuments.version(args.uri) };
|
|
555
607
|
}
|
|
556
608
|
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
609
|
+
/**
|
|
610
|
+
* End a session this connection registered. The ended handle stays in
|
|
611
|
+
* {@link clientSessions}, as it does after {@link dispose}, so a request for
|
|
612
|
+
* the id still arriving fails with the ended session's own error.
|
|
613
|
+
*/
|
|
614
|
+
async closeSession(args: CloseSessionArgs): Promise<void> {
|
|
615
|
+
const session = this.clientSessions.get(args.clientId);
|
|
616
|
+
if (session) {
|
|
617
|
+
this.endSession(args.clientId, session);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
|
|
622
|
+
protected endSession(
|
|
623
|
+
clientId: string,
|
|
624
|
+
session: ClientSession<AstNode, AstDiagnostic, TTransfer>,
|
|
625
|
+
cause: SessionEndCause = 'closed'
|
|
626
|
+
): void {
|
|
627
|
+
for (const [uri, record] of this.uriWatchRecords) {
|
|
628
|
+
if (record.watchers.delete(clientId)) {
|
|
629
|
+
this.pruneUriWatchRecord(uri);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
session.dispose(cause);
|
|
564
633
|
}
|
|
565
634
|
|
|
566
635
|
/**
|
|
567
|
-
*
|
|
568
|
-
*
|
|
636
|
+
* The resumable sessions of this services tree, by client id, across all of
|
|
637
|
+
* its data connections: a client resumes on another connection than the one
|
|
638
|
+
* that registered it. An entry leaves when its session ends, by any path, so
|
|
639
|
+
* it keeps no ended connection alive.
|
|
640
|
+
*
|
|
641
|
+
* A takeover by resume token ends the old session even when its connection
|
|
642
|
+
* is still alive, so two clients that shared an id and its token would end
|
|
643
|
+
* each other's sessions. And the token is a guard against colliding with a
|
|
644
|
+
* session the server has not yet seen end, not a secret: the wire carries no
|
|
645
|
+
* authentication, and a peer that learns the token can end the session.
|
|
569
646
|
*/
|
|
570
|
-
protected
|
|
571
|
-
|
|
572
|
-
if (!
|
|
573
|
-
|
|
647
|
+
protected resumableSessions(): Map<string, ResumableSession> {
|
|
648
|
+
let sessions = resumableByModelService.get(this.modelService);
|
|
649
|
+
if (!sessions) {
|
|
650
|
+
const created = new Map<string, ResumableSession>();
|
|
651
|
+
// Subscribed once per services tree, and never disposed: it lives as
|
|
652
|
+
// long as the text store it listens to.
|
|
653
|
+
this.services.workspace.TextDocuments.onDidCloseSession(event => created.delete(event.clientId));
|
|
654
|
+
resumableByModelService.set(this.modelService, created);
|
|
655
|
+
sessions = created;
|
|
574
656
|
}
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
657
|
+
return sessions;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
async createModelDocument(args: CreateModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
661
|
+
const session = this.requireSession(args.clientId);
|
|
662
|
+
await session.create(args.uri, args.text);
|
|
663
|
+
return this.openedSnapshot(args.uri, () => session.close(args.uri));
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
async updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>[]> {
|
|
667
|
+
const astDocuments = await this.requireSession(args.clientId).updateAll({
|
|
668
|
+
updates: args.updates.map(update => this.toSessionWrite(update))
|
|
669
|
+
});
|
|
670
|
+
return astDocuments.map(astDocument => this.encodeDocument(astDocument));
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* The session write a wire write request carries. Only the fields a session
|
|
675
|
+
* takes: a field an adopter adds to a request reaches the session only
|
|
676
|
+
* through an override of this.
|
|
677
|
+
*/
|
|
678
|
+
protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer> {
|
|
679
|
+
return { uri: request.uri, model: request.model, basedOn: request.basedOn };
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* The session this connection registered under `clientId`, which every
|
|
684
|
+
* document request acts as. An id that is not one fails with the
|
|
685
|
+
* closed-session code: opening or writing under it would leave an open that
|
|
686
|
+
* no session end ever closes.
|
|
687
|
+
*/
|
|
688
|
+
protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer> {
|
|
689
|
+
const session = this.clientSessions.get(clientId);
|
|
690
|
+
if (!session) {
|
|
691
|
+
throw new SessionClosedError(clientId, 'The client session was never registered on this connection.');
|
|
578
692
|
}
|
|
693
|
+
return session;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
async openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
697
|
+
const session = this.requireSession(args.clientId);
|
|
698
|
+
const wasOpen = this.services.workspace.TextDocuments.isOpenInClient(args.uri, args.clientId);
|
|
699
|
+
await session.open(args.uri, args.options);
|
|
700
|
+
// A repeat open keeps the earlier one, which is still in use.
|
|
701
|
+
return this.openedSnapshot(args.uri, wasOpen ? undefined : () => session.close(args.uri));
|
|
579
702
|
}
|
|
580
703
|
|
|
581
704
|
/**
|
|
582
|
-
*
|
|
583
|
-
*
|
|
705
|
+
* The snapshot a session's open or create answers with. When the read
|
|
706
|
+
* fails, `rollback` undoes the open this call made before the failure is
|
|
707
|
+
* rethrown: the caller sees no open, so nothing on its side would ever close
|
|
708
|
+
* it.
|
|
584
709
|
*
|
|
585
|
-
*
|
|
586
|
-
*
|
|
587
|
-
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
590
|
-
* exceptional, so the leak accumulates there.
|
|
591
|
-
*
|
|
592
|
-
* Runs from {@link dispose}, which is synchronous, so each close is fired and
|
|
593
|
-
* its failure swallowed — a teardown must not reject, and a URI whose close
|
|
594
|
-
* fails is no worse off than it was before this drain existed.
|
|
710
|
+
* Versioned with the store's shared version rather than the snapshot's own:
|
|
711
|
+
* the built document's `textDocument.version` lags the store's whenever the
|
|
712
|
+
* store assigned the version, and the store's is what a write's `basedOn` is
|
|
713
|
+
* compared against, so reporting the snapshot's would make the caller's
|
|
714
|
+
* first based-on write conflict with itself.
|
|
595
715
|
*/
|
|
596
|
-
protected
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
716
|
+
protected async openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
717
|
+
let document: TransferDocument<TTransfer, TDiagnostic>;
|
|
718
|
+
try {
|
|
719
|
+
document = await this.getModelDocument({ uri });
|
|
720
|
+
} catch (error: unknown) {
|
|
721
|
+
// The open's failure is the one the caller needs, not the cleanup's.
|
|
722
|
+
await rollback?.().catch(() => undefined);
|
|
723
|
+
throw error;
|
|
603
724
|
}
|
|
725
|
+
return { ...document, version: asSnapshotVersion(this.services.workspace.TextDocuments.version(uri)) };
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
async closeModelDocument(args: CloseModelArgs): Promise<void> {
|
|
729
|
+
// Through the handle, so a close under an ended session fails as that
|
|
730
|
+
// session's calls do, and a session class's own close is honoured.
|
|
731
|
+
const session = this.requireSession(args.clientId);
|
|
732
|
+
// Closing also releases the watch for (uri, clientId) — a forgotten
|
|
733
|
+
// unwatch would otherwise leak phase-event dispatch until the connection
|
|
734
|
+
// closes. Idempotent: a close without a prior watch is a no-op.
|
|
735
|
+
await this.unwatchModelDocument({ uri: args.uri, clientId: args.clientId });
|
|
736
|
+
await session.close(args.uri);
|
|
604
737
|
}
|
|
605
738
|
|
|
606
739
|
async getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
@@ -615,18 +748,27 @@ export class DataServer<
|
|
|
615
748
|
// unsubscribed caller that needs diagnostics inline passes
|
|
616
749
|
// `includeDiagnostics: true` to settle at `Validated` instead.
|
|
617
750
|
const state = args.includeDiagnostics ? DocumentState.Validated : undefined;
|
|
618
|
-
|
|
619
|
-
|
|
751
|
+
try {
|
|
752
|
+
return this.encodeDocument(await this.modelService.ensureDocumentState(args.uri, state));
|
|
753
|
+
} catch (error: unknown) {
|
|
754
|
+
// A URI with neither a file nor text builds nothing, and the wait after
|
|
755
|
+
// the build rejects for want of a document. The protocol answers that
|
|
756
|
+
// read with an envelope that has no root.
|
|
757
|
+
if (!(error instanceof ReentrantWriteLockError) && this.modelService.getDocument(args.uri) === undefined) {
|
|
758
|
+
return this.envelope(UriUtils.toUri(args.uri));
|
|
759
|
+
}
|
|
760
|
+
throw error;
|
|
761
|
+
}
|
|
620
762
|
}
|
|
621
763
|
|
|
622
764
|
async updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
623
|
-
const astDocument = await this.
|
|
624
|
-
return this.
|
|
765
|
+
const astDocument = await this.requireSession(args.clientId).update(this.toSessionWrite(args));
|
|
766
|
+
return this.encodeDocument(astDocument);
|
|
625
767
|
}
|
|
626
768
|
|
|
627
769
|
async saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>> {
|
|
628
|
-
const astDocument = await this.
|
|
629
|
-
return this.
|
|
770
|
+
const astDocument = await this.requireSession(args.clientId).save(this.toSessionWrite(args));
|
|
771
|
+
return this.encodeDocument(astDocument);
|
|
630
772
|
}
|
|
631
773
|
|
|
632
774
|
/**
|
|
@@ -634,28 +776,24 @@ export class DataServer<
|
|
|
634
776
|
* fan out to the wired `clientProxy.onDocumentUpdated`. The
|
|
635
777
|
* bidirectional pattern means the event channel is the client
|
|
636
778
|
* notification surface, not a returned handle — this method only
|
|
637
|
-
* registers the
|
|
779
|
+
* registers the watcher in {@link uriWatchRecords}.
|
|
638
780
|
*
|
|
639
|
-
* Also baselines the
|
|
640
|
-
* {@link
|
|
641
|
-
*
|
|
642
|
-
*
|
|
643
|
-
*
|
|
644
|
-
*
|
|
645
|
-
* redundant phase notification for that same state.
|
|
781
|
+
* Also baselines the URI's emission fingerprint (see
|
|
782
|
+
* {@link dispatchPhaseEvent}) to the document's current state when the
|
|
783
|
+
* first watcher for the URI registers. This guarantees that any phase event firing immediately after
|
|
784
|
+
* the watch with no observable change is suppressed — watchers obtain
|
|
785
|
+
* initial state via `getModelDocument` (or {@link openModelDocument}) and
|
|
786
|
+
* do not need a redundant phase notification for that same state.
|
|
646
787
|
*/
|
|
647
788
|
async watchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
|
|
648
789
|
const uri = this.canonicalKey(args.uri);
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
}
|
|
654
|
-
subscribers.add(args.clientId);
|
|
655
|
-
if (!this.lastEmittedFingerprint.has(uri)) {
|
|
790
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
|
|
791
|
+
this.uriWatchRecords.set(uri, record);
|
|
792
|
+
record.watchers.add(args.clientId);
|
|
793
|
+
if (record.fingerprint === undefined) {
|
|
656
794
|
const document = this.services.workspace.LangiumDocuments.getDocument(UriUtils.toUri(uri));
|
|
657
795
|
if (document) {
|
|
658
|
-
|
|
796
|
+
record.fingerprint = this.computeDocumentFingerprint(document);
|
|
659
797
|
}
|
|
660
798
|
}
|
|
661
799
|
}
|
|
@@ -663,29 +801,40 @@ export class DataServer<
|
|
|
663
801
|
/**
|
|
664
802
|
* Remove a watch for `(uri, clientId)` previously created by
|
|
665
803
|
* {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
|
|
666
|
-
* Dispatch for `uri` stops once no watchers remain,
|
|
667
|
-
*
|
|
668
|
-
* re-baselines against the then-current document state rather than a
|
|
669
|
-
* stale snapshot from the previous watch.
|
|
804
|
+
* Dispatch for `uri` stops once no watchers remain, and the emission
|
|
805
|
+
* fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
|
|
670
806
|
*/
|
|
671
807
|
async unwatchModelDocument(args: WatchModelDocumentArgs): Promise<void> {
|
|
672
808
|
const uri = this.canonicalKey(args.uri);
|
|
673
|
-
|
|
674
|
-
|
|
809
|
+
if (this.uriWatchRecords.get(uri)?.watchers.delete(args.clientId)) {
|
|
810
|
+
this.pruneUriWatchRecord(uri);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* Drop what `uri` no longer needs: the
|
|
816
|
+
* {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
|
|
817
|
+
* and the whole record once it holds no
|
|
818
|
+
* {@link DataServerUriWatchRecord.revertPending} mark either. Every path
|
|
819
|
+
* that removes a watcher or consumes a mark ends here.
|
|
820
|
+
*/
|
|
821
|
+
protected pruneUriWatchRecord(uri: string): void {
|
|
822
|
+
const record = this.uriWatchRecords.get(uri);
|
|
823
|
+
if (!record || record.watchers.size > 0) {
|
|
675
824
|
return;
|
|
676
825
|
}
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
this.
|
|
826
|
+
if (record.revertPending) {
|
|
827
|
+
record.fingerprint = undefined;
|
|
828
|
+
} else {
|
|
829
|
+
this.uriWatchRecords.delete(uri);
|
|
681
830
|
}
|
|
682
831
|
}
|
|
683
832
|
|
|
684
833
|
/**
|
|
685
|
-
* Canonicalise a URI string for use as a
|
|
686
|
-
*
|
|
687
|
-
*
|
|
688
|
-
*
|
|
834
|
+
* Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
|
|
835
|
+
* shared `DocumentUriPolicy`. Callers may send non-canonical URIs
|
|
836
|
+
* (drive-letter casing, percent-encoding differences, or a symlink path)
|
|
837
|
+
* over the wire; the dispatch side keys by
|
|
689
838
|
* `document.uri.toString()` from `LangiumDocuments`, so writer keys must
|
|
690
839
|
* canonicalise to the same form or events silently fail to deliver.
|
|
691
840
|
* Routing through the seam (rather than a bare `UriUtils.normalize`)
|
|
@@ -734,26 +883,57 @@ export class DataServer<
|
|
|
734
883
|
// (see resolveReferenceServices) and delegate.
|
|
735
884
|
// ============================================================
|
|
736
885
|
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
886
|
+
/**
|
|
887
|
+
* Settle the build before a reference question is answered from the index.
|
|
888
|
+
*
|
|
889
|
+
* A query issued right after a model update otherwise races the rebuild and
|
|
890
|
+
* reads an index missing the symbols it asks about. The cost is not confined
|
|
891
|
+
* to this call: a scope built inside that window is cached, and the build's
|
|
892
|
+
* remaining documents link against it.
|
|
893
|
+
*
|
|
894
|
+
* Waits the source document specifically, but ONLY when one is loaded at
|
|
895
|
+
* that URI: a synthetic source can address a URI with no document (a
|
|
896
|
+
* directory URI, typically), where a per-URI `waitUntil` throws "No document
|
|
897
|
+
* found". Falls back to a global settle, matching the id-based
|
|
898
|
+
* `ElementSource` path.
|
|
899
|
+
*
|
|
900
|
+
* Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
|
|
901
|
+
*/
|
|
902
|
+
protected async awaitReferencesLinked(source: ReferenceSource): Promise<void> {
|
|
903
|
+
const uri = isDocumentSource(source) || isSyntheticSource(source) ? UriUtils.toUri(source.uri) : undefined;
|
|
746
904
|
const waitUri = uri && this.services.workspace.LangiumDocuments.hasDocument(uri) ? uri : undefined;
|
|
747
|
-
|
|
905
|
+
const stopwatch = this.services.Clock.stopwatch();
|
|
906
|
+
const linked = this.services.workspace.DocumentBuilder.waitUntil(DocumentState.Linked, waitUri);
|
|
907
|
+
if ((await this.services.Clock.raceTimer(linked, this.options.referenceSettleTimeoutMs)) !== TIMED_OUT) {
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
const elapsedMs = Math.round(stopwatch.elapsedMs);
|
|
911
|
+
// A per-URI wait resolves off a document-phase notification, so a
|
|
912
|
+
// missed one strands a wait on a document that HAS reached the
|
|
913
|
+
// phase. Re-read before failing; the workspace-wide wait has no
|
|
914
|
+
// equivalent reading and can only reject.
|
|
915
|
+
const document = waitUri ? this.services.workspace.LangiumDocuments.getDocument(waitUri) : undefined;
|
|
916
|
+
if (waitUri && document && document.state >= DocumentState.Linked) {
|
|
917
|
+
this.tracer
|
|
918
|
+
.withUri(waitUri.toString())
|
|
919
|
+
.warn(`Missed the 'Linked' notification after ${elapsedMs}ms; the document already reached it`);
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
throw referenceSettleTimeoutError(elapsedMs);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
async findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]> {
|
|
926
|
+
await this.awaitReferencesLinked(ctx.source);
|
|
748
927
|
return this.resolveReferenceServices(ctx.source).CandidateProvider.find(ctx);
|
|
749
928
|
}
|
|
750
929
|
|
|
751
930
|
async resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined> {
|
|
931
|
+
await this.awaitReferencesLinked(ref.source);
|
|
752
932
|
const resolved = this.resolveReferenceServices(ref.source).CandidateProvider.resolveCandidate(ref);
|
|
753
933
|
if (!resolved) {
|
|
754
934
|
return undefined;
|
|
755
935
|
}
|
|
756
|
-
const element = this.encoder.toTransfer(resolved.node) as
|
|
936
|
+
const element = this.encoder.toTransfer(resolved.node) as TTransfer;
|
|
757
937
|
return { ...resolved.candidate, element };
|
|
758
938
|
}
|
|
759
939
|
|
|
@@ -764,7 +944,14 @@ export class DataServer<
|
|
|
764
944
|
// synthetic source — and the create-element flow driving this method is
|
|
765
945
|
// the one that produces directory URIs, on which a bare
|
|
766
946
|
// `getServices(uri)` throws while `findReferenceCandidates` succeeds.
|
|
767
|
-
const
|
|
947
|
+
const source = ReferenceSource.synthetic(args.uri, args.type, args.language);
|
|
948
|
+
// Mid-rebuild the names of documents not yet re-indexed are absent from
|
|
949
|
+
// the taken set, and the caller PERSISTS what it is handed. Nothing
|
|
950
|
+
// reserves the answer either, so a name is free of the collisions the
|
|
951
|
+
// index knows about and of nothing else — two callers racing get the same
|
|
952
|
+
// proposal, which only uniqueness at the write can catch.
|
|
953
|
+
await this.awaitReferencesLinked(source);
|
|
954
|
+
const nameProvider = this.resolveReferenceServices(source).NameProvider;
|
|
768
955
|
const tier = args.tier ?? 'project';
|
|
769
956
|
if (tier === 'public') {
|
|
770
957
|
return nameProvider.findNextProjectQualifiedName(args.type, args.proposal);
|
|
@@ -772,7 +959,7 @@ export class DataServer<
|
|
|
772
959
|
if (tier === 'local') {
|
|
773
960
|
// Document-scoped uniqueness: the document root is the container.
|
|
774
961
|
const document = await this.modelService.ensureDocumentState(args.uri);
|
|
775
|
-
return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root
|
|
962
|
+
return document.root ? nameProvider.findNextName(args.type, args.proposal, document.root) : args.proposal;
|
|
776
963
|
}
|
|
777
964
|
const project = this.services.workspace.ProjectManager.getProject(uri);
|
|
778
965
|
if (!project) {
|
|
@@ -811,6 +998,9 @@ export class DataServer<
|
|
|
811
998
|
/**
|
|
812
999
|
* Pick the language that owns a reference source, in order:
|
|
813
1000
|
*
|
|
1001
|
+
* 0. A {@link isSyntheticSource} naming its own `language` routes there.
|
|
1002
|
+
* First because every step below infers, and an inference must not
|
|
1003
|
+
* override a caller that has said which grammar it means.
|
|
814
1004
|
* 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
|
|
815
1005
|
* whose URI resolves to a registered language routes by URI.
|
|
816
1006
|
* 2. A single-language workspace always routes to that one language — so
|
|
@@ -829,6 +1019,15 @@ export class DataServer<
|
|
|
829
1019
|
*/
|
|
830
1020
|
protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined {
|
|
831
1021
|
const registry = this.services.ServiceRegistry;
|
|
1022
|
+
if (isSyntheticSource(source) && source.language !== undefined) {
|
|
1023
|
+
const declared = registry.getServicesById(source.language);
|
|
1024
|
+
if (declared) {
|
|
1025
|
+
return declared;
|
|
1026
|
+
}
|
|
1027
|
+
// Falling through on an UNREGISTERED id rather than failing: the id
|
|
1028
|
+
// crosses the wire, so a client built against a head with one more
|
|
1029
|
+
// grammar would otherwise lose queries the steps below can answer.
|
|
1030
|
+
}
|
|
832
1031
|
// `getServicesFor` (non-throwing, one ladder walk) gates the URI lookup:
|
|
833
1032
|
// an extensionless / unregistered URI falls through to the steps below
|
|
834
1033
|
// rather than throwing "no services for the extension ''".
|
|
@@ -839,7 +1038,7 @@ export class DataServer<
|
|
|
839
1038
|
}
|
|
840
1039
|
const all = registry.all;
|
|
841
1040
|
if (all.length === 1) {
|
|
842
|
-
return all[0]
|
|
1041
|
+
return all[0];
|
|
843
1042
|
}
|
|
844
1043
|
if (isElementSource(source)) {
|
|
845
1044
|
const documentUri = this.findElementDocumentUri(source);
|
|
@@ -945,14 +1144,28 @@ export class DataServer<
|
|
|
945
1144
|
// decides policy at its own layer; `root` is optional on the envelope
|
|
946
1145
|
// so the compiler forces that decision. Adopters preferring to throw
|
|
947
1146
|
// override `envelope`.
|
|
948
|
-
return
|
|
949
|
-
uri: uri.toString(),
|
|
950
|
-
version: 0,
|
|
951
|
-
root: undefined,
|
|
952
|
-
diagnostics: [] as TDiagnostic[]
|
|
953
|
-
};
|
|
1147
|
+
return TransferDocument.absent<TTransfer, TDiagnostic>(uri.toString());
|
|
954
1148
|
}
|
|
955
|
-
return this.encoder.toTransferDocument
|
|
1149
|
+
return this.withDirtyState(this.encoder.toTransferDocument(document) as TransferDocument<TTransfer, TDiagnostic>);
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/**
|
|
1153
|
+
* The transfer document a request answers with for `astDocument`, the
|
|
1154
|
+
* store's current `dirty` stamped on it by {@link withDirtyState}. Every
|
|
1155
|
+
* document a request answers with goes through here, so none goes out
|
|
1156
|
+
* without the stamp.
|
|
1157
|
+
*/
|
|
1158
|
+
protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
|
|
1159
|
+
return this.withDirtyState(this.encoder.astDocumentToTransferDocument(astDocument) as TransferDocument<TTransfer, TDiagnostic>);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
/**
|
|
1163
|
+
* `document` with the store's current {@link TransferDocument.dirty}. Read
|
|
1164
|
+
* when the document is sent rather than kept with the build: a save changes
|
|
1165
|
+
* the answer without a rebuild.
|
|
1166
|
+
*/
|
|
1167
|
+
protected withDirtyState(document: TransferDocument<TTransfer, TDiagnostic>): TransferDocument<TTransfer, TDiagnostic> {
|
|
1168
|
+
return { ...document, dirty: this.services.workspace.TextDocuments.isDirty(document.uri) };
|
|
956
1169
|
}
|
|
957
1170
|
|
|
958
1171
|
/**
|
|
@@ -967,6 +1180,59 @@ export class DataServer<
|
|
|
967
1180
|
this.dispatchPhaseEvent(document, cancelToken)
|
|
968
1181
|
)
|
|
969
1182
|
);
|
|
1183
|
+
// The BUILD-phase hook, not the per-document one: this notification is one
|
|
1184
|
+
// message per build rather than one per document, and Langium hands the
|
|
1185
|
+
// whole batch over here. It also does not fire for a cancelled build,
|
|
1186
|
+
// which is what the per-document dispatch has to check by hand.
|
|
1187
|
+
this.disposables.push(
|
|
1188
|
+
this.services.workspace.DocumentBuilder.onBuildPhase(this.options.subscriptionPhase, built => this.dispatchBuiltEvent(built))
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/**
|
|
1193
|
+
* Report the documents that reached {@link DataServerOptions.subscriptionPhase}
|
|
1194
|
+
* and that NOBODY on this
|
|
1195
|
+
* connection is watching — the ones a client was not told about through
|
|
1196
|
+
* {@link dispatchPhaseEvent}, which is gated per URI.
|
|
1197
|
+
*
|
|
1198
|
+
* **The gap this closes is the one no other source can observe.** A document
|
|
1199
|
+
* the client watches, it hears about already. A file changed on disk, the
|
|
1200
|
+
* host's own filesystem watcher reports — and on a browser host, where the
|
|
1201
|
+
* workspace lives behind this head, an external change cannot happen at all.
|
|
1202
|
+
* What is left, and what nothing outside the server can see, is a document
|
|
1203
|
+
* rebuilt because something it DEPENDS ON changed: its file never changed, so
|
|
1204
|
+
* a filesystem watcher is silent by construction, and it has no subscriber, so
|
|
1205
|
+
* the update channel is silent by design. A consumer displaying data derived
|
|
1206
|
+
* from that document — a tree label, a decorator — otherwise goes stale with
|
|
1207
|
+
* no signal from any source, and repairs itself the moment someone opens the
|
|
1208
|
+
* file to investigate, which is what makes it expensive to diagnose later.
|
|
1209
|
+
*
|
|
1210
|
+
* Payload-free on purpose: URIs only, so a client re-reads what it displays
|
|
1211
|
+
* rather than being handed transfer documents it did not ask for. That is the
|
|
1212
|
+
* property the watcher gate protects, and it is preserved here by
|
|
1213
|
+
* carrying no document rather than by gating the message.
|
|
1214
|
+
*
|
|
1215
|
+
* Quiet in the common case. Editing a document that an editor has open leaves
|
|
1216
|
+
* that URI watched and therefore out of this set, so a build with no
|
|
1217
|
+
* dependents produces nothing at all, and workspace initialisation produces
|
|
1218
|
+
* nothing because it does not build to this phase. The ceiling is a
|
|
1219
|
+
* whole-workspace rebuild at the subscription phase: one message, URIs only.
|
|
1220
|
+
*
|
|
1221
|
+
* The URI is canonicalised for the same reason {@link uriWatchRecords} is keyed
|
|
1222
|
+
* that way, and is untested for the same reason as its twin in
|
|
1223
|
+
* {@link dispatchDeleteEvents}: the builder reports URIs out of its own
|
|
1224
|
+
* store, so a non-canonical one cannot be produced without a fixture
|
|
1225
|
+
* asserting a shape the real system never emits.
|
|
1226
|
+
*/
|
|
1227
|
+
protected dispatchBuiltEvent(built: readonly LangiumDocument[]): void {
|
|
1228
|
+
const uris = built
|
|
1229
|
+
.map(document => this.canonicalKey(document.uri.toString()))
|
|
1230
|
+
.filter(uri => !this.uriWatchRecords.get(uri)?.watchers.size);
|
|
1231
|
+
if (uris.length === 0) {
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
this.tracer.debug(`Emit onDocumentsBuilt: ${uris.length} unwatched document(s)`);
|
|
1235
|
+
this.clientProxy.onDocumentsBuilt({ uris });
|
|
970
1236
|
}
|
|
971
1237
|
|
|
972
1238
|
/**
|
|
@@ -987,32 +1253,113 @@ export class DataServer<
|
|
|
987
1253
|
this.disposables.push(this.services.workspace.TextDocuments.onDidSave(event => this.dispatchSaveEvent(event)));
|
|
988
1254
|
}
|
|
989
1255
|
|
|
1256
|
+
/** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
|
|
1257
|
+
protected subscribeToDirtyChanges(): void {
|
|
1258
|
+
this.disposables.push(this.services.workspace.TextDocuments.onDidChangeDirty(event => this.dispatchDirtyEvent(event)));
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* Send a dirty flip to the connection, gated on the URI's watchers as
|
|
1263
|
+
* {@link dispatchSaveEvent} is: the answer at any one moment travels on
|
|
1264
|
+
* every document sent, so a client that watches nothing reads it there.
|
|
1265
|
+
*/
|
|
1266
|
+
protected dispatchDirtyEvent(event: DocumentDirtyChangedEvent): void {
|
|
1267
|
+
const uri = this.canonicalKey(event.uri);
|
|
1268
|
+
if (this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
1269
|
+
this.clientProxy.onDocumentDirtyChanged({ uri, dirty: event.dirty });
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
|
|
990
1273
|
/**
|
|
991
|
-
* Mark the
|
|
992
|
-
* {@link
|
|
993
|
-
*
|
|
994
|
-
*
|
|
1274
|
+
* Mark each document the store releases after its last close, so
|
|
1275
|
+
* {@link dispatchPhaseEvent} broadcasts the following rebuild even without
|
|
1276
|
+
* a watcher. The store rebuilds such a document from its disk content,
|
|
1277
|
+
* discarding unsaved in-session edits, and the last close typically also
|
|
1278
|
+
* removed the last watcher: without the broadcast, a consumer that only
|
|
1279
|
+
* ever fetches via `getModelDocument` keeps showing the discarded state.
|
|
1280
|
+
* The broadcast is de-duplicated against the fingerprint while a watcher
|
|
1281
|
+
* holds one, so a close whose disk state equals the last emitted state
|
|
1282
|
+
* stays silent; with no watcher there is no fingerprint, and every revert
|
|
1283
|
+
* is sent.
|
|
1284
|
+
*
|
|
1285
|
+
* A release, not the close itself: a document whose last client lost its
|
|
1286
|
+
* connection is released only once the revert grace runs out, or when
|
|
1287
|
+
* another client opens it meanwhile, and not at all when a client lost
|
|
1288
|
+
* from it opens it again within its own grace.
|
|
995
1289
|
*/
|
|
996
1290
|
protected subscribeToTextDocumentCloses(): void {
|
|
997
|
-
const textDocuments = this.services.workspace.TextDocuments;
|
|
998
1291
|
this.disposables.push(
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1292
|
+
this.services.workspace.TextDocuments.onDidCloseLastOpen(event => {
|
|
1293
|
+
const uri = this.canonicalKey(event.uri);
|
|
1294
|
+
const record = this.uriWatchRecords.get(uri) ?? { watchers: new Set<string>() };
|
|
1295
|
+
record.revertPending = true;
|
|
1296
|
+
this.uriWatchRecords.set(uri, record);
|
|
1003
1297
|
})
|
|
1004
1298
|
);
|
|
1005
1299
|
}
|
|
1006
1300
|
|
|
1007
|
-
/**
|
|
1301
|
+
/**
|
|
1302
|
+
* Fan out a deletion for each removed URI, to EVERY client on the connection
|
|
1303
|
+
* rather than only to the ones watching that URI.
|
|
1304
|
+
*
|
|
1305
|
+
* **Deliberately ungated, where {@link dispatchPhaseEvent} and
|
|
1306
|
+
* {@link dispatchSaveEvent} are gated.** Those two carry a built document and
|
|
1307
|
+
* fire on every build, so the watcher gate is what keeps bandwidth
|
|
1308
|
+
* proportional to what a client asked for. A deletion is neither: it is one
|
|
1309
|
+
* URI, it is rare, and it reports the workspace's STRUCTURE rather than a
|
|
1310
|
+
* document's content. Gating it forces any consumer that displays the
|
|
1311
|
+
* workspace — a model tree, a file decorator — to learn about disappearances
|
|
1312
|
+
* from a filesystem watcher instead, which a client hosted in a browser has
|
|
1313
|
+
* no way to run: its workspace lives behind the head. A client that does not
|
|
1314
|
+
* care filters on the URI, which costs it a comparison.
|
|
1315
|
+
*
|
|
1316
|
+
* The precedent is the last-close revert broadcast (see
|
|
1317
|
+
* {@link subscribeToTextDocumentCloses}), where the same judgement was already made
|
|
1318
|
+
* in the other direction: a transition that matters enough is delivered
|
|
1319
|
+
* without a subscription.
|
|
1320
|
+
*
|
|
1321
|
+
* Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
|
|
1322
|
+
* listener, which is the only place a deletion is observable: `update`
|
|
1323
|
+
* removes the document before deriving the rebuild set, so it is never built.
|
|
1324
|
+
* That ordering also puts this notification ahead of the `'rebuilt'` events
|
|
1325
|
+
* for the dependents whose references the deletion just broke.
|
|
1326
|
+
*
|
|
1327
|
+
* The `deleted` list arrives already expanded to concrete document URIs —
|
|
1328
|
+
* `deleteDocuments` resolves a directory URI to the documents beneath it — so
|
|
1329
|
+
* no caller has to handle a directory here.
|
|
1330
|
+
*
|
|
1331
|
+
* The URI's fingerprint and revert mark are dropped: they describe a
|
|
1332
|
+
* document that no longer exists. A kept fingerprint is adopted as the
|
|
1333
|
+
* baseline and suppresses the first emit after the file returns with its
|
|
1334
|
+
* previous content.
|
|
1335
|
+
*
|
|
1336
|
+
* The watchers SURVIVE: a recreated file resumes delivering to them with no
|
|
1337
|
+
* re-subscription, and a client that answers the deletion by closing
|
|
1338
|
+
* releases the watch through `closeModelDocument` anyway.
|
|
1339
|
+
*/
|
|
1340
|
+
protected dispatchDeleteEvents(deleted: readonly URI[]): void {
|
|
1341
|
+
for (const removed of deleted) {
|
|
1342
|
+
const uri = this.canonicalKey(removed.toString());
|
|
1343
|
+
const record = this.uriWatchRecords.get(uri);
|
|
1344
|
+
if (record) {
|
|
1345
|
+
record.fingerprint = undefined;
|
|
1346
|
+
record.revertPending = undefined;
|
|
1347
|
+
record.sentVersion = undefined;
|
|
1348
|
+
this.pruneUriWatchRecord(uri);
|
|
1349
|
+
}
|
|
1350
|
+
this.clientProxy.onDocumentDeleted({ uri });
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
/** Fan out a save event for the document's URI, gated on the URI's watchers. */
|
|
1008
1355
|
protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void {
|
|
1009
1356
|
// The save event arrives under the CLIENT URI the text store keys by (e.g. a
|
|
1010
|
-
// symlink path S);
|
|
1357
|
+
// symlink path S); `uriWatchRecords` and `dispatchPhaseEvent` key by the
|
|
1011
1358
|
// CANONICAL identity R. Canonicalize before both the gate and the envelope so
|
|
1012
1359
|
// a save of a symlinked file isn't silently dropped (and the envelope resolves
|
|
1013
1360
|
// the R-keyed document rather than missing into an empty one).
|
|
1014
1361
|
const uri = this.canonicalKey(event.document.uri);
|
|
1015
|
-
if (!this.
|
|
1362
|
+
if (!this.uriWatchRecords.get(uri)?.watchers.size) {
|
|
1016
1363
|
return;
|
|
1017
1364
|
}
|
|
1018
1365
|
const response = this.envelope(UriUtils.toUri(uri));
|
|
@@ -1032,13 +1379,25 @@ export class DataServer<
|
|
|
1032
1379
|
* out to multiple local subscribers with an `Emitter<T>` — the
|
|
1033
1380
|
* framework deliberately does NOT promise multi-listener semantics.
|
|
1034
1381
|
*
|
|
1035
|
-
*
|
|
1036
|
-
*
|
|
1037
|
-
*
|
|
1038
|
-
*
|
|
1039
|
-
*
|
|
1040
|
-
*
|
|
1041
|
-
*
|
|
1382
|
+
* An event for a URI no client watches is NOT sent over the wire, so
|
|
1383
|
+
* bandwidth scales with watched URIs rather than with phase events; a
|
|
1384
|
+
* pending revert mark is the exception (see
|
|
1385
|
+
* {@link subscribeToTextDocumentCloses}).
|
|
1386
|
+
*
|
|
1387
|
+
* An event for a rebuild with no observable change since the last emit is
|
|
1388
|
+
* suppressed against the URI's fingerprint. Such rebuilds are routine: a
|
|
1389
|
+
* second client attaching to an open document makes
|
|
1390
|
+
* `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
|
|
1391
|
+
* to re-trigger the build, and Langium rebuilds a document when a
|
|
1392
|
+
* dependency changes even if its diagnostics come out the same. Sent at a
|
|
1393
|
+
* version this head has not sent, they reach watchers as `'changed'`, and a
|
|
1394
|
+
* watcher that reads `'changed'` as another client's write and resets its
|
|
1395
|
+
* root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
|
|
1396
|
+
* fingerprint, so the first event after a watch is de-duplicated against
|
|
1397
|
+
* the state the watcher just fetched; it goes with the last watcher, so the
|
|
1398
|
+
* next first watch re-baselines rather than adopting a stale digest. A
|
|
1399
|
+
* cyrb53 digest keeps its memory constant in document size; see
|
|
1400
|
+
* {@link computeDocumentFingerprint} for the inputs.
|
|
1042
1401
|
*/
|
|
1043
1402
|
protected dispatchPhaseEvent(document: LangiumDocument, cancelToken: CancellationToken): void {
|
|
1044
1403
|
if (cancelToken.isCancellationRequested) {
|
|
@@ -1050,16 +1409,23 @@ export class DataServer<
|
|
|
1050
1409
|
return;
|
|
1051
1410
|
}
|
|
1052
1411
|
const uri = document.uri.toString();
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
// the author lookup would yield.
|
|
1057
|
-
const revertedOnClose = this.pendingRevertBroadcasts.delete(uri);
|
|
1058
|
-
if (!this.subscriptions.has(uri) && !revertedOnClose) {
|
|
1412
|
+
const record = this.uriWatchRecords.get(uri);
|
|
1413
|
+
const revertedOnClose = record?.revertPending === true;
|
|
1414
|
+
if (!record || (record.watchers.size === 0 && !revertedOnClose)) {
|
|
1059
1415
|
return;
|
|
1060
1416
|
}
|
|
1417
|
+
if (revertedOnClose) {
|
|
1418
|
+
// Consumed even when watchers exist — the regular dispatch below
|
|
1419
|
+
// serves them, and the mark's attribution is more precise than the
|
|
1420
|
+
// post-close unknown client the manager's attribution would yield.
|
|
1421
|
+
// With no watcher the record goes now, so the fingerprint written
|
|
1422
|
+
// below lands on a detached record and the next first watch
|
|
1423
|
+
// re-baselines instead of adopting it.
|
|
1424
|
+
record.revertPending = undefined;
|
|
1425
|
+
this.pruneUriWatchRecord(uri);
|
|
1426
|
+
}
|
|
1061
1427
|
const fingerprint = this.computeDocumentFingerprint(document);
|
|
1062
|
-
if (
|
|
1428
|
+
if (record.fingerprint === fingerprint) {
|
|
1063
1429
|
// A rebuild that produced no observable change since the last emit —
|
|
1064
1430
|
// suppressed so RPC subscribers don't see a no-op broadcast. Logged at
|
|
1065
1431
|
// debug so a *needed* re-broadcast wrongly suppressed by this dedup
|
|
@@ -1067,11 +1433,20 @@ export class DataServer<
|
|
|
1067
1433
|
this.tracer.withUri(uri).debug(`Suppress onDocumentUpdated v${document.textDocument.version}: fingerprint unchanged`);
|
|
1068
1434
|
return;
|
|
1069
1435
|
}
|
|
1070
|
-
|
|
1436
|
+
record.fingerprint = fingerprint;
|
|
1437
|
+
// The manager's attribution, so this head names the same client as the
|
|
1438
|
+
// in-process heads do for one build, except for a version this head
|
|
1439
|
+
// already sent; see `DataServerUriWatchRecord.sentVersion`.
|
|
1440
|
+
const version = this.services.workspace.AstDocumentManager.isOpen(uri) ? document.textDocument.version : undefined;
|
|
1441
|
+
const { reason, sourceClientId } =
|
|
1442
|
+
version !== undefined && record.sentVersion === version
|
|
1443
|
+
? { reason: 'rebuilt' as const, sourceClientId: UNKNOWN_CLIENT_ID }
|
|
1444
|
+
: this.services.workspace.AstDocumentManager.attributeUpdate(document);
|
|
1445
|
+
record.sentVersion = version;
|
|
1071
1446
|
const event: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic> = {
|
|
1072
1447
|
document: this.envelope(document.uri),
|
|
1073
|
-
sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID :
|
|
1074
|
-
reason
|
|
1448
|
+
sourceClientId: revertedOnClose ? REVERT_ON_CLOSE_CLIENT_ID : sourceClientId,
|
|
1449
|
+
reason
|
|
1075
1450
|
};
|
|
1076
1451
|
this.tracer
|
|
1077
1452
|
.withUri(uri)
|
|
@@ -1119,31 +1494,6 @@ export class DataServer<
|
|
|
1119
1494
|
return [];
|
|
1120
1495
|
}
|
|
1121
1496
|
|
|
1122
|
-
/**
|
|
1123
|
-
* Discriminate the reason for a phase-event-driven update notification.
|
|
1124
|
-
* Uses the most recent `DocumentBuilder.onUpdate` snapshot:
|
|
1125
|
-
* - URI in the `deleted` list → `'deleted'`
|
|
1126
|
-
* - URI in the `changed` list → `'changed'` (the URI was passed to
|
|
1127
|
-
* `documentBuilder.update(changed, deleted)`, which spans `didChange`
|
|
1128
|
-
* text-document events and programmatic `update([uri], [])` calls).
|
|
1129
|
-
* - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
|
|
1130
|
-
* because something it depends on changed; its own text wasn't flagged).
|
|
1131
|
-
*
|
|
1132
|
-
* `'saved'` is NOT emitted from this code path — saves take the dedicated
|
|
1133
|
-
* `DataClientProtocol.onDocumentSaved` channel; adopters that want a
|
|
1134
|
-
* unified update stream synthesise `'saved'` in their bridge layer.
|
|
1135
|
-
*/
|
|
1136
|
-
protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'] {
|
|
1137
|
-
const last = this.lastBuildUpdate;
|
|
1138
|
-
if (last?.deleted.some(deleted => UriUtils.equals(deleted, uri))) {
|
|
1139
|
-
return 'deleted';
|
|
1140
|
-
}
|
|
1141
|
-
if (last?.changed.some(changed => UriUtils.equals(changed, uri))) {
|
|
1142
|
-
return 'changed';
|
|
1143
|
-
}
|
|
1144
|
-
return 'rebuilt';
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
1497
|
/**
|
|
1148
1498
|
* Subscribe to the project tier's change channel and re-fan registry
|
|
1149
1499
|
* diffs into per-project wire notifications. The internal
|
|
@@ -1187,20 +1537,6 @@ export class DataServer<
|
|
|
1187
1537
|
}
|
|
1188
1538
|
}
|
|
1189
1539
|
|
|
1190
|
-
/**
|
|
1191
|
-
* Resolve the wire-level `sourceClientId` for `document`'s events — the client
|
|
1192
|
-
* that authored its current version, from the version-author history on
|
|
1193
|
-
* `HydraniumTextDocuments`. The protocol-level counterpart of the internal
|
|
1194
|
-
* `AstDocumentManager.getAuthor`: a framework-internal rebuild has no author,
|
|
1195
|
-
* so this surfaces the {@link UNKNOWN_CLIENT_ID} presentation default. Adopters
|
|
1196
|
-
* that rebuild through non-text-document channels override to derive a
|
|
1197
|
-
* source id of their own.
|
|
1198
|
-
*/
|
|
1199
|
-
protected resolveSourceClientId(document: LangiumDocument): string {
|
|
1200
|
-
const author = this.services.workspace.TextDocuments.getAuthor(document.textDocument.uri, document.textDocument.version);
|
|
1201
|
-
return author ?? UNKNOWN_CLIENT_ID;
|
|
1202
|
-
}
|
|
1203
|
-
|
|
1204
1540
|
// --- Diagnostics (DataServerDiagnosticsProtocol) ---------------------------
|
|
1205
1541
|
// Computed in THIS process: the data-server child holds the model store, so
|
|
1206
1542
|
// these snapshots reflect the heap that actually carries the workspace
|
|
@@ -1243,7 +1579,7 @@ export class DataServer<
|
|
|
1243
1579
|
|
|
1244
1580
|
async stopProfiling(args: StopProfilingArgs): Promise<string> {
|
|
1245
1581
|
if (!this.activeProfile) {
|
|
1246
|
-
throw
|
|
1582
|
+
throw noActiveProfileError();
|
|
1247
1583
|
}
|
|
1248
1584
|
const capture = this.activeProfile;
|
|
1249
1585
|
this.activeProfile = undefined;
|
|
@@ -1262,7 +1598,7 @@ export class DataServer<
|
|
|
1262
1598
|
/** Resolve a partial options object into a fully-defaulted form. */
|
|
1263
1599
|
protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions {
|
|
1264
1600
|
const additionalMethods = partial.additionalMethods ?? [];
|
|
1265
|
-
const builtIn = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS]
|
|
1601
|
+
const builtIn: readonly string[] = [...DATA_SERVER_PROTOCOL_METHODS, ...DATA_SERVER_DIAGNOSTICS_METHODS];
|
|
1266
1602
|
const overlap = additionalMethods.filter(name => builtIn.includes(name));
|
|
1267
1603
|
if (overlap.length > 0) {
|
|
1268
1604
|
throw new Error(
|
|
@@ -1276,7 +1612,8 @@ export class DataServer<
|
|
|
1276
1612
|
methodNamespace: partial.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
|
|
1277
1613
|
additionalMethods,
|
|
1278
1614
|
excludedMethods: partial.excludedMethods ?? [],
|
|
1279
|
-
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics()
|
|
1615
|
+
diagnostics: partial.diagnostics ?? defaultDataServerDiagnostics(),
|
|
1616
|
+
referenceSettleTimeoutMs: partial.referenceSettleTimeoutMs ?? DataServer.DEFAULT_OPTIONS.referenceSettleTimeoutMs
|
|
1280
1617
|
};
|
|
1281
1618
|
}
|
|
1282
1619
|
}
|