@hydranium/client-theia 1.0.0-next.7 → 1.0.0-next.71

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.
Files changed (51) hide show
  1. package/README.md +2 -2
  2. package/lib/browser/connection-diagnostics-contribution.d.ts +69 -0
  3. package/lib/browser/connection-diagnostics-contribution.d.ts.map +1 -0
  4. package/lib/browser/connection-diagnostics-contribution.js +153 -0
  5. package/lib/browser/connection-diagnostics-contribution.js.map +1 -0
  6. package/lib/browser/index.d.ts +2 -0
  7. package/lib/browser/index.d.ts.map +1 -1
  8. package/lib/browser/index.js +2 -0
  9. package/lib/browser/index.js.map +1 -1
  10. package/lib/browser/log-level-preference.d.ts.map +1 -1
  11. package/lib/browser/log-level-preference.js +11 -0
  12. package/lib/browser/log-level-preference.js.map +1 -1
  13. package/lib/browser/memory-diagnostics-contribution.d.ts +40 -4
  14. package/lib/browser/memory-diagnostics-contribution.d.ts.map +1 -1
  15. package/lib/browser/memory-diagnostics-contribution.js +161 -31
  16. package/lib/browser/memory-diagnostics-contribution.js.map +1 -1
  17. package/lib/browser/session-aware-connection-source.d.ts +98 -0
  18. package/lib/browser/session-aware-connection-source.d.ts.map +1 -0
  19. package/lib/browser/session-aware-connection-source.js +167 -0
  20. package/lib/browser/session-aware-connection-source.js.map +1 -0
  21. package/lib/common/connection-resilience-options.d.ts +24 -0
  22. package/lib/common/connection-resilience-options.d.ts.map +1 -0
  23. package/lib/common/connection-resilience-options.js +11 -0
  24. package/lib/common/connection-resilience-options.js.map +1 -0
  25. package/lib/common/framed-socket-write-buffer.d.ts +121 -0
  26. package/lib/common/framed-socket-write-buffer.d.ts.map +1 -0
  27. package/lib/common/framed-socket-write-buffer.js +190 -0
  28. package/lib/common/framed-socket-write-buffer.js.map +1 -0
  29. package/lib/common/index.d.ts +11 -0
  30. package/lib/common/index.d.ts.map +1 -0
  31. package/lib/common/index.js +30 -0
  32. package/lib/common/index.js.map +1 -0
  33. package/lib/node/index.d.ts +1 -0
  34. package/lib/node/index.d.ts.map +1 -1
  35. package/lib/node/index.js +1 -0
  36. package/lib/node/index.js.map +1 -1
  37. package/lib/node/session-bound-frontend-connection-service.d.ts +77 -0
  38. package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
  39. package/lib/node/session-bound-frontend-connection-service.js +128 -0
  40. package/lib/node/session-bound-frontend-connection-service.js.map +1 -0
  41. package/package.json +16 -7
  42. package/src/browser/connection-diagnostics-contribution.ts +142 -0
  43. package/src/browser/index.ts +2 -0
  44. package/src/browser/log-level-preference.ts +11 -0
  45. package/src/browser/memory-diagnostics-contribution.ts +268 -45
  46. package/src/browser/session-aware-connection-source.ts +179 -0
  47. package/src/common/connection-resilience-options.ts +24 -0
  48. package/src/common/framed-socket-write-buffer.ts +227 -0
  49. package/src/common/index.ts +14 -0
  50. package/src/node/index.ts +1 -0
  51. package/src/node/session-bound-frontend-connection-service.ts +155 -0
