@hydranium/client-theia 1.0.0-next.13 → 1.0.0-next.135
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -8
- 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 +9 -4
- package/lib/browser/channel-logger.js.map +1 -1
- package/lib/browser/connection-diagnostics-contribution.d.ts +69 -0
- package/lib/browser/connection-diagnostics-contribution.d.ts.map +1 -0
- package/lib/browser/connection-diagnostics-contribution.js +153 -0
- package/lib/browser/connection-diagnostics-contribution.js.map +1 -0
- package/lib/browser/editor-disk-sync.d.ts +133 -0
- package/lib/browser/editor-disk-sync.d.ts.map +1 -0
- package/lib/browser/editor-disk-sync.js +232 -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 +4 -0
- package/lib/browser/index.d.ts.map +1 -1
- package/lib/browser/index.js +4 -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 +40 -4
- package/lib/browser/memory-diagnostics-contribution.d.ts.map +1 -1
- package/lib/browser/memory-diagnostics-contribution.js +161 -31
- package/lib/browser/memory-diagnostics-contribution.js.map +1 -1
- package/lib/browser/session-aware-connection-source.d.ts +98 -0
- package/lib/browser/session-aware-connection-source.d.ts.map +1 -0
- package/lib/browser/session-aware-connection-source.js +167 -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 +24 -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 +121 -0
- package/lib/common/framed-socket-write-buffer.d.ts.map +1 -0
- package/lib/common/framed-socket-write-buffer.js +190 -0
- package/lib/common/framed-socket-write-buffer.js.map +1 -0
- package/lib/common/index.d.ts +12 -0
- package/lib/common/index.d.ts.map +1 -0
- package/lib/common/index.js +31 -0
- package/lib/common/index.js.map +1 -0
- package/lib/node/abstract-socket-forwarding-connection-handler.d.ts +8 -7
- package/lib/node/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
- package/lib/node/abstract-socket-forwarding-connection-handler.js +28 -7
- 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 +77 -0
- package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
- package/lib/node/session-bound-frontend-connection-service.js +128 -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 +93 -0
- package/lib/node/socket-channel-forwarder.js.map +1 -0
- package/package.json +24 -9
- package/src/browser/channel-logger.ts +9 -4
- package/src/browser/connection-diagnostics-contribution.ts +142 -0
- package/src/browser/editor-disk-sync.ts +236 -0
- package/src/browser/hydranium-file-service.ts +56 -0
- package/src/browser/index.ts +4 -0
- package/src/browser/log-level-preference.ts +11 -0
- package/src/browser/memory-diagnostics-contribution.ts +268 -45
- package/src/browser/session-aware-connection-source.ts +179 -0
- package/src/common/clock.ts +20 -0
- package/src/common/connection-resilience-options.ts +24 -0
- package/src/common/framed-socket-write-buffer.ts +227 -0
- package/src/common/index.ts +15 -0
- package/src/node/abstract-socket-forwarding-connection-handler.ts +19 -9
- package/src/node/index.ts +2 -0
- package/src/node/session-bound-frontend-connection-service.ts +155 -0
- package/src/node/socket-channel-forwarder.ts +99 -0
|
@@ -0,0 +1,227 @@
|
|
|
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 { Emitter, type Event } from '@theia/core/lib/common/event';
|
|
11
|
+
import { SocketWriteBuffer } from '@theia/core/lib/common/messaging/socket-write-buffer';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Prefix on every connection log line, deliberately shared by the browser and the
|
|
15
|
+
* server so one pattern greps a console and a pod log at once.
|
|
16
|
+
*/
|
|
17
|
+
export const CONNECTION_LOG_PREFIX = '[connection]';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The part of a socket this buffer uses. Narrower than the socket type Theia
|
|
21
|
+
* declares, which keeps the dependency honest and lets the class be tested
|
|
22
|
+
* without a connection.
|
|
23
|
+
*/
|
|
24
|
+
export interface MessageSink {
|
|
25
|
+
send(data: Uint8Array): void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Reported when the buffer runs out of room. The message that did not fit is
|
|
30
|
+
* rejected, and so is every further one for as long as the buffer stays full.
|
|
31
|
+
* Reconnecting drains it and sending resumes, but whatever was rejected
|
|
32
|
+
* meanwhile is gone, so the two sides no longer agree about the session.
|
|
33
|
+
*/
|
|
34
|
+
export interface ConnectionBufferOverflow {
|
|
35
|
+
/** Messages held when the limit was reached. */
|
|
36
|
+
readonly messages: number;
|
|
37
|
+
/** Bytes held when the limit was reached. */
|
|
38
|
+
readonly bytes: number;
|
|
39
|
+
/** The limit in force, so a reader can tell what to raise it to. */
|
|
40
|
+
readonly maxBytes: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Holds messages while the peer is away and re-sends them when it returns.
|
|
45
|
+
*
|
|
46
|
+
* Theia copies them into one growing byte array and flushes that with a single
|
|
47
|
+
* `send`. A websocket delivers whole messages rather than a byte stream, so
|
|
48
|
+
* Theia's encoding adds no length prefix and every reader assumes one delivery
|
|
49
|
+
* is one message. The concatenated flush breaks that assumption: the reader
|
|
50
|
+
* decodes the first message and throws away the bytes behind it.
|
|
51
|
+
*
|
|
52
|
+
* Changed here: one entry per message, sent one at a time, so each arrives as
|
|
53
|
+
* its own delivery. The buffer also decides whether a message may go out
|
|
54
|
+
* directly — see {@link sendOrQueue} — because a caller that decides for itself
|
|
55
|
+
* is how messages end up overtaking a backlog.
|
|
56
|
+
*
|
|
57
|
+
* Unchanged from Theia: exceeding the limit rejects the message rather than
|
|
58
|
+
* dropping something silently. The limit is settable, since the right value
|
|
59
|
+
* depends on how long an outage has to survive.
|
|
60
|
+
*
|
|
61
|
+
* Logging goes to `console` rather than through a `Logger`. On the browser side
|
|
62
|
+
* Theia's preloader builds this before any Output channel exists, so there is
|
|
63
|
+
* nothing else to write to; the {@link CONNECTION_LOG_PREFIX} keeps the lines
|
|
64
|
+
* findable on both sides.
|
|
65
|
+
*/
|
|
66
|
+
export class FramedSocketWriteBuffer extends SocketWriteBuffer {
|
|
67
|
+
/** Theia's fixed limit, kept as the default. */
|
|
68
|
+
static readonly DEFAULT_MAX_BYTES = 100 * 1024;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Settable so a deployment can trade memory for longer outages.
|
|
72
|
+
*
|
|
73
|
+
* Consulted directly rather than through the base class's `maxBufferSize`,
|
|
74
|
+
* which does not exist before Theia 1.71 — an `override` of it would not
|
|
75
|
+
* compile against the oldest release this package supports. Nothing is lost:
|
|
76
|
+
* `buffer`, `flush` and `drain` are all replaced here, so the base's own
|
|
77
|
+
* limit is never reached.
|
|
78
|
+
*/
|
|
79
|
+
maxBytes = FramedSocketWriteBuffer.DEFAULT_MAX_BYTES;
|
|
80
|
+
|
|
81
|
+
protected pending: Uint8Array[] = [];
|
|
82
|
+
protected pendingBytes = 0;
|
|
83
|
+
protected overflowReported = false;
|
|
84
|
+
protected readonly onOverflowEmitter = new Emitter<ConnectionBufferOverflow>();
|
|
85
|
+
|
|
86
|
+
/** Fires once per outage when the limit is reached. */
|
|
87
|
+
get onOverflow(): Event<ConnectionBufferOverflow> {
|
|
88
|
+
return this.onOverflowEmitter.event;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Sends `data` now only if nothing is waiting, and queues it otherwise.
|
|
93
|
+
*
|
|
94
|
+
* Callers say whether the peer is ready for a message; the buffer decides
|
|
95
|
+
* whether it may go ahead of one already waiting. Splitting it this way is
|
|
96
|
+
* the point: a caller that answers both questions from one flag is how a
|
|
97
|
+
* fresh message ends up overtaking a backlog.
|
|
98
|
+
*/
|
|
99
|
+
sendOrQueue(socket: MessageSink | undefined, data: Uint8Array): void {
|
|
100
|
+
if (socket && !this.hasBacklog) {
|
|
101
|
+
socket.send(data);
|
|
102
|
+
} else {
|
|
103
|
+
this.buffer(data);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
override buffer(data: Uint8Array): void {
|
|
108
|
+
if (this.pendingBytes + data.byteLength > this.maxBytes) {
|
|
109
|
+
this.reportOverflow();
|
|
110
|
+
throw new Error(`Max disconnected buffer size exceeded by adding ${data.byteLength} bytes`);
|
|
111
|
+
}
|
|
112
|
+
// Copied for the same reason the base class copies: the caller owns `data`.
|
|
113
|
+
this.pending.push(data.slice());
|
|
114
|
+
this.pendingBytes += data.byteLength;
|
|
115
|
+
if (this.pending.length === 1) {
|
|
116
|
+
console.info(`${CONNECTION_LOG_PREFIX} buffering messages, the peer is disconnected`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
override flush(socket: MessageSink): void {
|
|
121
|
+
if (this.pending.length === 0) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const count = this.pending.length;
|
|
125
|
+
const bytes = this.pendingBytes;
|
|
126
|
+
// Walked with an index and dropped in one slice, not shifted per message: a shift re-indexes
|
|
127
|
+
// the whole array, so the drain would cost the square of a backlog `bufferBytes` invites an
|
|
128
|
+
// adopter to enlarge. Leaving the queue in place is what keeps `hasBacklog` true until the
|
|
129
|
+
// last message is out, and re-reading the length is what drains one appended by a nested send.
|
|
130
|
+
let index = 0;
|
|
131
|
+
try {
|
|
132
|
+
while (index < this.pending.length) {
|
|
133
|
+
const message = this.pending[index];
|
|
134
|
+
socket.send(message);
|
|
135
|
+
index++;
|
|
136
|
+
this.pendingBytes -= message.byteLength;
|
|
137
|
+
}
|
|
138
|
+
} catch (error: unknown) {
|
|
139
|
+
// Said here because nothing retries: Theia flushes once, from a reconnect handler that has
|
|
140
|
+
// deregistered by now, so the stall would otherwise surface much later as an overflow —
|
|
141
|
+
// which names the wrong cause, the socket being up rather than absent.
|
|
142
|
+
console.error(
|
|
143
|
+
`${CONNECTION_LOG_PREFIX} send failed ${index} message(s) into a ${count}-message backlog; ` +
|
|
144
|
+
`${this.pending.length - index} still queued and nothing will retry them`,
|
|
145
|
+
error
|
|
146
|
+
);
|
|
147
|
+
throw error;
|
|
148
|
+
} finally {
|
|
149
|
+
this.pending = this.pending.slice(index);
|
|
150
|
+
}
|
|
151
|
+
this.overflowReported = false;
|
|
152
|
+
console.info(`${CONNECTION_LOG_PREFIX} sent ${count} buffered message(s), ${bytes} bytes`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
override drain(): void {
|
|
156
|
+
if (this.pending.length > 0) {
|
|
157
|
+
console.warn(`${CONNECTION_LOG_PREFIX} discarded ${this.pending.length} buffered message(s), ${this.pendingBytes} bytes`);
|
|
158
|
+
}
|
|
159
|
+
this.reset();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Whether messages are still waiting to go out. */
|
|
163
|
+
get hasBacklog(): boolean {
|
|
164
|
+
return this.pending.length > 0;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
protected reportOverflow(): void {
|
|
168
|
+
if (this.overflowReported) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
this.overflowReported = true;
|
|
172
|
+
const overflow: ConnectionBufferOverflow = { messages: this.pending.length, bytes: this.pendingBytes, maxBytes: this.maxBytes };
|
|
173
|
+
console.error(
|
|
174
|
+
`${CONNECTION_LOG_PREFIX} buffer full at ${overflow.maxBytes} bytes after ${overflow.messages} message(s); ` +
|
|
175
|
+
'this message is rejected, and so is every further one until the peer returns'
|
|
176
|
+
);
|
|
177
|
+
this.onOverflowEmitter.fire(overflow);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
protected reset(): void {
|
|
181
|
+
this.pending = [];
|
|
182
|
+
this.pendingBytes = 0;
|
|
183
|
+
this.overflowReported = false;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Named in the warning a skipped install emits, so the reader is told what to upgrade to. */
|
|
188
|
+
export const REQUIRED_THEIA_HINT = '@theia/core 1.71 or newer';
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Whether this Theia exposes the seam the reconnect hardening replaces.
|
|
192
|
+
*
|
|
193
|
+
* Theia only began binding {@link SocketWriteBuffer} in 1.71; before that each
|
|
194
|
+
* connection built one privately, so there is no binding to rebind and no way
|
|
195
|
+
* in. Every other API involved has been there throughout, which makes this one
|
|
196
|
+
* probe the whole compatibility question — and it is a binding check rather
|
|
197
|
+
* than a version parse, so it answers about the container actually in front of
|
|
198
|
+
* us instead of a number that may have been overridden or vendored.
|
|
199
|
+
*
|
|
200
|
+
* Callers that get `false` must leave Theia's own wiring alone: rebinding half
|
|
201
|
+
* of it would be worse than not rebinding at all.
|
|
202
|
+
*/
|
|
203
|
+
export function supportsConnectionResilience(isBound: (identifier: typeof SocketWriteBuffer) => boolean): boolean {
|
|
204
|
+
return isBound(SocketWriteBuffer);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The warning a skipped install emits. Says what is lost rather than only what
|
|
209
|
+
* is missing: the failures this guards against are silent, so an adopter who
|
|
210
|
+
* never sees this line has no other way to learn the guard is absent.
|
|
211
|
+
*/
|
|
212
|
+
export function warnConnectionResilienceUnavailable(tier: 'frontend' | 'backend'): void {
|
|
213
|
+
console.warn(
|
|
214
|
+
`${CONNECTION_LOG_PREFIX} ${tier} reconnect hardening NOT installed: this Theia does not expose an injectable ` +
|
|
215
|
+
`socket write buffer (needs ${REQUIRED_THEIA_HINT}). Theia's own behaviour is left in place, which can lose or ` +
|
|
216
|
+
'reorder messages when a socket drops and reconnects.'
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Builds a buffer with the given limit, or Theia's default when none is configured. */
|
|
221
|
+
export function createFramedSocketWriteBuffer(maxBytes?: number): FramedSocketWriteBuffer {
|
|
222
|
+
const buffer = new FramedSocketWriteBuffer();
|
|
223
|
+
if (typeof maxBytes === 'number' && maxBytes > 0) {
|
|
224
|
+
buffer.maxBytes = maxBytes;
|
|
225
|
+
}
|
|
226
|
+
return buffer;
|
|
227
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
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 './connection-resilience-options';
|
|
15
|
+
export * from './clock';
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* SPDX-License-Identifier: MIT
|
|
8
8
|
********************************************************************************/
|
|
9
9
|
|
|
10
|
+
import { SystemClock } from '@hydranium/protocol';
|
|
10
11
|
import {
|
|
11
12
|
type Channel,
|
|
12
13
|
CommandService,
|
|
@@ -18,8 +19,10 @@ import {
|
|
|
18
19
|
} from '@theia/core';
|
|
19
20
|
import { ForwardingChannel } 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
|
|
|
@@ -175,7 +178,12 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
|
|
|
175
178
|
if (channel instanceof ForwardingChannel) {
|
|
176
179
|
socket.on('error', error => channel.onErrorEmitter.fire(error));
|
|
177
180
|
}
|
|
178
|
-
|
|
181
|
+
// `127.0.0.1`, not the `localhost` Node dials when no host is given, and it
|
|
182
|
+
// has to match the head: the socket launchers bind `127.0.0.1` by default,
|
|
183
|
+
// so on a dual-stack machine where `localhost` resolves to `::1` first the
|
|
184
|
+
// dial fails as ECONNREFUSED with nothing in the message naming the address
|
|
185
|
+
// family as the cause.
|
|
186
|
+
socket.connect({ port, host: '127.0.0.1' });
|
|
179
187
|
setTimeout(() => connected.reject('Timeout reached.'), this.connectTimeoutMs);
|
|
180
188
|
return connected.promise;
|
|
181
189
|
}
|
|
@@ -185,7 +193,9 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
|
|
|
185
193
|
* relay both ways. Called once, after the socket is created and the
|
|
186
194
|
* pre-forward buffer is about to be replayed.
|
|
187
195
|
*/
|
|
188
|
-
protected
|
|
196
|
+
protected forwardToSocketConnection(clientChannel: Channel, socket: net.Socket): Disposable {
|
|
197
|
+
return new SocketChannelForwarder(clientChannel, socket, this.clock);
|
|
198
|
+
}
|
|
189
199
|
|
|
190
200
|
/**
|
|
191
201
|
* Re-fire pre-forward buffered `MessageProvider`s on the channel's internal
|
package/src/node/index.ts
CHANGED
|
@@ -0,0 +1,155 @@
|
|
|
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 { BackendApplicationConfigProvider } from '@theia/core/lib/node/backend-application-config-provider';
|
|
11
|
+
import { SocketWriteBuffer } from '@theia/core/lib/common/messaging/socket-write-buffer';
|
|
12
|
+
import { WebsocketFrontendConnectionService } from '@theia/core/lib/node/messaging/websocket-frontend-connection-service';
|
|
13
|
+
import { injectable, type interfaces } from '@theia/core/shared/inversify';
|
|
14
|
+
import { type ConnectionResilienceOptions } from '../common/connection-resilience-options';
|
|
15
|
+
import {
|
|
16
|
+
CONNECTION_LOG_PREFIX as PREFIX,
|
|
17
|
+
createFramedSocketWriteBuffer,
|
|
18
|
+
supportsConnectionResilience,
|
|
19
|
+
warnConnectionResilienceUnavailable
|
|
20
|
+
} from '../common/framed-socket-write-buffer';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Socket Theia hands the disconnect handler, read off the base signature rather
|
|
24
|
+
* than imported, which spares a direct `socket.io` dependency carried purely
|
|
25
|
+
* for a parameter type.
|
|
26
|
+
*/
|
|
27
|
+
export type FrontendSocket = Parameters<WebsocketFrontendConnectionService['handleSocketDisconnect']>[0];
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Channel Theia hands the disconnect handler, read off the base signature so
|
|
31
|
+
* this package's emitted declarations name only
|
|
32
|
+
* `WebsocketFrontendConnectionService`.
|
|
33
|
+
*
|
|
34
|
+
* `ReconnectableSocketChannel` is not exported by every Theia release in the
|
|
35
|
+
* supported range, so importing it would make those declarations unresolvable
|
|
36
|
+
* for an adopter on one of them — a compile error for a feature they may not
|
|
37
|
+
* even be using.
|
|
38
|
+
*/
|
|
39
|
+
export type FrontendChannel = Parameters<WebsocketFrontendConnectionService['handleSocketDisconnect']>[1];
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Ignores a disconnect from a socket that no longer belongs to the frontend.
|
|
43
|
+
*
|
|
44
|
+
* A frontend that loses its network reconnects on a new socket within seconds;
|
|
45
|
+
* the server only notices the old one is gone when its next heartbeat write
|
|
46
|
+
* fails, which is a whole ping interval later. For that stretch both sockets are
|
|
47
|
+
* registered against the same session, and Theia's disconnect handler tears the
|
|
48
|
+
* session off its socket without checking which one just died. The late
|
|
49
|
+
* notification from the abandoned socket therefore cuts the healthy one loose.
|
|
50
|
+
* The frontend sees a connected socket and never retries, so the session is dead
|
|
51
|
+
* until the page is reloaded.
|
|
52
|
+
*
|
|
53
|
+
* Changed here: only the socket the session is currently using may act on a
|
|
54
|
+
* disconnect. The handler is rewritten rather than wrapped because the problem
|
|
55
|
+
* sits inside the listener Theia installs; the rest of the body is Theia's.
|
|
56
|
+
*
|
|
57
|
+
* Re-diff against Theia when the supported range moves: `override` catches a changed signature,
|
|
58
|
+
* not a changed body, so this copy can go stale in silence.
|
|
59
|
+
*/
|
|
60
|
+
@injectable()
|
|
61
|
+
export class SessionBoundFrontendConnectionService extends WebsocketFrontendConnectionService {
|
|
62
|
+
/** Socket each frontend's channel is currently bound to, with the time it was bound. */
|
|
63
|
+
protected readonly bindings = new Map<string, { socketId: string; boundAt: number }>();
|
|
64
|
+
/** When a frontend's live socket went away, so the reconnect gap can be reported. */
|
|
65
|
+
protected readonly offlineSince = new Map<string, number>();
|
|
66
|
+
|
|
67
|
+
override handleSocketDisconnect(socket: FrontendSocket, channel: FrontendChannel, frontEndId: string): void {
|
|
68
|
+
const previous = this.bindings.get(frontEndId);
|
|
69
|
+
this.bindings.set(frontEndId, { socketId: socket.id, boundAt: Date.now() });
|
|
70
|
+
|
|
71
|
+
const wentOfflineAt = this.offlineSince.get(frontEndId);
|
|
72
|
+
this.offlineSince.delete(frontEndId);
|
|
73
|
+
const replacing = previous ? `, replacing socket ${previous.socketId}` : '';
|
|
74
|
+
const gap = wentOfflineAt === undefined ? '' : `, after ${Date.now() - wentOfflineAt} ms offline`;
|
|
75
|
+
console.info(`${PREFIX} frontend ${frontEndId} channel bound to socket ${socket.id}${replacing}${gap}`);
|
|
76
|
+
|
|
77
|
+
socket.on('disconnect', reason => {
|
|
78
|
+
const bound = this.bindings.get(frontEndId);
|
|
79
|
+
if (bound?.socketId !== socket.id) {
|
|
80
|
+
// Either a superseded socket being reaped late, or one outliving `closeConnection`, which
|
|
81
|
+
// deletes the binding. Neither owns the channel, so neither may disconnect it, arm a close
|
|
82
|
+
// timeout, or close a connection that is no longer in `connectionsByFrontend`.
|
|
83
|
+
const owner = bound
|
|
84
|
+
? `socket ${bound.socketId} owns it (bound ${Date.now() - bound.boundAt} ms ago)`
|
|
85
|
+
: 'the connection is already closed';
|
|
86
|
+
console.info(`${PREFIX} ignoring disconnect of stale socket ${socket.id} (frontend ${frontEndId}, ${reason}); ${owner}`);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// From here on: Theia's own handler body, unchanged apart from naming the socket.
|
|
91
|
+
this.offlineSince.set(frontEndId, Date.now());
|
|
92
|
+
console.info(`${PREFIX} socket ${socket.id} (frontend ${frontEndId}) disconnected: ${reason}`);
|
|
93
|
+
channel.disconnect();
|
|
94
|
+
const timeout = this.connectionTimeout();
|
|
95
|
+
const isMarkedForClose = this.channelsMarkedForClose.delete(frontEndId);
|
|
96
|
+
if (timeout === 0 || isMarkedForClose) {
|
|
97
|
+
this.closeConnection(frontEndId, reason);
|
|
98
|
+
} else if (timeout > 0) {
|
|
99
|
+
console.info(`${PREFIX} close timeout for frontend ${frontEndId} set to ${timeout} ms`);
|
|
100
|
+
this.closeTimeouts.set(
|
|
101
|
+
frontEndId,
|
|
102
|
+
setTimeout(() => this.closeConnection(frontEndId, reason), timeout)
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
// timeout < 0: never close the back end.
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
protected override closeConnection(frontEndId: string, reason: string): void {
|
|
110
|
+
console.info(`${PREFIX} closing frontend ${frontEndId}: ${reason}`);
|
|
111
|
+
this.bindings.delete(frontEndId);
|
|
112
|
+
this.offlineSince.delete(frontEndId);
|
|
113
|
+
super.closeConnection(frontEndId, reason);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Mirrors Theia's private `frontendConnectionTimeout`, including `Number('')` resolving to 0.
|
|
117
|
+
* Private there, so the copy is forced; re-diff it with the handler above. */
|
|
118
|
+
protected connectionTimeout(): number {
|
|
119
|
+
const envValue = Number(process.env['FRONTEND_CONNECTION_TIMEOUT']);
|
|
120
|
+
if (!isNaN(envValue)) {
|
|
121
|
+
return envValue;
|
|
122
|
+
}
|
|
123
|
+
return BackendApplicationConfigProvider.get().frontendConnectionTimeout;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Replaces the server pieces that decide how a session survives a reconnect.
|
|
129
|
+
*
|
|
130
|
+
* `FrontendConnectionService` is bound `toService(WebsocketFrontendConnectionService)`,
|
|
131
|
+
* so rebinding the concrete class is enough. The buffer stays transient (one per
|
|
132
|
+
* connection), matching Theia's `bind(SocketWriteBuffer).toSelf()`; the frontend
|
|
133
|
+
* counterpart is bound by `bindConnectionResilience` in a `frontendPreload`
|
|
134
|
+
* module, which is the only point early enough on that side.
|
|
135
|
+
*
|
|
136
|
+
* Does nothing but warn on a Theia too old to expose the buffer binding, so the
|
|
137
|
+
* package keeps one supported range rather than splitting its floor for this
|
|
138
|
+
* feature. Returns whether the hardening was installed, for an adopter that
|
|
139
|
+
* wants to branch on it.
|
|
140
|
+
*/
|
|
141
|
+
export function bindConnectionResilience(
|
|
142
|
+
bind: interfaces.Bind,
|
|
143
|
+
isBound: interfaces.IsBound,
|
|
144
|
+
rebind: interfaces.Rebind,
|
|
145
|
+
options: ConnectionResilienceOptions = {}
|
|
146
|
+
): boolean {
|
|
147
|
+
if (!supportsConnectionResilience(isBound)) {
|
|
148
|
+
warnConnectionResilienceUnavailable('backend');
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
bind(SessionBoundFrontendConnectionService).toSelf().inSingletonScope();
|
|
152
|
+
rebind(WebsocketFrontendConnectionService).toService(SessionBoundFrontendConnectionService);
|
|
153
|
+
rebind(SocketWriteBuffer).toDynamicValue(() => createFramedSocketWriteBuffer(options.bufferBytes));
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
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 Clock, SystemClock } from '@hydranium/protocol';
|
|
11
|
+
import { type Channel, Disposable, DisposableCollection, type MessageProvider } from '@theia/core';
|
|
12
|
+
import type * as net from 'node:net';
|
|
13
|
+
import {
|
|
14
|
+
createMessageConnection,
|
|
15
|
+
type Message,
|
|
16
|
+
type MessageConnection,
|
|
17
|
+
SocketMessageReader,
|
|
18
|
+
SocketMessageWriter
|
|
19
|
+
} from 'vscode-jsonrpc/node';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Relays JSON-RPC messages between a Theia browser-frontend {@link Channel} and
|
|
23
|
+
* a server's TCP socket — the backend half of a head's transport. The server
|
|
24
|
+
* speaks vscode-jsonrpc (Content-Length framed) on the socket; the frontend
|
|
25
|
+
* speaks the same protocol over the channel. This forwarder decodes each side
|
|
26
|
+
* and re-emits on the other.
|
|
27
|
+
*
|
|
28
|
+
* Behaves as `@eclipse-glsp/theia-integration`'s `SocketConnectionForwarder`
|
|
29
|
+
* does, and both heads use it, except that when the channel closes, the writes
|
|
30
|
+
* still queued go out before the socket ends. A page going away sends its last
|
|
31
|
+
* messages and closes its channel in the same tick, and the writer takes
|
|
32
|
+
* several turns per message, so destroying the socket on the close loses them.
|
|
33
|
+
*/
|
|
34
|
+
export class SocketChannelForwarder implements Disposable {
|
|
35
|
+
protected readonly toDispose = new DisposableCollection();
|
|
36
|
+
/** The last write to the socket; the writer runs its writes one at a time, so this settles last. */
|
|
37
|
+
protected lastWrite: Promise<void> = Promise.resolve();
|
|
38
|
+
/**
|
|
39
|
+
* How long {@link endSocket} waits for the queued writes before it destroys
|
|
40
|
+
* the socket anyway. Without a bound, a server that stops reading holds the
|
|
41
|
+
* socket open for good, and with it the server's end of the connection.
|
|
42
|
+
*/
|
|
43
|
+
protected readonly flushTimeoutMs: number = 10_000;
|
|
44
|
+
|
|
45
|
+
constructor(
|
|
46
|
+
protected readonly channel: Channel,
|
|
47
|
+
protected readonly socket: net.Socket,
|
|
48
|
+
/** Times {@link flushTimeoutMs}. */
|
|
49
|
+
protected readonly clock: Clock = new SystemClock()
|
|
50
|
+
) {
|
|
51
|
+
const reader = new SocketMessageReader(socket);
|
|
52
|
+
const writer = new SocketMessageWriter(socket);
|
|
53
|
+
const connection = createMessageConnection(reader, writer);
|
|
54
|
+
// Nothing here destroys the socket directly. `SocketMessageWriter.dispose()`
|
|
55
|
+
// destroys it itself, which covers both `dispose` and `endSocket`; and
|
|
56
|
+
// `connection.onClose` fires only from the reader's or writer's own close,
|
|
57
|
+
// which for a socket means the socket has already gone — so a destroy
|
|
58
|
+
// handler there is downstream of the effect it would be trying to cause.
|
|
59
|
+
this.toDispose.pushAll([
|
|
60
|
+
reader.listen(message => this.writeToChannel(message)),
|
|
61
|
+
channel.onMessage(provider => {
|
|
62
|
+
// A failed write means the socket is gone, which its own close reports.
|
|
63
|
+
this.lastWrite = writer.write(this.decodeChannelMessage(provider)).catch(() => undefined);
|
|
64
|
+
}),
|
|
65
|
+
channel.onClose(() => void this.endSocket(connection)),
|
|
66
|
+
connection.onClose(() => channel.close()),
|
|
67
|
+
Disposable.create(() => {
|
|
68
|
+
channel.close();
|
|
69
|
+
connection.dispose();
|
|
70
|
+
})
|
|
71
|
+
]);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Dispose `connection`, which destroys the socket, once the writes queued
|
|
76
|
+
* before the channel closed are out, or {@link flushTimeoutMs} has passed. A
|
|
77
|
+
* write has settled once the socket handed its bytes to the OS, and
|
|
78
|
+
* destroying the socket then loses nothing.
|
|
79
|
+
*/
|
|
80
|
+
protected async endSocket(connection: MessageConnection): Promise<void> {
|
|
81
|
+
await this.clock.raceTimer(this.lastWrite, this.flushTimeoutMs);
|
|
82
|
+
connection.dispose();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
protected decodeChannelMessage(provider: MessageProvider): Message {
|
|
86
|
+
const buffer = provider().readBytes();
|
|
87
|
+
return JSON.parse(new TextDecoder().decode(buffer)) as Message;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
protected writeToChannel(message: Message): void {
|
|
91
|
+
const writeBuffer = this.channel.getWriteBuffer();
|
|
92
|
+
writeBuffer.writeBytes(new TextEncoder().encode(JSON.stringify(message)));
|
|
93
|
+
writeBuffer.commit();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
dispose(): void {
|
|
97
|
+
this.toDispose.dispose();
|
|
98
|
+
}
|
|
99
|
+
}
|