@hydranium/client-theia 1.0.0-next.37 → 1.0.0-next.371
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 +52 -80
- package/lib/browser/browser-capture.js.map +1 -1
- package/lib/browser/channel-logger.d.ts +4 -3
- package/lib/browser/channel-logger.d.ts.map +1 -1
- package/lib/browser/channel-logger.js +11 -19
- package/lib/browser/channel-logger.js.map +1 -1
- package/lib/browser/connection-diagnostics-contribution.d.ts +73 -0
- package/lib/browser/connection-diagnostics-contribution.d.ts.map +1 -0
- package/lib/browser/connection-diagnostics-contribution.js +162 -0
- package/lib/browser/connection-diagnostics-contribution.js.map +1 -0
- package/lib/browser/connection-reporter.d.ts +57 -0
- package/lib/browser/connection-reporter.d.ts.map +1 -0
- package/lib/browser/connection-reporter.js +104 -0
- package/lib/browser/connection-reporter.js.map +1 -0
- package/lib/browser/editor-disk-sync.d.ts +142 -0
- package/lib/browser/editor-disk-sync.d.ts.map +1 -0
- package/lib/browser/editor-disk-sync.js +250 -0
- package/lib/browser/editor-disk-sync.js.map +1 -0
- package/lib/browser/hydranium-file-service.d.ts +44 -0
- package/lib/browser/hydranium-file-service.d.ts.map +1 -0
- package/lib/browser/hydranium-file-service.js +61 -0
- package/lib/browser/hydranium-file-service.js.map +1 -0
- package/lib/browser/index.d.ts +5 -0
- package/lib/browser/index.d.ts.map +1 -1
- package/lib/browser/index.js +5 -0
- package/lib/browser/index.js.map +1 -1
- package/lib/browser/log-level-preference.d.ts.map +1 -1
- package/lib/browser/log-level-preference.js +11 -0
- package/lib/browser/log-level-preference.js.map +1 -1
- package/lib/browser/memory-diagnostics-contribution.d.ts +1 -1
- package/lib/browser/memory-diagnostics-contribution.d.ts.map +1 -1
- package/lib/browser/memory-diagnostics-contribution.js +1 -1
- package/lib/browser/memory-diagnostics-contribution.js.map +1 -1
- package/lib/browser/session-aware-connection-source.d.ts +104 -0
- package/lib/browser/session-aware-connection-source.d.ts.map +1 -0
- package/lib/browser/session-aware-connection-source.js +193 -0
- package/lib/browser/session-aware-connection-source.js.map +1 -0
- package/lib/common/clock.d.ts +19 -0
- package/lib/common/clock.d.ts.map +1 -0
- package/lib/common/clock.js +13 -0
- package/lib/common/clock.js.map +1 -0
- package/lib/common/connection-resilience-options.d.ts +30 -0
- package/lib/common/connection-resilience-options.d.ts.map +1 -0
- package/lib/common/connection-resilience-options.js +11 -0
- package/lib/common/connection-resilience-options.js.map +1 -0
- package/lib/common/framed-socket-write-buffer.d.ts +173 -0
- package/lib/common/framed-socket-write-buffer.d.ts.map +1 -0
- package/lib/common/framed-socket-write-buffer.js +293 -0
- package/lib/common/framed-socket-write-buffer.js.map +1 -0
- package/lib/common/inbound-message-sequence.d.ts +56 -0
- package/lib/common/inbound-message-sequence.d.ts.map +1 -0
- package/lib/common/inbound-message-sequence.js +98 -0
- package/lib/common/inbound-message-sequence.js.map +1 -0
- package/lib/common/index.d.ts +13 -0
- package/lib/common/index.d.ts.map +1 -0
- package/lib/common/index.js +32 -0
- package/lib/common/index.js.map +1 -0
- package/lib/node/abstract-socket-forwarding-connection-handler.d.ts +16 -12
- package/lib/node/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
- package/lib/node/abstract-socket-forwarding-connection-handler.js +94 -31
- package/lib/node/abstract-socket-forwarding-connection-handler.js.map +1 -1
- package/lib/node/index.d.ts +2 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +2 -0
- package/lib/node/index.js.map +1 -1
- package/lib/node/session-bound-frontend-connection-service.d.ts +122 -0
- package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
- package/lib/node/session-bound-frontend-connection-service.js +236 -0
- package/lib/node/session-bound-frontend-connection-service.js.map +1 -0
- package/lib/node/socket-channel-forwarder.d.ts +54 -0
- package/lib/node/socket-channel-forwarder.d.ts.map +1 -0
- package/lib/node/socket-channel-forwarder.js +95 -0
- package/lib/node/socket-channel-forwarder.js.map +1 -0
- package/lib/testing/stub-inversify-context.js.map +1 -1
- package/lib/testing/stub-output-channel.js.map +1 -1
- package/package.json +33 -34
- package/src/browser/browser-capture.ts +1 -1
- package/src/browser/channel-logger.ts +11 -19
- package/src/browser/connection-diagnostics-contribution.ts +146 -0
- package/src/browser/connection-reporter.ts +121 -0
- package/src/browser/editor-disk-sync.ts +253 -0
- package/src/browser/hydranium-file-service.ts +56 -0
- package/src/browser/index.ts +5 -0
- package/src/browser/log-level-preference.ts +11 -0
- package/src/browser/memory-diagnostics-contribution.ts +4 -3
- package/src/browser/session-aware-connection-source.ts +205 -0
- package/src/common/clock.ts +20 -0
- package/src/common/connection-resilience-options.ts +30 -0
- package/src/common/framed-socket-write-buffer.ts +345 -0
- package/src/common/inbound-message-sequence.ts +102 -0
- package/src/common/index.ts +16 -0
- package/src/node/abstract-socket-forwarding-connection-handler.ts +85 -36
- package/src/node/index.ts +2 -0
- package/src/node/session-bound-frontend-connection-service.ts +264 -0
- package/src/node/socket-channel-forwarder.ts +101 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/********************************************************************************
|
|
2
|
+
* Copyright (c) 2026 EclipseSource and others.
|
|
3
|
+
*
|
|
4
|
+
* This program and the accompanying materials are made available under the
|
|
5
|
+
* terms of the MIT License which is available in the project root.
|
|
6
|
+
*
|
|
7
|
+
* SPDX-License-Identifier: MIT
|
|
8
|
+
********************************************************************************/
|
|
9
|
+
|
|
10
|
+
import { CONNECTION_LOG_PREFIX } from './framed-socket-write-buffer';
|
|
11
|
+
|
|
12
|
+
/** The socket.io event that carries the highest message number a side has accepted. */
|
|
13
|
+
export const ACKNOWLEDGEMENT_EVENT = 'hydranium:ack';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What one side has received on a session: drops a message it already accepted
|
|
17
|
+
* and acknowledges the rest.
|
|
18
|
+
*
|
|
19
|
+
* The peer resends everything unacknowledged when a session resumes, because it
|
|
20
|
+
* cannot tell which of its messages died with the old socket, so every resumed
|
|
21
|
+
* session can repeat messages already delivered. Delivering one twice corrupts
|
|
22
|
+
* anything applied by position, just as losing one does.
|
|
23
|
+
*
|
|
24
|
+
* Acknowledges once enough has arrived, and otherwise after a short delay. A
|
|
25
|
+
* timer alone is not enough: a background tab throttles timers, and the peer
|
|
26
|
+
* holds every unacknowledged message until the acknowledgement arrives. The
|
|
27
|
+
* first message of a session is acknowledged at once, because the peer resends
|
|
28
|
+
* nothing until an acknowledgement shows it may.
|
|
29
|
+
*
|
|
30
|
+
* Belongs to one session. A new session numbers from the start again, so it
|
|
31
|
+
* needs a new instance.
|
|
32
|
+
*/
|
|
33
|
+
export class InboundMessageSequence {
|
|
34
|
+
static readonly ACKNOWLEDGE_AFTER_MESSAGES = 64;
|
|
35
|
+
static readonly ACKNOWLEDGE_AFTER_BYTES = 32 * 1024;
|
|
36
|
+
static readonly ACKNOWLEDGE_DELAY_MS = 100;
|
|
37
|
+
|
|
38
|
+
protected lastAccepted = 0;
|
|
39
|
+
protected messagesSinceAcknowledgement = 0;
|
|
40
|
+
protected bytesSinceAcknowledgement = 0;
|
|
41
|
+
protected acknowledgementTimer: ReturnType<typeof setTimeout> | undefined;
|
|
42
|
+
|
|
43
|
+
constructor(protected readonly sendAcknowledgement: (sequence: number) => void) {}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Whether to deliver a message that arrived with `sequence`.
|
|
47
|
+
*
|
|
48
|
+
* A message without a number comes from a peer that does not number them,
|
|
49
|
+
* and is delivered as it is. A duplicate is still acknowledged: the peer
|
|
50
|
+
* resent it because an earlier acknowledgement was lost, and keeps it until
|
|
51
|
+
* one arrives.
|
|
52
|
+
*
|
|
53
|
+
* A skipped number is delivered past, with a warning: the skipped messages
|
|
54
|
+
* are lost, and this is the one place that can tell.
|
|
55
|
+
*/
|
|
56
|
+
accept(sequence: unknown, bytes: number): boolean {
|
|
57
|
+
if (typeof sequence !== 'number') {
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
const isFirst = this.lastAccepted === 0;
|
|
61
|
+
const isNew = sequence > this.lastAccepted;
|
|
62
|
+
if (isNew) {
|
|
63
|
+
if (sequence > this.lastAccepted + 1) {
|
|
64
|
+
const missing = sequence - this.lastAccepted - 1;
|
|
65
|
+
console.warn(
|
|
66
|
+
`${CONNECTION_LOG_PREFIX} lost ${missing} message(s), numbered ${this.lastAccepted + 1} to ${sequence - 1}; ` +
|
|
67
|
+
'they never arrived and nothing will resend them'
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
this.lastAccepted = sequence;
|
|
71
|
+
}
|
|
72
|
+
this.messagesSinceAcknowledgement++;
|
|
73
|
+
this.bytesSinceAcknowledgement += bytes;
|
|
74
|
+
if (
|
|
75
|
+
isFirst ||
|
|
76
|
+
this.messagesSinceAcknowledgement >= InboundMessageSequence.ACKNOWLEDGE_AFTER_MESSAGES ||
|
|
77
|
+
this.bytesSinceAcknowledgement >= InboundMessageSequence.ACKNOWLEDGE_AFTER_BYTES
|
|
78
|
+
) {
|
|
79
|
+
this.acknowledge();
|
|
80
|
+
} else {
|
|
81
|
+
this.acknowledgementTimer ??= setTimeout(() => this.acknowledge(), InboundMessageSequence.ACKNOWLEDGE_DELAY_MS);
|
|
82
|
+
}
|
|
83
|
+
return isNew;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Sends the acknowledgement now rather than waiting for more traffic. */
|
|
87
|
+
acknowledge(): void {
|
|
88
|
+
this.cancelTimer();
|
|
89
|
+
this.messagesSinceAcknowledgement = 0;
|
|
90
|
+
this.bytesSinceAcknowledgement = 0;
|
|
91
|
+
this.sendAcknowledgement(this.lastAccepted);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
dispose(): void {
|
|
95
|
+
this.cancelTimer();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
protected cancelTimer(): void {
|
|
99
|
+
clearTimeout(this.acknowledgementTimer);
|
|
100
|
+
this.acknowledgementTimer = undefined;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/********************************************************************************
|
|
2
|
+
* Copyright (c) 2026 CrossBreeze, EclipseSource and others.
|
|
3
|
+
*
|
|
4
|
+
* This program and the accompanying materials are made available under the
|
|
5
|
+
* terms of the MIT License which is available in the project root.
|
|
6
|
+
*
|
|
7
|
+
* SPDX-License-Identifier: MIT
|
|
8
|
+
********************************************************************************/
|
|
9
|
+
|
|
10
|
+
// Environment-neutral primitives that the browser and the server tiers each
|
|
11
|
+
// bind for their own side, such as the buffer for each half of the socket.
|
|
12
|
+
// Kept out of both tier barrels for that reason.
|
|
13
|
+
export * from './framed-socket-write-buffer';
|
|
14
|
+
export * from './inbound-message-sequence';
|
|
15
|
+
export * from './connection-resilience-options';
|
|
16
|
+
export * from './clock';
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* SPDX-License-Identifier: MIT
|
|
8
8
|
********************************************************************************/
|
|
9
9
|
|
|
10
|
+
import { SystemClock, describeError, describeErrorWithStack } from '@hydranium/protocol';
|
|
10
11
|
import {
|
|
11
12
|
type Channel,
|
|
12
13
|
CommandService,
|
|
@@ -16,10 +17,12 @@ import {
|
|
|
16
17
|
type MessageProvider,
|
|
17
18
|
MessageService
|
|
18
19
|
} from '@theia/core';
|
|
19
|
-
import {
|
|
20
|
+
import { AbstractChannel } from '@theia/core/lib/common/message-rpc/channel';
|
|
20
21
|
import { Deferred } from '@theia/core/lib/common/promise-util';
|
|
21
|
-
import { inject, injectable } from '@theia/core/shared/inversify';
|
|
22
|
+
import { inject, injectable, optional } from '@theia/core/shared/inversify';
|
|
22
23
|
import * as net from 'node:net';
|
|
24
|
+
import { Clock } from '../common/clock';
|
|
25
|
+
import { SocketChannelForwarder } from './socket-channel-forwarder';
|
|
23
26
|
|
|
24
27
|
/** Resolved configuration for a {@link AbstractSocketForwardingConnectionHandler}.
|
|
25
28
|
* A head-specific subclass derives these from its own (adopter-facing) options
|
|
@@ -61,12 +64,10 @@ export interface SocketForwardingConnectionHandlerOptions {
|
|
|
61
64
|
* the same wire protocol the server speaks, so the backend performs no semantic
|
|
62
65
|
* re-proxy — it relays bytes only and stays oblivious to the server's method set.
|
|
63
66
|
*
|
|
64
|
-
* The
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
* behind the hook is what lets the data head stay GLSP-free while sharing the
|
|
69
|
-
* port-discovery + buffer-and-replay race fix + connect orchestration here.
|
|
67
|
+
* The byte forwarder that bridges the channel and the socket is
|
|
68
|
+
* {@link forwardToSocketConnection}; both heads use {@link SocketChannelForwarder},
|
|
69
|
+
* and the port discovery, buffer-and-replay race fix and connect orchestration
|
|
70
|
+
* here are shared.
|
|
70
71
|
*/
|
|
71
72
|
@injectable()
|
|
72
73
|
export abstract class AbstractSocketForwardingConnectionHandler implements ConnectionHandler {
|
|
@@ -76,6 +77,8 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
|
|
|
76
77
|
// not the spawned language-server process, so the framework `LspLogger`
|
|
77
78
|
// (which needs the Langium connection/services) is out of reach here.
|
|
78
79
|
@inject(ILogger) protected readonly logger!: ILogger;
|
|
80
|
+
/** The clock each {@link SocketChannelForwarder} bounds its flush on: the container's {@link Clock}, or a `SystemClock`. */
|
|
81
|
+
@inject(Clock) @optional() protected readonly clock: Clock = new SystemClock();
|
|
79
82
|
|
|
80
83
|
readonly path: string;
|
|
81
84
|
|
|
@@ -114,31 +117,66 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
|
|
|
114
117
|
// window.
|
|
115
118
|
const buffered: MessageProvider[] = [];
|
|
116
119
|
const bufferSub = channel.onMessage(provider => buffered.push(provider));
|
|
120
|
+
const closed = new AbortController();
|
|
121
|
+
const closeSub = channel.onClose(() => closed.abort());
|
|
117
122
|
try {
|
|
118
|
-
const port = await this.findPort();
|
|
123
|
+
const port = await this.findPort(closed.signal);
|
|
124
|
+
closed.signal.throwIfAborted();
|
|
119
125
|
this.logger.info(`[${this.logComponent}] Connecting to ${this.serverName} on port ${port}...`);
|
|
120
126
|
await this.connectToServer(channel, port, { bufferSub, buffered });
|
|
121
127
|
this.logger.info(`[${this.logComponent}] Connected to ${this.serverName} on port ${port}.`);
|
|
122
128
|
} catch (error) {
|
|
123
129
|
bufferSub.dispose();
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
130
|
+
if (closed.signal.aborted) {
|
|
131
|
+
this.logger.debug(`[${this.logComponent}] Stopped connecting to ${this.serverName}: the frontend closed the channel.`);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
this.logger.error(`[${this.logComponent}] Could not connect to ${this.serverName}: ${describeErrorWithStack(error)}`);
|
|
135
|
+
this.reportConnectFailure(describeError(error));
|
|
136
|
+
// Closed so the frontend learns of it: left open, the channel has no
|
|
137
|
+
// server behind it, and every request on it waits for good.
|
|
138
|
+
channel.close();
|
|
139
|
+
} finally {
|
|
140
|
+
closeSub.dispose();
|
|
127
141
|
}
|
|
128
142
|
}
|
|
129
143
|
|
|
130
|
-
|
|
144
|
+
/** Tell the user this handler gave up; `message` is the reason it logged. */
|
|
145
|
+
protected reportConnectFailure(message: string): void {
|
|
146
|
+
this.messageService.error(`Could not connect to ${this.serverName}: ` + message);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Poll the port command until it answers, its attempts run out, or `signal` aborts. */
|
|
150
|
+
protected async findPort(signal?: AbortSignal): Promise<number> {
|
|
131
151
|
const pendingContent = new Deferred<number>();
|
|
132
152
|
let counter = 0;
|
|
153
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
154
|
+
const stop = (): void => {
|
|
155
|
+
clearTimeout(timer);
|
|
156
|
+
pendingContent.reject(signal?.reason);
|
|
157
|
+
};
|
|
158
|
+
if (signal?.aborted) {
|
|
159
|
+
stop();
|
|
160
|
+
}
|
|
161
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
133
162
|
const tryQueryingPort = (): void => {
|
|
134
|
-
|
|
163
|
+
if (signal?.aborted) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
timer = setTimeout(async () => {
|
|
135
167
|
try {
|
|
136
168
|
const port = await this.commandService.executeCommand<number>(this.portCommand);
|
|
137
|
-
|
|
138
|
-
|
|
169
|
+
// An empty answer fails the attempt like a throw does: left
|
|
170
|
+
// unanswered, it neither resolves nor re-queues, and the lookup
|
|
171
|
+
// stays pending with nothing logged.
|
|
172
|
+
if (!port) {
|
|
173
|
+
throw new Error(`Port command '${this.portCommand}' answered without a port.`);
|
|
139
174
|
}
|
|
175
|
+
pendingContent.resolve(port);
|
|
140
176
|
} catch (error) {
|
|
141
177
|
counter++;
|
|
178
|
+
const message = describeError(error);
|
|
179
|
+
this.logger.debug(`[${this.logComponent}] Port command '${this.portCommand}' attempt ${counter} failed: ${message}`);
|
|
142
180
|
if (this.findPortAttempts >= 0 && counter > this.findPortAttempts) {
|
|
143
181
|
pendingContent.reject(error);
|
|
144
182
|
} else {
|
|
@@ -159,9 +197,20 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
|
|
|
159
197
|
const connected = new Deferred<void>();
|
|
160
198
|
const socket = new net.Socket();
|
|
161
199
|
this.onSocketCreated?.(socket);
|
|
162
|
-
|
|
200
|
+
let ready = false;
|
|
201
|
+
socket.on('ready', () => {
|
|
202
|
+
ready = true;
|
|
203
|
+
connected.resolve();
|
|
204
|
+
});
|
|
163
205
|
socket.on('close', () => connected.reject(`Socket to ${this.serverName} was closed.`));
|
|
164
|
-
|
|
206
|
+
// Before `ready` the error fails the connect, whose caller logs it; the `close` that follows rejects too late to count.
|
|
207
|
+
socket.on('error', error => {
|
|
208
|
+
if (ready) {
|
|
209
|
+
this.logger.error(`Error occurred with the ${this.serverName} socket: ${describeErrorWithStack(error)}`);
|
|
210
|
+
} else {
|
|
211
|
+
connected.reject(error);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
165
214
|
// Synchronous hand-off: dispose the pre-forward buffer FIRST, then wire the
|
|
166
215
|
// forwarder, then replay buffered messages. The event loop cannot
|
|
167
216
|
// interleave between these synchronous statements, so no message is both
|
|
@@ -172,10 +221,15 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
|
|
|
172
221
|
if (preForwardBuffer && preForwardBuffer.buffered.length > 0) {
|
|
173
222
|
this.replayBufferedMessages(channel, preForwardBuffer.buffered);
|
|
174
223
|
}
|
|
175
|
-
if (channel instanceof
|
|
224
|
+
if (channel instanceof AbstractChannel) {
|
|
176
225
|
socket.on('error', error => channel.onErrorEmitter.fire(error));
|
|
177
226
|
}
|
|
178
|
-
|
|
227
|
+
// `127.0.0.1`, not the `localhost` Node dials when no host is given, and it
|
|
228
|
+
// has to match the head: the socket launchers bind `127.0.0.1` by default,
|
|
229
|
+
// so on a dual-stack machine where `localhost` resolves to `::1` first the
|
|
230
|
+
// dial fails as ECONNREFUSED with nothing in the message naming the address
|
|
231
|
+
// family as the cause.
|
|
232
|
+
socket.connect({ port, host: '127.0.0.1' });
|
|
179
233
|
setTimeout(() => connected.reject('Timeout reached.'), this.connectTimeoutMs);
|
|
180
234
|
return connected.promise;
|
|
181
235
|
}
|
|
@@ -185,34 +239,29 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
|
|
|
185
239
|
* relay both ways. Called once, after the socket is created and the
|
|
186
240
|
* pre-forward buffer is about to be replayed.
|
|
187
241
|
*/
|
|
188
|
-
protected
|
|
242
|
+
protected forwardToSocketConnection(clientChannel: Channel, socket: net.Socket): Disposable {
|
|
243
|
+
return new SocketChannelForwarder(clientChannel, socket, this.clock);
|
|
244
|
+
}
|
|
189
245
|
|
|
190
246
|
/**
|
|
191
|
-
* Re-fire pre-forward buffered `MessageProvider`s on the channel's
|
|
247
|
+
* Re-fire pre-forward buffered `MessageProvider`s on the channel's
|
|
192
248
|
* `onMessageEmitter` so the now-subscribed forwarder picks them up in arrival
|
|
193
249
|
* order. `MessageProvider` is a thunk (`() => ReadBuffer`) — buffering does
|
|
194
250
|
* not consume the read position, so replay produces the same bytes the
|
|
195
251
|
* forwarder would have seen if wired earlier.
|
|
196
252
|
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
*
|
|
253
|
+
* The emitter is public on `AbstractChannel`; the `Channel` interface
|
|
254
|
+
* carries just its `Event`, so any other channel has its messages logged as
|
|
255
|
+
* dropped. A Theia rename of the emitter fails to compile here.
|
|
200
256
|
*/
|
|
201
257
|
protected replayBufferedMessages(channel: Channel, buffered: MessageProvider[]): void {
|
|
202
|
-
if (!(channel instanceof
|
|
203
|
-
this.logger.
|
|
204
|
-
return;
|
|
205
|
-
}
|
|
206
|
-
const internals = channel as unknown as { onMessageEmitter?: { fire(provider: MessageProvider): void } };
|
|
207
|
-
if (!internals.onMessageEmitter) {
|
|
208
|
-
this.logger.warn(
|
|
209
|
-
`[${this.logComponent}] dropping ${buffered.length} pre-forward message(s) — ForwardingChannel.onMessageEmitter not accessible`
|
|
210
|
-
);
|
|
258
|
+
if (!(channel instanceof AbstractChannel)) {
|
|
259
|
+
this.logger.error(`[${this.logComponent}] dropping ${buffered.length} pre-forward message(s) — channel is not an AbstractChannel`);
|
|
211
260
|
return;
|
|
212
261
|
}
|
|
213
|
-
this.logger.
|
|
262
|
+
this.logger.debug(`[${this.logComponent}] replaying ${buffered.length} pre-forward message(s) onto the wired socket forwarder`);
|
|
214
263
|
for (const provider of buffered) {
|
|
215
|
-
|
|
264
|
+
channel.onMessageEmitter.fire(provider);
|
|
216
265
|
}
|
|
217
266
|
}
|
|
218
267
|
}
|
package/src/node/index.ts
CHANGED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/********************************************************************************
|
|
2
|
+
* Copyright (c) 2026 CrossBreeze, EclipseSource and others.
|
|
3
|
+
*
|
|
4
|
+
* This program and the accompanying materials are made available under the
|
|
5
|
+
* terms of the MIT License which is available in the project root.
|
|
6
|
+
*
|
|
7
|
+
* SPDX-License-Identifier: MIT
|
|
8
|
+
********************************************************************************/
|
|
9
|
+
|
|
10
|
+
import { type Stopwatch, SystemClock } from '@hydranium/protocol';
|
|
11
|
+
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
|
12
|
+
import { AbstractChannel } from '@theia/core/lib/common/message-rpc/channel';
|
|
13
|
+
import { type WriteBuffer } from '@theia/core/lib/common/message-rpc/message-buffer';
|
|
14
|
+
import { Uint8ArrayReadBuffer, Uint8ArrayWriteBuffer } from '@theia/core/lib/common/message-rpc/uint8-array-message-buffer';
|
|
15
|
+
import { BackendApplicationConfigProvider } from '@theia/core/lib/node/backend-application-config-provider';
|
|
16
|
+
import { SocketWriteBuffer } from '@theia/core/lib/common/messaging/socket-write-buffer';
|
|
17
|
+
import { WebsocketFrontendConnectionService } from '@theia/core/lib/node/messaging/websocket-frontend-connection-service';
|
|
18
|
+
import { inject, injectable, optional, type interfaces } from '@theia/core/shared/inversify';
|
|
19
|
+
import { Clock } from '../common/clock';
|
|
20
|
+
import { type ConnectionResilienceOptions } from '../common/connection-resilience-options';
|
|
21
|
+
import {
|
|
22
|
+
CONNECTION_LOG_PREFIX as PREFIX,
|
|
23
|
+
createFramedSocketWriteBuffer,
|
|
24
|
+
FramedSocketWriteBuffer,
|
|
25
|
+
supportsConnectionResilience,
|
|
26
|
+
warnConnectionResilienceUnavailable
|
|
27
|
+
} from '../common/framed-socket-write-buffer';
|
|
28
|
+
import { ACKNOWLEDGEMENT_EVENT, InboundMessageSequence } from '../common/inbound-message-sequence';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Socket Theia hands the disconnect handler, read off the base signature rather
|
|
32
|
+
* than imported, which spares a direct `socket.io` dependency carried purely
|
|
33
|
+
* for a parameter type.
|
|
34
|
+
*/
|
|
35
|
+
export type FrontendSocket = Parameters<WebsocketFrontendConnectionService['handleSocketDisconnect']>[0];
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Channel Theia hands the disconnect handler, read off the base signature so
|
|
39
|
+
* this package's emitted declarations name only
|
|
40
|
+
* `WebsocketFrontendConnectionService`.
|
|
41
|
+
*
|
|
42
|
+
* `ReconnectableSocketChannel` is not exported by every Theia release in the
|
|
43
|
+
* supported range, so importing it would make those declarations unresolvable
|
|
44
|
+
* for an adopter on one of them — a compile error for a feature they may not
|
|
45
|
+
* even be using.
|
|
46
|
+
*/
|
|
47
|
+
export type FrontendChannel = Parameters<WebsocketFrontendConnectionService['handleSocketDisconnect']>[1];
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The server end of one frontend's session, carried across the sockets the
|
|
51
|
+
* frontend reconnects on.
|
|
52
|
+
*
|
|
53
|
+
* Theia's own channel sends straight into any socket that reports itself
|
|
54
|
+
* connected. A socket whose far end died unnoticed still does, so whatever is
|
|
55
|
+
* sent until the server notices is lost. This one numbers and keeps every
|
|
56
|
+
* message through {@link FramedSocketWriteBuffer}, resends what is still
|
|
57
|
+
* unacknowledged when the frontend reconnects, and drops what it has received
|
|
58
|
+
* twice. Otherwise it behaves as Theia's.
|
|
59
|
+
*/
|
|
60
|
+
export class AcknowledgedSocketChannel extends AbstractChannel {
|
|
61
|
+
protected socket: FrontendSocket | undefined;
|
|
62
|
+
protected socketDisposables = new DisposableCollection();
|
|
63
|
+
protected readonly inbound = new InboundMessageSequence(sequence => this.socket?.emit(ACKNOWLEDGEMENT_EVENT, sequence));
|
|
64
|
+
|
|
65
|
+
constructor(protected readonly socketBuffer: FramedSocketWriteBuffer) {
|
|
66
|
+
super();
|
|
67
|
+
this.toDispose.push(this.inbound);
|
|
68
|
+
this.toDispose.push(Disposable.create(() => this.socketDisposables.dispose()));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Flushes in the same step that attaches the listeners, so nothing new can overtake the resend. */
|
|
72
|
+
connect(socket: FrontendSocket): void {
|
|
73
|
+
this.socketDisposables.dispose();
|
|
74
|
+
this.socketDisposables = new DisposableCollection();
|
|
75
|
+
this.socket = socket;
|
|
76
|
+
const errorHandler = (error: unknown): void => this.onErrorEmitter.fire(error);
|
|
77
|
+
const dataListener = (data: ArrayBuffer | Uint8Array, sequence?: unknown): void => {
|
|
78
|
+
if (typeof sequence === 'number') {
|
|
79
|
+
this.socketBuffer.markPeerDeduplicates();
|
|
80
|
+
}
|
|
81
|
+
if (!this.inbound.accept(sequence, data.byteLength)) {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const buffer = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
85
|
+
this.onMessageEmitter.fire(() => new Uint8ArrayReadBuffer(buffer));
|
|
86
|
+
};
|
|
87
|
+
const acknowledgementListener = (sequence: unknown): void => {
|
|
88
|
+
if (typeof sequence === 'number') {
|
|
89
|
+
this.socketBuffer.acknowledge(sequence);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
socket.on('error', errorHandler);
|
|
93
|
+
socket.on('message', dataListener);
|
|
94
|
+
socket.on(ACKNOWLEDGEMENT_EVENT, acknowledgementListener);
|
|
95
|
+
this.socketDisposables.push(
|
|
96
|
+
Disposable.create(() => {
|
|
97
|
+
socket.off('error', errorHandler);
|
|
98
|
+
socket.off('message', dataListener);
|
|
99
|
+
socket.off(ACKNOWLEDGEMENT_EVENT, acknowledgementListener);
|
|
100
|
+
})
|
|
101
|
+
);
|
|
102
|
+
this.socketBuffer.flush(socket);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
disconnect(): void {
|
|
106
|
+
this.socketDisposables.dispose();
|
|
107
|
+
this.socket = undefined;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
drainBuffer(): void {
|
|
111
|
+
this.socketBuffer.drain();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
getWriteBuffer(): WriteBuffer {
|
|
115
|
+
const writeBuffer = new Uint8ArrayWriteBuffer();
|
|
116
|
+
writeBuffer.onCommit(data => this.socketBuffer.sendOrQueue(this.socket?.connected ? this.socket : undefined, data));
|
|
117
|
+
return writeBuffer;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Ignores a disconnect from a socket that no longer belongs to the frontend.
|
|
123
|
+
*
|
|
124
|
+
* A frontend that loses its network reconnects on a new socket within seconds;
|
|
125
|
+
* the server only notices the old one is gone when its next heartbeat write
|
|
126
|
+
* fails, which is a whole ping interval later. For that stretch both sockets are
|
|
127
|
+
* registered against the same session, and Theia's disconnect handler tears the
|
|
128
|
+
* session off its socket without checking which one just died. The late
|
|
129
|
+
* notification from the abandoned socket therefore cuts the healthy one loose.
|
|
130
|
+
* The frontend sees a connected socket and never retries, so the session is dead
|
|
131
|
+
* until the page is reloaded.
|
|
132
|
+
*
|
|
133
|
+
* Changed here: only the socket the session is currently using may act on a
|
|
134
|
+
* disconnect. The handler is rewritten rather than wrapped because the problem
|
|
135
|
+
* sits inside the listener Theia installs; the rest of the body is Theia's.
|
|
136
|
+
*
|
|
137
|
+
* Re-diff against Theia when the supported range moves: `override` catches a changed signature,
|
|
138
|
+
* not a changed body, so this copy can go stale in silence.
|
|
139
|
+
*/
|
|
140
|
+
@injectable()
|
|
141
|
+
export class SessionBoundFrontendConnectionService extends WebsocketFrontendConnectionService {
|
|
142
|
+
/** Times the gaps the log reports: the container's {@link Clock}, or a `SystemClock`. */
|
|
143
|
+
@inject(Clock) @optional() protected readonly clock: Clock = new SystemClock();
|
|
144
|
+
/** Socket each frontend's channel is currently bound to, with how long it has been. */
|
|
145
|
+
protected readonly bindings = new Map<string, { socketId: string; sinceBound: Stopwatch }>();
|
|
146
|
+
/** Running since a frontend's live socket went away, so the reconnect gap can be reported. */
|
|
147
|
+
protected readonly sinceOffline = new Map<string, Stopwatch>();
|
|
148
|
+
|
|
149
|
+
override handleSocketDisconnect(socket: FrontendSocket, channel: FrontendChannel, frontEndId: string): void {
|
|
150
|
+
const previous = this.bindings.get(frontEndId);
|
|
151
|
+
this.bindings.set(frontEndId, { socketId: socket.id, sinceBound: this.clock.stopwatch() });
|
|
152
|
+
|
|
153
|
+
const sinceOffline = this.sinceOffline.get(frontEndId);
|
|
154
|
+
this.sinceOffline.delete(frontEndId);
|
|
155
|
+
const replacing = previous ? `, replacing socket ${previous.socketId}` : '';
|
|
156
|
+
const gap = sinceOffline === undefined ? '' : `, after ${Math.round(sinceOffline.elapsedMs)} ms offline`;
|
|
157
|
+
console.info(`${PREFIX} frontend ${frontEndId} channel bound to socket ${socket.id}${replacing}${gap}`);
|
|
158
|
+
|
|
159
|
+
socket.on('disconnect', reason => {
|
|
160
|
+
const bound = this.bindings.get(frontEndId);
|
|
161
|
+
if (bound?.socketId !== socket.id) {
|
|
162
|
+
// Either a superseded socket being reaped late, or one outliving `closeConnection`, which
|
|
163
|
+
// deletes the binding. Neither owns the channel, so neither may disconnect it, arm a close
|
|
164
|
+
// timeout, or close a connection that is no longer in `connectionsByFrontend`.
|
|
165
|
+
const owner = bound
|
|
166
|
+
? `socket ${bound.socketId} owns it (bound ${Math.round(bound.sinceBound.elapsedMs)} ms ago)`
|
|
167
|
+
: 'the connection is already closed';
|
|
168
|
+
console.info(`${PREFIX} ignoring disconnect of stale socket ${socket.id} (frontend ${frontEndId}, ${reason}); ${owner}`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// From here on: Theia's own handler body, unchanged apart from naming the socket.
|
|
173
|
+
this.sinceOffline.set(frontEndId, this.clock.stopwatch());
|
|
174
|
+
console.info(`${PREFIX} socket ${socket.id} (frontend ${frontEndId}) disconnected: ${reason}`);
|
|
175
|
+
channel.disconnect();
|
|
176
|
+
const timeout = this.connectionTimeout();
|
|
177
|
+
const isMarkedForClose = this.channelsMarkedForClose.delete(frontEndId);
|
|
178
|
+
if (timeout === 0 || isMarkedForClose) {
|
|
179
|
+
this.closeConnection(frontEndId, reason);
|
|
180
|
+
} else if (timeout > 0) {
|
|
181
|
+
console.info(`${PREFIX} close timeout for frontend ${frontEndId} set to ${timeout} ms`);
|
|
182
|
+
this.closeTimeouts.set(
|
|
183
|
+
frontEndId,
|
|
184
|
+
setTimeout(() => this.closeConnection(frontEndId, reason), timeout)
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
// timeout < 0: never close the back end.
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Theia's body, building an {@link AcknowledgedSocketChannel} in place of its own channel.
|
|
193
|
+
*
|
|
194
|
+
* Handed over through a cast, because Theia types the slot as its own channel class. The cast
|
|
195
|
+
* also hides from the compiler what Theia calls on the channel, so a release that calls a member
|
|
196
|
+
* this one lacks fails at runtime: re-diff with the disconnect handler.
|
|
197
|
+
*/
|
|
198
|
+
protected override createConnection(socket: FrontendSocket, frontEndId: string): FrontendChannel {
|
|
199
|
+
const channel = new AcknowledgedSocketChannel(this.createWriteBuffer()) as unknown as FrontendChannel;
|
|
200
|
+
channel.connect(socket);
|
|
201
|
+
this.connectionsByFrontend.set(frontEndId, channel);
|
|
202
|
+
return channel;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* One buffer per session, from the container Theia resolves its own channel's buffer from.
|
|
207
|
+
* Reached through a structural view because Theia 1.70 does not declare `container`.
|
|
208
|
+
*/
|
|
209
|
+
protected createWriteBuffer(): FramedSocketWriteBuffer {
|
|
210
|
+
const container = (this as unknown as { readonly container: interfaces.Container }).container;
|
|
211
|
+
const buffer = container.get<SocketWriteBuffer>(SocketWriteBuffer);
|
|
212
|
+
if (!(buffer instanceof FramedSocketWriteBuffer)) {
|
|
213
|
+
throw new Error('SessionBoundFrontendConnectionService requires FramedSocketWriteBuffer to be bound');
|
|
214
|
+
}
|
|
215
|
+
return buffer;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
protected override closeConnection(frontEndId: string, reason: string): void {
|
|
219
|
+
console.info(`${PREFIX} closing frontend ${frontEndId}: ${reason}`);
|
|
220
|
+
this.bindings.delete(frontEndId);
|
|
221
|
+
this.sinceOffline.delete(frontEndId);
|
|
222
|
+
super.closeConnection(frontEndId, reason);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Mirrors Theia's private `frontendConnectionTimeout`, including `Number('')` resolving to 0.
|
|
226
|
+
* Private there, so the copy is forced; re-diff it with the handler above. */
|
|
227
|
+
protected connectionTimeout(): number {
|
|
228
|
+
const envValue = Number(process.env['FRONTEND_CONNECTION_TIMEOUT']);
|
|
229
|
+
if (!isNaN(envValue)) {
|
|
230
|
+
return envValue;
|
|
231
|
+
}
|
|
232
|
+
return BackendApplicationConfigProvider.get().frontendConnectionTimeout;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Replaces the server pieces that decide how a session survives a reconnect.
|
|
238
|
+
*
|
|
239
|
+
* `FrontendConnectionService` is bound `toService(WebsocketFrontendConnectionService)`,
|
|
240
|
+
* so rebinding the concrete class is enough. The buffer stays transient (one per
|
|
241
|
+
* connection), matching Theia's `bind(SocketWriteBuffer).toSelf()`; the frontend
|
|
242
|
+
* counterpart is bound by `bindConnectionResilience` in a `frontendPreload`
|
|
243
|
+
* module, which is the only point early enough on that side.
|
|
244
|
+
*
|
|
245
|
+
* Does nothing but warn on a Theia too old to expose the buffer binding, so the
|
|
246
|
+
* package keeps one supported range rather than splitting its floor for this
|
|
247
|
+
* feature. Returns whether the hardening was installed, for an adopter that
|
|
248
|
+
* wants to branch on it.
|
|
249
|
+
*/
|
|
250
|
+
export function bindConnectionResilience(
|
|
251
|
+
bind: interfaces.Bind,
|
|
252
|
+
isBound: interfaces.IsBound,
|
|
253
|
+
rebind: interfaces.Rebind,
|
|
254
|
+
options: ConnectionResilienceOptions = {}
|
|
255
|
+
): boolean {
|
|
256
|
+
if (!supportsConnectionResilience(isBound)) {
|
|
257
|
+
warnConnectionResilienceUnavailable('backend');
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
bind(SessionBoundFrontendConnectionService).toSelf().inSingletonScope();
|
|
261
|
+
rebind(WebsocketFrontendConnectionService).toService(SessionBoundFrontendConnectionService);
|
|
262
|
+
rebind(SocketWriteBuffer).toDynamicValue(() => createFramedSocketWriteBuffer(options));
|
|
263
|
+
return true;
|
|
264
|
+
}
|