@@ -0,0 +1,179 @@
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 { WebSocketConnectionSource } from '@theia/core/lib/browser/messaging/ws-connection-source';
11
+ import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
12
+ import { type Event } from '@theia/core/lib/common/event';
13
+ import { type AbstractChannel, ForwardingChannel } from '@theia/core/lib/common/message-rpc/channel';
14
+ import { Uint8ArrayReadBuffer, Uint8ArrayWriteBuffer } from '@theia/core/lib/common/message-rpc/uint8-array-message-buffer';
15
+ import { ConnectionManagementMessages } from '@theia/core/lib/common/messaging/connection-management';
16
+ import { injectable, type interfaces } from '@theia/core/shared/inversify';
17
+ import { SocketWriteBuffer } from '@theia/core/lib/common/messaging/socket-write-buffer';
18
+ import { type ConnectionResilienceOptions } from '../common/connection-resilience-options';
19
+ import {
20
+ type ConnectionBufferOverflow,
21
+ createFramedSocketWriteBuffer,
22
+ FramedSocketWriteBuffer,
23
+ supportsConnectionResilience,
24
+ warnConnectionResilienceUnavailable
25
+ } from '../common/framed-socket-write-buffer';
26
+
27
+ /**
28
+ * Sends a message only once the server has confirmed the session, and only
29
+ * behind anything already queued.
30
+ *
31
+ * Theia sends straight away when `socket.connected` is true and buffers
32
+ * otherwise. The gap is that reconnecting sets that flag immediately, while the
33
+ * session is only confirmed a round trip later. A message produced in that
34
+ * window either jumps ahead of older messages still waiting in the buffer, or,
35
+ * if nothing was waiting, goes out on a socket whose channel the server has not
36
+ * attached yet and is discarded by a peer with no listener for it.
37
+ *
38
+ * Losing one or reordering them is equally unrecoverable for anything that
39
+ * applies messages by position. Theia's plugin host keeps a line-indexed copy of
40
+ * every open document, so a single late or missing edit leaves that copy wrong
41
+ * for good, and the next edit past its end fails.
42
+ *
43
+ * The server side needs no equivalent: it adopts its socket and flushes in one
44
+ * synchronous step, so it has no window of this kind.
45
+ */
46
+ @injectable()
47
+ export class SessionAwareConnectionSource extends WebSocketConnectionSource {
48
+ /**
49
+ * Whether the server has confirmed, on the socket in use right now, that it
50
+ * still holds this frontend's session. A connected socket is not enough:
51
+ * until the handshake is answered the server has not attached its channel to
52
+ * this socket, and a message sent meanwhile reaches a peer with no listener
53
+ * for it and is discarded without a trace.
54
+ */
55
+ protected sessionResumed = false;
56
+ protected sessionListenersAttached = false;
57
+
58
+ /**
59
+ * Every connect starts a socket the server has not confirmed yet, including
60
+ * the reconnects socket.io performs on its own. Resetting here rather than on
61
+ * disconnect also covers a connect that follows no clean disconnect event.
62
+ */
63
+ protected override handleSocketConnected(): void {
64
+ this.trackSessionState();
65
+ this.sessionResumed = false;
66
+ super.handleSocketConnected();
67
+ }
68
+
69
+ /**
70
+ * Watches the connection handshake for its outcome.
71
+ *
72
+ * Attached once, to the socket socket.io reuses across reconnects, and before
73
+ * the base class adds its own per-negotiation listeners — so this has already
74
+ * recorded the outcome by the time the base class reacts to it by flushing.
75
+ */
76
+ protected trackSessionState(): void {
77
+ if (this.sessionListenersAttached) {
78
+ return;
79
+ }
80
+ this.sessionListenersAttached = true;
81
+ this.socket.on(ConnectionManagementMessages.INITIAL_CONNECT, () => {
82
+ this.sessionResumed = true;
83
+ });
84
+ this.socket.on(ConnectionManagementMessages.RECONNECT, (hasConnection: boolean) => {
85
+ this.sessionResumed = hasConnection;
86
+ });
87
+ }
88
+
89
+ /** Whether a message may go out now, as opposed to waiting in the buffer. */
90
+ protected get canSend(): boolean {
91
+ return this.socket.connected && this.sessionResumed;
92
+ }
93
+
94
+ /**
95
+ * Copied from Theia apart from the `onCommit` body, because the base builds that callback inline
96
+ * and exposes no narrower seam. Re-diff when the supported range moves.
97
+ */
98
+ protected override createChannel(): AbstractChannel {
99
+ const toDispose = new DisposableCollection();
100
+ const messageHandler = (data: ArrayBuffer | Uint8Array): void => {
101
+ this.onIncomingMessageActivityEmitter.fire();
102
+ if (this.currentChannel) {
103
+ // socket.io hands binary over as ArrayBuffer in the browser.
104
+ const buffer = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
105
+ this.currentChannel.onMessageEmitter.fire(() => new Uint8ArrayReadBuffer(buffer));
106
+ }
107
+ };
108
+ this.socket.on('message', messageHandler);
109
+ toDispose.push(Disposable.create(() => this.socket.off('message', messageHandler)));
110
+
111
+ return new ForwardingChannel(
112
+ 'any',
113
+ () => toDispose.dispose(),
114
+ () => {
115
+ const result = new Uint8ArrayWriteBuffer();
116
+ // Says only whether the session can carry a message; the buffer decides whether it may
117
+ // go ahead of anything already waiting.
118
+ result.onCommit(buffer => this.framedBuffer.sendOrQueue(this.canSend ? this.socket : undefined, buffer));
119
+ return result;
120
+ }
121
+ );
122
+ }
123
+
124
+ /** Fires when the buffer runs out of room, so an adopter can say so rather than just stopping. */
125
+ get onBufferOverflow(): Event<ConnectionBufferOverflow> {
126
+ return this.framedBuffer.onOverflow;
127
+ }
128
+
129
+ /**
130
+ * The write buffer Theia injected into the base class.
131
+ *
132
+ * Reached through a structural view rather than as `this.writeBuffer`,
133
+ * because that member is `private` in Theia 1.70 and only became `protected`
134
+ * in 1.71 — and this package compiles against the whole range. The view
135
+ * asserts nothing the versions disagree about: the field is there in both,
136
+ * holding whatever `SocketWriteBuffer` is bound, and the check below is what
137
+ * establishes it is ours.
138
+ */
139
+ protected get framedBuffer(): FramedSocketWriteBuffer {
140
+ const buffer = (this as unknown as { readonly writeBuffer: SocketWriteBuffer }).writeBuffer;
141
+ if (!(buffer instanceof FramedSocketWriteBuffer)) {
142
+ throw new Error('SessionAwareConnectionSource requires FramedSocketWriteBuffer to be bound');
143
+ }
144
+ return buffer;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Replaces the frontend pieces that decide how outgoing messages survive a
150
+ * reconnect. Every one of them rebinds something Theia's
151
+ * `messagingFrontendModule` already bound, so this belongs in a module loaded
152
+ * into the same container.
153
+ *
154
+ * It must be a `frontendPreload` module rather than a normal frontend module:
155
+ * Theia's preloader resolves `WebSocketConnectionSource` (and with it the write
156
+ * buffer) while loading i18n and OS settings, which happens before any frontend
157
+ * module is loaded. A rebind there would come too late — the instances would
158
+ * already exist. All `frontendPreload` modules, by contrast, are loaded before
159
+ * the preloader constructs anything.
160
+ *
161
+ * Does nothing but warn on a Theia too old to expose the buffer binding, so the
162
+ * package keeps one supported range rather than splitting its floor for this
163
+ * feature. Returns whether the hardening was installed, for an adopter that
164
+ * wants to branch on it.
165
+ */
166
+ export function bindConnectionResilience(
167
+ isBound: interfaces.IsBound,
168
+ rebind: interfaces.Rebind,
169
+ options: ConnectionResilienceOptions = {}
170
+ ): boolean {
171
+ if (!supportsConnectionResilience(isBound)) {
172
+ warnConnectionResilienceUnavailable('frontend');
173
+ return false;
174
+ }
175
+ // Scopes are kept as Theia declares them: one buffer per connection source, one shared socket owner.
176
+ rebind(SocketWriteBuffer).toDynamicValue(() => createFramedSocketWriteBuffer(options.bufferBytes));
177
+ rebind(WebSocketConnectionSource).to(SessionAwareConnectionSource).inSingletonScope();
178
+ return true;
179
+ }
@@ -0,0 +1,24 @@
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
+ /**
11
+ * Options for the `bindConnectionResilience` helper each tier exports.
12
+ *
13
+ * Lives in `common` rather than beside either helper so the server entry can
14
+ * name the type without importing the browser module, and the other way round.
15
+ */
16
+ export interface ConnectionResilienceOptions {
17
+ /**
18
+ * Size of the buffer holding messages while the socket is down, in bytes.
19
+ * Defaults to Theia's own limit. It decides how long an outage can last
20
+ * before changes start being rejected, so a deployment on a poor network
21
+ * trades memory for tolerance here.
22
+ */
23
+ readonly bufferBytes?: number;
24
+ }
@@ -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,14 @@
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 connection primitives, shared by the browser connection
11
+ // source and the server connection service. Kept out of both tier barrels
12
+ // because each side binds the same buffer for its own half of the socket.
13
+ export * from './framed-socket-write-buffer';
14
+ export * from './connection-resilience-options';
package/src/node/index.ts CHANGED
@@ -8,3 +8,4 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  export * from './abstract-socket-forwarding-connection-handler';
11
+ export * from './session-bound-frontend-connection-service';
@@ -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
+ }