@hydranium/client-theia 1.0.0-next.23 → 1.0.0-next.232
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 +54 -16
- 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 +10 -7
- 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/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 +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 +101 -0
- package/lib/browser/session-aware-connection-source.d.ts.map +1 -0
- package/lib/browser/session-aware-connection-source.js +184 -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 +12 -8
- package/lib/node/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
- package/lib/node/abstract-socket-forwarding-connection-handler.js +70 -13
- 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 +118 -0
- package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
- package/lib/node/session-bound-frontend-connection-service.js +224 -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 +31 -32
- package/src/browser/channel-logger.ts +10 -7
- package/src/browser/connection-diagnostics-contribution.ts +142 -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 +268 -45
- package/src/browser/session-aware-connection-source.ts +196 -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 +61 -15
- package/src/node/index.ts +2 -0
- package/src/node/session-bound-frontend-connection-service.ts +260 -0
- package/src/node/socket-channel-forwarder.ts +101 -0
|
@@ -0,0 +1,260 @@
|
|
|
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 { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
|
|
11
|
+
import { AbstractChannel } from '@theia/core/lib/common/message-rpc/channel';
|
|
12
|
+
import { type WriteBuffer } from '@theia/core/lib/common/message-rpc/message-buffer';
|
|
13
|
+
import { Uint8ArrayReadBuffer, Uint8ArrayWriteBuffer } from '@theia/core/lib/common/message-rpc/uint8-array-message-buffer';
|
|
14
|
+
import { BackendApplicationConfigProvider } from '@theia/core/lib/node/backend-application-config-provider';
|
|
15
|
+
import { SocketWriteBuffer } from '@theia/core/lib/common/messaging/socket-write-buffer';
|
|
16
|
+
import { WebsocketFrontendConnectionService } from '@theia/core/lib/node/messaging/websocket-frontend-connection-service';
|
|
17
|
+
import { injectable, type interfaces } from '@theia/core/shared/inversify';
|
|
18
|
+
import { type ConnectionResilienceOptions } from '../common/connection-resilience-options';
|
|
19
|
+
import {
|
|
20
|
+
CONNECTION_LOG_PREFIX as PREFIX,
|
|
21
|
+
createFramedSocketWriteBuffer,
|
|
22
|
+
FramedSocketWriteBuffer,
|
|
23
|
+
supportsConnectionResilience,
|
|
24
|
+
warnConnectionResilienceUnavailable
|
|
25
|
+
} from '../common/framed-socket-write-buffer';
|
|
26
|
+
import { ACKNOWLEDGEMENT_EVENT, InboundMessageSequence } from '../common/inbound-message-sequence';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Socket Theia hands the disconnect handler, read off the base signature rather
|
|
30
|
+
* than imported, which spares a direct `socket.io` dependency carried purely
|
|
31
|
+
* for a parameter type.
|
|
32
|
+
*/
|
|
33
|
+
export type FrontendSocket = Parameters<WebsocketFrontendConnectionService['handleSocketDisconnect']>[0];
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Channel Theia hands the disconnect handler, read off the base signature so
|
|
37
|
+
* this package's emitted declarations name only
|
|
38
|
+
* `WebsocketFrontendConnectionService`.
|
|
39
|
+
*
|
|
40
|
+
* `ReconnectableSocketChannel` is not exported by every Theia release in the
|
|
41
|
+
* supported range, so importing it would make those declarations unresolvable
|
|
42
|
+
* for an adopter on one of them — a compile error for a feature they may not
|
|
43
|
+
* even be using.
|
|
44
|
+
*/
|
|
45
|
+
export type FrontendChannel = Parameters<WebsocketFrontendConnectionService['handleSocketDisconnect']>[1];
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The server end of one frontend's session, carried across the sockets the
|
|
49
|
+
* frontend reconnects on.
|
|
50
|
+
*
|
|
51
|
+
* Theia's own channel sends straight into any socket that reports itself
|
|
52
|
+
* connected. A socket whose far end died unnoticed still does, so whatever is
|
|
53
|
+
* sent until the server notices is lost. This one numbers and keeps every
|
|
54
|
+
* message through {@link FramedSocketWriteBuffer}, resends what is still
|
|
55
|
+
* unacknowledged when the frontend reconnects, and drops what it has received
|
|
56
|
+
* twice. Otherwise it behaves as Theia's.
|
|
57
|
+
*/
|
|
58
|
+
export class AcknowledgedSocketChannel extends AbstractChannel {
|
|
59
|
+
protected socket: FrontendSocket | undefined;
|
|
60
|
+
protected socketDisposables = new DisposableCollection();
|
|
61
|
+
protected readonly inbound = new InboundMessageSequence(sequence => this.socket?.emit(ACKNOWLEDGEMENT_EVENT, sequence));
|
|
62
|
+
|
|
63
|
+
constructor(protected readonly socketBuffer: FramedSocketWriteBuffer) {
|
|
64
|
+
super();
|
|
65
|
+
this.toDispose.push(this.inbound);
|
|
66
|
+
this.toDispose.push(Disposable.create(() => this.socketDisposables.dispose()));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Flushes in the same step that attaches the listeners, so nothing new can overtake the resend. */
|
|
70
|
+
connect(socket: FrontendSocket): void {
|
|
71
|
+
this.socketDisposables.dispose();
|
|
72
|
+
this.socketDisposables = new DisposableCollection();
|
|
73
|
+
this.socket = socket;
|
|
74
|
+
const errorHandler = (error: unknown): void => this.onErrorEmitter.fire(error);
|
|
75
|
+
const dataListener = (data: ArrayBuffer | Uint8Array, sequence?: unknown): void => {
|
|
76
|
+
if (typeof sequence === 'number') {
|
|
77
|
+
this.socketBuffer.markPeerDeduplicates();
|
|
78
|
+
}
|
|
79
|
+
if (!this.inbound.accept(sequence, data.byteLength)) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const buffer = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
83
|
+
this.onMessageEmitter.fire(() => new Uint8ArrayReadBuffer(buffer));
|
|
84
|
+
};
|
|
85
|
+
const acknowledgementListener = (sequence: unknown): void => {
|
|
86
|
+
if (typeof sequence === 'number') {
|
|
87
|
+
this.socketBuffer.acknowledge(sequence);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
socket.on('error', errorHandler);
|
|
91
|
+
socket.on('message', dataListener);
|
|
92
|
+
socket.on(ACKNOWLEDGEMENT_EVENT, acknowledgementListener);
|
|
93
|
+
this.socketDisposables.push(
|
|
94
|
+
Disposable.create(() => {
|
|
95
|
+
socket.off('error', errorHandler);
|
|
96
|
+
socket.off('message', dataListener);
|
|
97
|
+
socket.off(ACKNOWLEDGEMENT_EVENT, acknowledgementListener);
|
|
98
|
+
})
|
|
99
|
+
);
|
|
100
|
+
this.socketBuffer.flush(socket);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
disconnect(): void {
|
|
104
|
+
this.socketDisposables.dispose();
|
|
105
|
+
this.socket = undefined;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
drainBuffer(): void {
|
|
109
|
+
this.socketBuffer.drain();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
getWriteBuffer(): WriteBuffer {
|
|
113
|
+
const writeBuffer = new Uint8ArrayWriteBuffer();
|
|
114
|
+
writeBuffer.onCommit(data => this.socketBuffer.sendOrQueue(this.socket?.connected ? this.socket : undefined, data));
|
|
115
|
+
return writeBuffer;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Ignores a disconnect from a socket that no longer belongs to the frontend.
|
|
121
|
+
*
|
|
122
|
+
* A frontend that loses its network reconnects on a new socket within seconds;
|
|
123
|
+
* the server only notices the old one is gone when its next heartbeat write
|
|
124
|
+
* fails, which is a whole ping interval later. For that stretch both sockets are
|
|
125
|
+
* registered against the same session, and Theia's disconnect handler tears the
|
|
126
|
+
* session off its socket without checking which one just died. The late
|
|
127
|
+
* notification from the abandoned socket therefore cuts the healthy one loose.
|
|
128
|
+
* The frontend sees a connected socket and never retries, so the session is dead
|
|
129
|
+
* until the page is reloaded.
|
|
130
|
+
*
|
|
131
|
+
* Changed here: only the socket the session is currently using may act on a
|
|
132
|
+
* disconnect. The handler is rewritten rather than wrapped because the problem
|
|
133
|
+
* sits inside the listener Theia installs; the rest of the body is Theia's.
|
|
134
|
+
*
|
|
135
|
+
* Re-diff against Theia when the supported range moves: `override` catches a changed signature,
|
|
136
|
+
* not a changed body, so this copy can go stale in silence.
|
|
137
|
+
*/
|
|
138
|
+
@injectable()
|
|
139
|
+
export class SessionBoundFrontendConnectionService extends WebsocketFrontendConnectionService {
|
|
140
|
+
/** Socket each frontend's channel is currently bound to, with the time it was bound. */
|
|
141
|
+
protected readonly bindings = new Map<string, { socketId: string; boundAt: number }>();
|
|
142
|
+
/** When a frontend's live socket went away, so the reconnect gap can be reported. */
|
|
143
|
+
protected readonly offlineSince = new Map<string, number>();
|
|
144
|
+
|
|
145
|
+
override handleSocketDisconnect(socket: FrontendSocket, channel: FrontendChannel, frontEndId: string): void {
|
|
146
|
+
const previous = this.bindings.get(frontEndId);
|
|
147
|
+
this.bindings.set(frontEndId, { socketId: socket.id, boundAt: Date.now() });
|
|
148
|
+
|
|
149
|
+
const wentOfflineAt = this.offlineSince.get(frontEndId);
|
|
150
|
+
this.offlineSince.delete(frontEndId);
|
|
151
|
+
const replacing = previous ? `, replacing socket ${previous.socketId}` : '';
|
|
152
|
+
const gap = wentOfflineAt === undefined ? '' : `, after ${Date.now() - wentOfflineAt} ms offline`;
|
|
153
|
+
console.info(`${PREFIX} frontend ${frontEndId} channel bound to socket ${socket.id}${replacing}${gap}`);
|
|
154
|
+
|
|
155
|
+
socket.on('disconnect', reason => {
|
|
156
|
+
const bound = this.bindings.get(frontEndId);
|
|
157
|
+
if (bound?.socketId !== socket.id) {
|
|
158
|
+
// Either a superseded socket being reaped late, or one outliving `closeConnection`, which
|
|
159
|
+
// deletes the binding. Neither owns the channel, so neither may disconnect it, arm a close
|
|
160
|
+
// timeout, or close a connection that is no longer in `connectionsByFrontend`.
|
|
161
|
+
const owner = bound
|
|
162
|
+
? `socket ${bound.socketId} owns it (bound ${Date.now() - bound.boundAt} ms ago)`
|
|
163
|
+
: 'the connection is already closed';
|
|
164
|
+
console.info(`${PREFIX} ignoring disconnect of stale socket ${socket.id} (frontend ${frontEndId}, ${reason}); ${owner}`);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// From here on: Theia's own handler body, unchanged apart from naming the socket.
|
|
169
|
+
this.offlineSince.set(frontEndId, Date.now());
|
|
170
|
+
console.info(`${PREFIX} socket ${socket.id} (frontend ${frontEndId}) disconnected: ${reason}`);
|
|
171
|
+
channel.disconnect();
|
|
172
|
+
const timeout = this.connectionTimeout();
|
|
173
|
+
const isMarkedForClose = this.channelsMarkedForClose.delete(frontEndId);
|
|
174
|
+
if (timeout === 0 || isMarkedForClose) {
|
|
175
|
+
this.closeConnection(frontEndId, reason);
|
|
176
|
+
} else if (timeout > 0) {
|
|
177
|
+
console.info(`${PREFIX} close timeout for frontend ${frontEndId} set to ${timeout} ms`);
|
|
178
|
+
this.closeTimeouts.set(
|
|
179
|
+
frontEndId,
|
|
180
|
+
setTimeout(() => this.closeConnection(frontEndId, reason), timeout)
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
// timeout < 0: never close the back end.
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Theia's body, building an {@link AcknowledgedSocketChannel} in place of its own channel.
|
|
189
|
+
*
|
|
190
|
+
* Handed over through a cast, because Theia types the slot as its own channel class. The cast
|
|
191
|
+
* also hides from the compiler what Theia calls on the channel, so a release that calls a member
|
|
192
|
+
* this one lacks fails at runtime: re-diff with the disconnect handler.
|
|
193
|
+
*/
|
|
194
|
+
protected override createConnection(socket: FrontendSocket, frontEndId: string): FrontendChannel {
|
|
195
|
+
const channel = new AcknowledgedSocketChannel(this.createWriteBuffer()) as unknown as FrontendChannel;
|
|
196
|
+
channel.connect(socket);
|
|
197
|
+
this.connectionsByFrontend.set(frontEndId, channel);
|
|
198
|
+
return channel;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* One buffer per session, from the container Theia resolves its own channel's buffer from.
|
|
203
|
+
* Reached through a structural view because Theia 1.70 does not declare `container`.
|
|
204
|
+
*/
|
|
205
|
+
protected createWriteBuffer(): FramedSocketWriteBuffer {
|
|
206
|
+
const container = (this as unknown as { readonly container: interfaces.Container }).container;
|
|
207
|
+
const buffer = container.get<SocketWriteBuffer>(SocketWriteBuffer);
|
|
208
|
+
if (!(buffer instanceof FramedSocketWriteBuffer)) {
|
|
209
|
+
throw new Error('SessionBoundFrontendConnectionService requires FramedSocketWriteBuffer to be bound');
|
|
210
|
+
}
|
|
211
|
+
return buffer;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
protected override closeConnection(frontEndId: string, reason: string): void {
|
|
215
|
+
console.info(`${PREFIX} closing frontend ${frontEndId}: ${reason}`);
|
|
216
|
+
this.bindings.delete(frontEndId);
|
|
217
|
+
this.offlineSince.delete(frontEndId);
|
|
218
|
+
super.closeConnection(frontEndId, reason);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Mirrors Theia's private `frontendConnectionTimeout`, including `Number('')` resolving to 0.
|
|
222
|
+
* Private there, so the copy is forced; re-diff it with the handler above. */
|
|
223
|
+
protected connectionTimeout(): number {
|
|
224
|
+
const envValue = Number(process.env['FRONTEND_CONNECTION_TIMEOUT']);
|
|
225
|
+
if (!isNaN(envValue)) {
|
|
226
|
+
return envValue;
|
|
227
|
+
}
|
|
228
|
+
return BackendApplicationConfigProvider.get().frontendConnectionTimeout;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Replaces the server pieces that decide how a session survives a reconnect.
|
|
234
|
+
*
|
|
235
|
+
* `FrontendConnectionService` is bound `toService(WebsocketFrontendConnectionService)`,
|
|
236
|
+
* so rebinding the concrete class is enough. The buffer stays transient (one per
|
|
237
|
+
* connection), matching Theia's `bind(SocketWriteBuffer).toSelf()`; the frontend
|
|
238
|
+
* counterpart is bound by `bindConnectionResilience` in a `frontendPreload`
|
|
239
|
+
* module, which is the only point early enough on that side.
|
|
240
|
+
*
|
|
241
|
+
* Does nothing but warn on a Theia too old to expose the buffer binding, so the
|
|
242
|
+
* package keeps one supported range rather than splitting its floor for this
|
|
243
|
+
* feature. Returns whether the hardening was installed, for an adopter that
|
|
244
|
+
* wants to branch on it.
|
|
245
|
+
*/
|
|
246
|
+
export function bindConnectionResilience(
|
|
247
|
+
bind: interfaces.Bind,
|
|
248
|
+
isBound: interfaces.IsBound,
|
|
249
|
+
rebind: interfaces.Rebind,
|
|
250
|
+
options: ConnectionResilienceOptions = {}
|
|
251
|
+
): boolean {
|
|
252
|
+
if (!supportsConnectionResilience(isBound)) {
|
|
253
|
+
warnConnectionResilienceUnavailable('backend');
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
bind(SessionBoundFrontendConnectionService).toSelf().inSingletonScope();
|
|
257
|
+
rebind(WebsocketFrontendConnectionService).toService(SessionBoundFrontendConnectionService);
|
|
258
|
+
rebind(SocketWriteBuffer).toDynamicValue(() => createFramedSocketWriteBuffer(options));
|
|
259
|
+
return true;
|
|
260
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
// Never listens, so it handles no message and has nothing to log.
|
|
54
|
+
// ast-grep-ignore: connection-without-logger
|
|
55
|
+
const connection = createMessageConnection(reader, writer);
|
|
56
|
+
// Nothing here destroys the socket directly. `SocketMessageWriter.dispose()`
|
|
57
|
+
// destroys it itself, which covers both `dispose` and `endSocket`; and
|
|
58
|
+
// `connection.onClose` fires only from the reader's or writer's own close,
|
|
59
|
+
// which for a socket means the socket has already gone — so a destroy
|
|
60
|
+
// handler there is downstream of the effect it would be trying to cause.
|
|
61
|
+
this.toDispose.pushAll([
|
|
62
|
+
reader.listen(message => this.writeToChannel(message)),
|
|
63
|
+
channel.onMessage(provider => {
|
|
64
|
+
// A failed write means the socket is gone, which its own close reports.
|
|
65
|
+
this.lastWrite = writer.write(this.decodeChannelMessage(provider)).catch(() => undefined);
|
|
66
|
+
}),
|
|
67
|
+
channel.onClose(() => void this.endSocket(connection)),
|
|
68
|
+
connection.onClose(() => channel.close()),
|
|
69
|
+
Disposable.create(() => {
|
|
70
|
+
channel.close();
|
|
71
|
+
connection.dispose();
|
|
72
|
+
})
|
|
73
|
+
]);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Dispose `connection`, which destroys the socket, once the writes queued
|
|
78
|
+
* before the channel closed are out, or {@link flushTimeoutMs} has passed. A
|
|
79
|
+
* write has settled once the socket handed its bytes to the OS, and
|
|
80
|
+
* destroying the socket then loses nothing.
|
|
81
|
+
*/
|
|
82
|
+
protected async endSocket(connection: MessageConnection): Promise<void> {
|
|
83
|
+
await this.clock.raceTimer(this.lastWrite, this.flushTimeoutMs);
|
|
84
|
+
connection.dispose();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
protected decodeChannelMessage(provider: MessageProvider): Message {
|
|
88
|
+
const buffer = provider().readBytes();
|
|
89
|
+
return JSON.parse(new TextDecoder().decode(buffer)) as Message;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
protected writeToChannel(message: Message): void {
|
|
93
|
+
const writeBuffer = this.channel.getWriteBuffer();
|
|
94
|
+
writeBuffer.writeBytes(new TextEncoder().encode(JSON.stringify(message)));
|
|
95
|
+
writeBuffer.commit();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
dispose(): void {
|
|
99
|
+
this.toDispose.dispose();
|
|
100
|
+
}
|
|
101
|
+
}
|