@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.
Files changed (94) hide show
  1. package/README.md +54 -16
  2. package/lib/browser/browser-capture.js.map +1 -1
  3. package/lib/browser/channel-logger.d.ts +4 -3
  4. package/lib/browser/channel-logger.d.ts.map +1 -1
  5. package/lib/browser/channel-logger.js +10 -7
  6. package/lib/browser/channel-logger.js.map +1 -1
  7. package/lib/browser/connection-diagnostics-contribution.d.ts +69 -0
  8. package/lib/browser/connection-diagnostics-contribution.d.ts.map +1 -0
  9. package/lib/browser/connection-diagnostics-contribution.js +153 -0
  10. package/lib/browser/connection-diagnostics-contribution.js.map +1 -0
  11. package/lib/browser/connection-reporter.d.ts +57 -0
  12. package/lib/browser/connection-reporter.d.ts.map +1 -0
  13. package/lib/browser/connection-reporter.js +104 -0
  14. package/lib/browser/connection-reporter.js.map +1 -0
  15. package/lib/browser/editor-disk-sync.d.ts +142 -0
  16. package/lib/browser/editor-disk-sync.d.ts.map +1 -0
  17. package/lib/browser/editor-disk-sync.js +250 -0
  18. package/lib/browser/editor-disk-sync.js.map +1 -0
  19. package/lib/browser/hydranium-file-service.d.ts +44 -0
  20. package/lib/browser/hydranium-file-service.d.ts.map +1 -0
  21. package/lib/browser/hydranium-file-service.js +61 -0
  22. package/lib/browser/hydranium-file-service.js.map +1 -0
  23. package/lib/browser/index.d.ts +5 -0
  24. package/lib/browser/index.d.ts.map +1 -1
  25. package/lib/browser/index.js +5 -0
  26. package/lib/browser/index.js.map +1 -1
  27. package/lib/browser/log-level-preference.d.ts.map +1 -1
  28. package/lib/browser/log-level-preference.js +11 -0
  29. package/lib/browser/log-level-preference.js.map +1 -1
  30. package/lib/browser/memory-diagnostics-contribution.d.ts +40 -4
  31. package/lib/browser/memory-diagnostics-contribution.d.ts.map +1 -1
  32. package/lib/browser/memory-diagnostics-contribution.js +161 -31
  33. package/lib/browser/memory-diagnostics-contribution.js.map +1 -1
  34. package/lib/browser/session-aware-connection-source.d.ts +101 -0
  35. package/lib/browser/session-aware-connection-source.d.ts.map +1 -0
  36. package/lib/browser/session-aware-connection-source.js +184 -0
  37. package/lib/browser/session-aware-connection-source.js.map +1 -0
  38. package/lib/common/clock.d.ts +19 -0
  39. package/lib/common/clock.d.ts.map +1 -0
  40. package/lib/common/clock.js +13 -0
  41. package/lib/common/clock.js.map +1 -0
  42. package/lib/common/connection-resilience-options.d.ts +30 -0
  43. package/lib/common/connection-resilience-options.d.ts.map +1 -0
  44. package/lib/common/connection-resilience-options.js +11 -0
  45. package/lib/common/connection-resilience-options.js.map +1 -0
  46. package/lib/common/framed-socket-write-buffer.d.ts +173 -0
  47. package/lib/common/framed-socket-write-buffer.d.ts.map +1 -0
  48. package/lib/common/framed-socket-write-buffer.js +293 -0
  49. package/lib/common/framed-socket-write-buffer.js.map +1 -0
  50. package/lib/common/inbound-message-sequence.d.ts +56 -0
  51. package/lib/common/inbound-message-sequence.d.ts.map +1 -0
  52. package/lib/common/inbound-message-sequence.js +98 -0
  53. package/lib/common/inbound-message-sequence.js.map +1 -0
  54. package/lib/common/index.d.ts +13 -0
  55. package/lib/common/index.d.ts.map +1 -0
  56. package/lib/common/index.js +32 -0
  57. package/lib/common/index.js.map +1 -0
  58. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts +12 -8
  59. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
  60. package/lib/node/abstract-socket-forwarding-connection-handler.js +70 -13
  61. package/lib/node/abstract-socket-forwarding-connection-handler.js.map +1 -1
  62. package/lib/node/index.d.ts +2 -0
  63. package/lib/node/index.d.ts.map +1 -1
  64. package/lib/node/index.js +2 -0
  65. package/lib/node/index.js.map +1 -1
  66. package/lib/node/session-bound-frontend-connection-service.d.ts +118 -0
  67. package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
  68. package/lib/node/session-bound-frontend-connection-service.js +224 -0
  69. package/lib/node/session-bound-frontend-connection-service.js.map +1 -0
  70. package/lib/node/socket-channel-forwarder.d.ts +54 -0
  71. package/lib/node/socket-channel-forwarder.d.ts.map +1 -0
  72. package/lib/node/socket-channel-forwarder.js +95 -0
  73. package/lib/node/socket-channel-forwarder.js.map +1 -0
  74. package/lib/testing/stub-inversify-context.js.map +1 -1
  75. package/lib/testing/stub-output-channel.js.map +1 -1
  76. package/package.json +31 -32
  77. package/src/browser/channel-logger.ts +10 -7
  78. package/src/browser/connection-diagnostics-contribution.ts +142 -0
  79. package/src/browser/connection-reporter.ts +121 -0
  80. package/src/browser/editor-disk-sync.ts +253 -0
  81. package/src/browser/hydranium-file-service.ts +56 -0
  82. package/src/browser/index.ts +5 -0
  83. package/src/browser/log-level-preference.ts +11 -0
  84. package/src/browser/memory-diagnostics-contribution.ts +268 -45
  85. package/src/browser/session-aware-connection-source.ts +196 -0
  86. package/src/common/clock.ts +20 -0
  87. package/src/common/connection-resilience-options.ts +30 -0
  88. package/src/common/framed-socket-write-buffer.ts +345 -0
  89. package/src/common/inbound-message-sequence.ts +102 -0
  90. package/src/common/index.ts +16 -0
  91. package/src/node/abstract-socket-forwarding-connection-handler.ts +61 -15
  92. package/src/node/index.ts +2 -0
  93. package/src/node/session-bound-frontend-connection-service.ts +260 -0
  94. package/src/node/socket-channel-forwarder.ts +101 -0
@@ -0,0 +1,345 @@
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
+ import { type ConnectionResilienceOptions } from './connection-resilience-options';
13
+
14
+ /**
15
+ * Prefix on every connection log line, deliberately shared by the browser and the
16
+ * server so one pattern greps a console and a pod log at once.
17
+ */
18
+ export const CONNECTION_LOG_PREFIX = '[connection]';
19
+
20
+ /**
21
+ * The part of a socket this buffer uses. Narrower than the socket type Theia
22
+ * declares, which keeps the dependency honest and lets the class be tested
23
+ * without a connection.
24
+ */
25
+ export interface MessageSink {
26
+ /** `sequence` travels as a second socket.io argument, which a reader that does not expect it ignores. */
27
+ send(data: Uint8Array, sequence: number): void;
28
+ }
29
+
30
+ /**
31
+ * Reported when the buffer runs out of room. The message that did not fit is
32
+ * rejected, and so is every further one for as long as the buffer stays full.
33
+ * Reconnecting drains it and sending resumes, but whatever was rejected
34
+ * meanwhile is gone, so the two sides no longer agree about the session.
35
+ */
36
+ export interface ConnectionBufferOverflow {
37
+ /** Messages held when the limit was reached. */
38
+ readonly messages: number;
39
+ /** Bytes held when the limit was reached. */
40
+ readonly bytes: number;
41
+ /** The limit in force, so a reader can tell what to raise it to. */
42
+ readonly maxBytes: number;
43
+ }
44
+
45
+ /**
46
+ * Holds messages while the peer is away and re-sends them when it returns.
47
+ *
48
+ * Theia copies them into one growing byte array and flushes that with a single
49
+ * `send`. A websocket delivers whole messages rather than a byte stream, so
50
+ * Theia's encoding adds no length prefix and every reader assumes one delivery
51
+ * is one message. The concatenated flush breaks that assumption: the reader
52
+ * decodes the first message and throws away the bytes behind it.
53
+ *
54
+ * Changed here: one entry per message, sent one at a time, so each arrives as
55
+ * its own delivery. The buffer also decides whether a message may go out
56
+ * directly — see {@link sendOrQueue} — because a caller that decides for itself
57
+ * is how messages end up overtaking a backlog.
58
+ *
59
+ * Unchanged from Theia: exceeding the limit rejects the message rather than
60
+ * dropping something silently. The limit is settable, since the right value
61
+ * depends on how long an outage has to survive.
62
+ *
63
+ * Added here: every message sent is numbered and kept until the peer
64
+ * acknowledges it, and {@link flush} resends what is still unacknowledged ahead
65
+ * of the backlog. A socket whose far end died unnoticed still accepts writes, so
66
+ * a message is not delivered just because it was sent.
67
+ *
68
+ * Logging goes to `console` rather than through a `Logger`. On the browser side
69
+ * Theia's preloader builds this before any Output channel exists, so there is
70
+ * nothing else to write to; the {@link CONNECTION_LOG_PREFIX} keeps the lines
71
+ * findable on both sides.
72
+ */
73
+ export class FramedSocketWriteBuffer extends SocketWriteBuffer {
74
+ /** Theia's fixed limit, kept as the default. */
75
+ static readonly DEFAULT_MAX_BYTES = 100 * 1024;
76
+
77
+ /**
78
+ * Settable so a deployment can trade memory for longer outages.
79
+ *
80
+ * Consulted directly rather than through the base class's `maxBufferSize`,
81
+ * which does not exist before Theia 1.71 — an `override` of it would not
82
+ * compile against the oldest release this package supports. Nothing is lost:
83
+ * `buffer`, `flush` and `drain` are all replaced here, so the base's own
84
+ * limit is never reached.
85
+ */
86
+ maxBytes = FramedSocketWriteBuffer.DEFAULT_MAX_BYTES;
87
+
88
+ /** Kept copies past this are discarded, so a peer that never acknowledges cannot grow them without bound. */
89
+ static readonly DEFAULT_MAX_UNACKNOWLEDGED_BYTES = 1024 * 1024;
90
+
91
+ /**
92
+ * Separate from {@link maxBytes}, which counts only what is produced while
93
+ * the peer is away: copies kept on a healthy connection must not use up the
94
+ * room an outage needs.
95
+ */
96
+ maxUnacknowledgedBytes = FramedSocketWriteBuffer.DEFAULT_MAX_UNACKNOWLEDGED_BYTES;
97
+
98
+ protected pending: Uint8Array[] = [];
99
+ protected pendingBytes = 0;
100
+ protected overflowReported = false;
101
+ protected readonly onOverflowEmitter = new Emitter<ConnectionBufferOverflow>();
102
+
103
+ protected nextSequence = 1;
104
+ /** Oldest first: {@link acknowledge} stops at the first entry the peer has not accepted. */
105
+ protected unacknowledged: { readonly sequence: number; readonly data: Uint8Array }[] = [];
106
+ protected unacknowledgedBytes = 0;
107
+ protected unacknowledgedOverflowReported = false;
108
+ /**
109
+ * Whether the peer drops a message it already has. One without the hardening
110
+ * applies a resent message a second time, so nothing is resent until the
111
+ * peer has shown otherwise.
112
+ */
113
+ protected peerDeduplicates = false;
114
+
115
+ /** Fires once per outage when the limit is reached. */
116
+ get onOverflow(): Event<ConnectionBufferOverflow> {
117
+ return this.onOverflowEmitter.event;
118
+ }
119
+
120
+ /**
121
+ * Sends `data` now only if nothing is waiting, and queues it otherwise.
122
+ *
123
+ * Callers say whether the peer is ready for a message; the buffer decides
124
+ * whether it may go ahead of one already waiting. Splitting it this way is
125
+ * the point: a caller that answers both questions from one flag is how a
126
+ * fresh message ends up overtaking a backlog.
127
+ */
128
+ sendOrQueue(socket: MessageSink | undefined, data: Uint8Array): void {
129
+ if (socket && !this.hasBacklog) {
130
+ this.send(socket, data);
131
+ } else {
132
+ this.buffer(data);
133
+ }
134
+ }
135
+
136
+ override buffer(data: Uint8Array): void {
137
+ if (this.pendingBytes + data.byteLength > this.maxBytes) {
138
+ this.reportOverflow();
139
+ throw new Error(`Max disconnected buffer size exceeded by adding ${data.byteLength} bytes`);
140
+ }
141
+ // Copied for the same reason the base class copies: the caller owns `data`.
142
+ this.pending.push(data.slice());
143
+ this.pendingBytes += data.byteLength;
144
+ if (this.pending.length === 1) {
145
+ console.info(`${CONNECTION_LOG_PREFIX} buffering messages, the peer is disconnected`);
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Kept only once `send` returns: a message whose send threw stays in the
151
+ * backlog, and keeping it as well would send it again under a second number,
152
+ * which the receiver cannot recognise as a duplicate.
153
+ */
154
+ protected send(socket: MessageSink, data: Uint8Array): void {
155
+ const sequence = this.nextSequence++;
156
+ socket.send(data, sequence);
157
+ this.keep(sequence, data);
158
+ }
159
+
160
+ protected keep(sequence: number, data: Uint8Array): void {
161
+ if (this.unacknowledgedBytes + data.byteLength > this.maxUnacknowledgedBytes) {
162
+ // Said only to a peer known to acknowledge: one without the hardening never does, and
163
+ // nothing would be resent to it anyway.
164
+ if (this.peerDeduplicates && !this.unacknowledgedOverflowReported) {
165
+ this.unacknowledgedOverflowReported = true;
166
+ console.warn(
167
+ `${CONNECTION_LOG_PREFIX} the peer has not acknowledged ${this.unacknowledged.length} message(s), ` +
168
+ `${this.unacknowledgedBytes} bytes; discarding their copies, so a connection dropped now loses them`
169
+ );
170
+ }
171
+ this.unacknowledged = [];
172
+ this.unacknowledgedBytes = 0;
173
+ return;
174
+ }
175
+ // Not copied: a committed write buffer hands over a fresh array and is disposed.
176
+ this.unacknowledged.push({ sequence, data });
177
+ this.unacknowledgedBytes += data.byteLength;
178
+ }
179
+
180
+ /**
181
+ * Records that the peer numbers its messages, which only a peer that also
182
+ * drops duplicates does, so resending to it is safe.
183
+ */
184
+ markPeerDeduplicates(): void {
185
+ this.peerDeduplicates = true;
186
+ }
187
+
188
+ /** Releases every kept message numbered up to `sequence`, which the peer has accepted. */
189
+ acknowledge(sequence: number): void {
190
+ this.peerDeduplicates = true;
191
+ let index = 0;
192
+ while (index < this.unacknowledged.length && this.unacknowledged[index].sequence <= sequence) {
193
+ this.unacknowledgedBytes -= this.unacknowledged[index].data.byteLength;
194
+ index++;
195
+ }
196
+ if (index > 0) {
197
+ this.unacknowledged = this.unacknowledged.slice(index);
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Resends what the peer has not acknowledged, under the same numbers, then
203
+ * sends the backlog. Some of the resent messages may have arrived already;
204
+ * the receiver recognises them by number and drops them.
205
+ *
206
+ * Resends only to a peer known to drop duplicates, and otherwise discards the
207
+ * copies, leaving any message lost with the old socket lost.
208
+ */
209
+ override flush(socket: MessageSink): void {
210
+ if (this.peerDeduplicates) {
211
+ for (const { sequence, data } of this.unacknowledged) {
212
+ socket.send(data, sequence);
213
+ }
214
+ if (this.unacknowledged.length > 0) {
215
+ console.info(
216
+ `${CONNECTION_LOG_PREFIX} resent ${this.unacknowledged.length} unacknowledged message(s), ${this.unacknowledgedBytes} bytes`
217
+ );
218
+ }
219
+ } else {
220
+ this.unacknowledged = [];
221
+ this.unacknowledgedBytes = 0;
222
+ }
223
+ if (this.pending.length === 0) {
224
+ return;
225
+ }
226
+ const count = this.pending.length;
227
+ const bytes = this.pendingBytes;
228
+ // Walked with an index and dropped in one slice, not shifted per message: a shift re-indexes
229
+ // the whole array, so the drain would cost the square of a backlog `bufferBytes` invites an
230
+ // adopter to enlarge. Leaving the queue in place is what keeps `hasBacklog` true until the
231
+ // last message is out, and re-reading the length is what drains one appended by a nested send.
232
+ let index = 0;
233
+ try {
234
+ while (index < this.pending.length) {
235
+ const message = this.pending[index];
236
+ this.send(socket, message);
237
+ index++;
238
+ this.pendingBytes -= message.byteLength;
239
+ }
240
+ } catch (error: unknown) {
241
+ // Said here because nothing retries: Theia flushes once, from a reconnect handler that has
242
+ // deregistered by now, so the stall would otherwise surface much later as an overflow —
243
+ // which names the wrong cause, the socket being up rather than absent.
244
+ console.error(
245
+ `${CONNECTION_LOG_PREFIX} send failed ${index} message(s) into a ${count}-message backlog; ` +
246
+ `${this.pending.length - index} still queued and nothing will retry them`,
247
+ error
248
+ );
249
+ throw error;
250
+ } finally {
251
+ this.pending = this.pending.slice(index);
252
+ }
253
+ this.overflowReported = false;
254
+ console.info(`${CONNECTION_LOG_PREFIX} sent ${count} buffered message(s), ${bytes} bytes`);
255
+ }
256
+
257
+ override drain(): void {
258
+ if (this.pending.length > 0 || this.unacknowledged.length > 0) {
259
+ console.warn(
260
+ `${CONNECTION_LOG_PREFIX} discarded ${this.pending.length} buffered message(s), ${this.pendingBytes} bytes, ` +
261
+ `and ${this.unacknowledged.length} sent but unacknowledged, ${this.unacknowledgedBytes} bytes`
262
+ );
263
+ }
264
+ this.reset();
265
+ }
266
+
267
+ /** Whether messages are still waiting to go out. */
268
+ get hasBacklog(): boolean {
269
+ return this.pending.length > 0;
270
+ }
271
+
272
+ protected reportOverflow(): void {
273
+ if (this.overflowReported) {
274
+ return;
275
+ }
276
+ this.overflowReported = true;
277
+ const overflow: ConnectionBufferOverflow = { messages: this.pending.length, bytes: this.pendingBytes, maxBytes: this.maxBytes };
278
+ console.error(
279
+ `${CONNECTION_LOG_PREFIX} buffer full at ${overflow.maxBytes} bytes after ${overflow.messages} message(s); ` +
280
+ 'this message is rejected, and so is every further one until the peer returns'
281
+ );
282
+ this.onOverflowEmitter.fire(overflow);
283
+ }
284
+
285
+ /** Also discards the kept copies: a drain ends the session, and resending them would replay it into the next one. */
286
+ protected reset(): void {
287
+ this.pending = [];
288
+ this.pendingBytes = 0;
289
+ this.overflowReported = false;
290
+ this.nextSequence = 1;
291
+ this.unacknowledged = [];
292
+ this.unacknowledgedBytes = 0;
293
+ this.unacknowledgedOverflowReported = false;
294
+ this.peerDeduplicates = false;
295
+ }
296
+ }
297
+
298
+ /** Named in the warning a skipped install emits, so the reader is told what to upgrade to. */
299
+ export const REQUIRED_THEIA_HINT = '@theia/core 1.71 or newer';
300
+
301
+ /**
302
+ * Whether this Theia exposes the seam the reconnect hardening replaces.
303
+ *
304
+ * Theia only began binding {@link SocketWriteBuffer} in 1.71; before that each
305
+ * connection built one privately, so there is no binding to rebind and no way
306
+ * in. Every other API involved has been there throughout, which makes this one
307
+ * probe the whole compatibility question — and it is a binding check rather
308
+ * than a version parse, so it answers about the container actually in front of
309
+ * us instead of a number that may have been overridden or vendored.
310
+ *
311
+ * Callers that get `false` must leave Theia's own wiring alone: rebinding half
312
+ * of it would be worse than not rebinding at all.
313
+ */
314
+ export function supportsConnectionResilience(isBound: (identifier: typeof SocketWriteBuffer) => boolean): boolean {
315
+ return isBound(SocketWriteBuffer);
316
+ }
317
+
318
+ /**
319
+ * The warning a skipped install emits. Says what is lost rather than only what
320
+ * is missing: the failures this guards against are silent, so an adopter who
321
+ * never sees this line has no other way to learn the guard is absent.
322
+ */
323
+ export function warnConnectionResilienceUnavailable(tier: 'frontend' | 'backend'): void {
324
+ console.warn(
325
+ `${CONNECTION_LOG_PREFIX} ${tier} reconnect hardening NOT installed: this Theia does not expose an injectable ` +
326
+ `socket write buffer (needs ${REQUIRED_THEIA_HINT}). Theia's own behaviour is left in place, which can lose or ` +
327
+ 'reorder messages when a socket drops and reconnects.'
328
+ );
329
+ }
330
+
331
+ /** Builds a buffer with the configured limits, or the defaults for any not configured. */
332
+ export function createFramedSocketWriteBuffer(options: ConnectionResilienceOptions = {}): FramedSocketWriteBuffer {
333
+ const buffer = new FramedSocketWriteBuffer();
334
+ if (isPositive(options.bufferBytes)) {
335
+ buffer.maxBytes = options.bufferBytes;
336
+ }
337
+ if (isPositive(options.unacknowledgedBytes)) {
338
+ buffer.maxUnacknowledgedBytes = options.unacknowledgedBytes;
339
+ }
340
+ return buffer;
341
+ }
342
+
343
+ function isPositive(value: number | undefined): value is number {
344
+ return typeof value === 'number' && value > 0;
345
+ }
@@ -0,0 +1,102 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { CONNECTION_LOG_PREFIX } from './framed-socket-write-buffer';
11
+
12
+ /** The socket.io event that carries the highest message number a side has accepted. */
13
+ export const ACKNOWLEDGEMENT_EVENT = 'hydranium:ack';
14
+
15
+ /**
16
+ * What one side has received on a session: drops a message it already accepted
17
+ * and acknowledges the rest.
18
+ *
19
+ * The peer resends everything unacknowledged when a session resumes, because it
20
+ * cannot tell which of its messages died with the old socket, so every resumed
21
+ * session can repeat messages already delivered. Delivering one twice corrupts
22
+ * anything applied by position, just as losing one does.
23
+ *
24
+ * Acknowledges once enough has arrived, and otherwise after a short delay. A
25
+ * timer alone is not enough: a background tab throttles timers, and the peer
26
+ * holds every unacknowledged message until the acknowledgement arrives. The
27
+ * first message of a session is acknowledged at once, because the peer resends
28
+ * nothing until an acknowledgement shows it may.
29
+ *
30
+ * Belongs to one session. A new session numbers from the start again, so it
31
+ * needs a new instance.
32
+ */
33
+ export class InboundMessageSequence {
34
+ static readonly ACKNOWLEDGE_AFTER_MESSAGES = 64;
35
+ static readonly ACKNOWLEDGE_AFTER_BYTES = 32 * 1024;
36
+ static readonly ACKNOWLEDGE_DELAY_MS = 100;
37
+
38
+ protected lastAccepted = 0;
39
+ protected messagesSinceAcknowledgement = 0;
40
+ protected bytesSinceAcknowledgement = 0;
41
+ protected acknowledgementTimer: ReturnType<typeof setTimeout> | undefined;
42
+
43
+ constructor(protected readonly sendAcknowledgement: (sequence: number) => void) {}
44
+
45
+ /**
46
+ * Whether to deliver a message that arrived with `sequence`.
47
+ *
48
+ * A message without a number comes from a peer that does not number them,
49
+ * and is delivered as it is. A duplicate is still acknowledged: the peer
50
+ * resent it because an earlier acknowledgement was lost, and keeps it until
51
+ * one arrives.
52
+ *
53
+ * A skipped number is delivered past, with a warning: the skipped messages
54
+ * are lost, and this is the one place that can tell.
55
+ */
56
+ accept(sequence: unknown, bytes: number): boolean {
57
+ if (typeof sequence !== 'number') {
58
+ return true;
59
+ }
60
+ const isFirst = this.lastAccepted === 0;
61
+ const isNew = sequence > this.lastAccepted;
62
+ if (isNew) {
63
+ if (sequence > this.lastAccepted + 1) {
64
+ const missing = sequence - this.lastAccepted - 1;
65
+ console.warn(
66
+ `${CONNECTION_LOG_PREFIX} lost ${missing} message(s), numbered ${this.lastAccepted + 1} to ${sequence - 1}; ` +
67
+ 'they never arrived and nothing will resend them'
68
+ );
69
+ }
70
+ this.lastAccepted = sequence;
71
+ }
72
+ this.messagesSinceAcknowledgement++;
73
+ this.bytesSinceAcknowledgement += bytes;
74
+ if (
75
+ isFirst ||
76
+ this.messagesSinceAcknowledgement >= InboundMessageSequence.ACKNOWLEDGE_AFTER_MESSAGES ||
77
+ this.bytesSinceAcknowledgement >= InboundMessageSequence.ACKNOWLEDGE_AFTER_BYTES
78
+ ) {
79
+ this.acknowledge();
80
+ } else {
81
+ this.acknowledgementTimer ??= setTimeout(() => this.acknowledge(), InboundMessageSequence.ACKNOWLEDGE_DELAY_MS);
82
+ }
83
+ return isNew;
84
+ }
85
+
86
+ /** Sends the acknowledgement now rather than waiting for more traffic. */
87
+ acknowledge(): void {
88
+ this.cancelTimer();
89
+ this.messagesSinceAcknowledgement = 0;
90
+ this.bytesSinceAcknowledgement = 0;
91
+ this.sendAcknowledgement(this.lastAccepted);
92
+ }
93
+
94
+ dispose(): void {
95
+ this.cancelTimer();
96
+ }
97
+
98
+ protected cancelTimer(): void {
99
+ clearTimeout(this.acknowledgementTimer);
100
+ this.acknowledgementTimer = undefined;
101
+ }
102
+ }
@@ -0,0 +1,16 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ // Environment-neutral primitives that the browser and the server tiers each
11
+ // bind for their own side, such as the buffer for each half of the socket.
12
+ // Kept out of both tier barrels for that reason.
13
+ export * from './framed-socket-write-buffer';
14
+ export * from './inbound-message-sequence';
15
+ export * from './connection-resilience-options';
16
+ export * from './clock';
@@ -7,6 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
+ import { SystemClock } 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 single per-head variation — *which* byte forwarder bridges the channel and
65
- * the socket — is the abstract {@link forwardToSocketConnection} hook: the GLSP
66
- * head plugs in `@eclipse-glsp/theia-integration`'s `SocketConnectionForwarder`,
67
- * the data-server head its own `SocketChannelForwarder`. Keeping the forwarder
68
- * behind the hook is what lets the data head stay GLSP-free while sharing the
69
- * port-discovery + buffer-and-replay race fix + connect orchestration here.
67
+ * The byte forwarder that bridges the channel and the socket is
68
+ * {@link forwardToSocketConnection}; both heads use {@link SocketChannelForwarder},
69
+ * and the port discovery, buffer-and-replay race fix and connect orchestration
70
+ * here are shared.
70
71
  */
71
72
  @injectable()
72
73
  export abstract class AbstractSocketForwardingConnectionHandler implements ConnectionHandler {
@@ -76,6 +77,8 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
76
77
  // not the spawned language-server process, so the framework `LspLogger`
77
78
  // (which needs the Langium connection/services) is out of reach here.
78
79
  @inject(ILogger) protected readonly logger!: ILogger;
80
+ /** The clock each {@link SocketChannelForwarder} bounds its flush on: the container's {@link Clock}, or a `SystemClock`. */
81
+ @inject(Clock) @optional() protected readonly clock: Clock = new SystemClock();
79
82
 
80
83
  readonly path: string;
81
84
 
@@ -114,31 +117,67 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
114
117
  // window.
115
118
  const buffered: MessageProvider[] = [];
116
119
  const bufferSub = channel.onMessage(provider => buffered.push(provider));
120
+ const closed = new AbortController();
121
+ const closeSub = channel.onClose(() => closed.abort());
117
122
  try {
118
- const port = await this.findPort();
123
+ const port = await this.findPort(closed.signal);
124
+ closed.signal.throwIfAborted();
119
125
  this.logger.info(`[${this.logComponent}] Connecting to ${this.serverName} on port ${port}...`);
120
126
  await this.connectToServer(channel, port, { bufferSub, buffered });
121
127
  this.logger.info(`[${this.logComponent}] Connected to ${this.serverName} on port ${port}.`);
122
128
  } catch (error) {
123
129
  bufferSub.dispose();
130
+ if (closed.signal.aborted) {
131
+ this.logger.info(`[${this.logComponent}] Stopped connecting to ${this.serverName}: the frontend closed the channel.`);
132
+ return;
133
+ }
124
134
  const message = error && typeof error === 'object' && 'message' in error ? String(error.message) : String(error);
125
135
  this.logger.error(`[${this.logComponent}] Could not connect to ${this.serverName}: ${message}`);
126
- this.messageService.error(`Could not connect to ${this.serverName}: ` + message);
136
+ this.reportConnectFailure(message);
137
+ // Closed so the frontend learns of it: left open, the channel has no
138
+ // server behind it, and every request on it waits for good.
139
+ channel.close();
140
+ } finally {
141
+ closeSub.dispose();
127
142
  }
128
143
  }
129
144
 
130
- protected async findPort(): Promise<number> {
145
+ /** Tell the user this handler gave up; `message` is the reason it logged. */
146
+ protected reportConnectFailure(message: string): void {
147
+ this.messageService.error(`Could not connect to ${this.serverName}: ` + message);
148
+ }
149
+
150
+ /** Poll the port command until it answers, its attempts run out, or `signal` aborts. */
151
+ protected async findPort(signal?: AbortSignal): Promise<number> {
131
152
  const pendingContent = new Deferred<number>();
132
153
  let counter = 0;
154
+ let timer: ReturnType<typeof setTimeout> | undefined;
155
+ const stop = (): void => {
156
+ clearTimeout(timer);
157
+ pendingContent.reject(signal?.reason);
158
+ };
159
+ if (signal?.aborted) {
160
+ stop();
161
+ }
162
+ signal?.addEventListener('abort', stop, { once: true });
133
163
  const tryQueryingPort = (): void => {
134
- setTimeout(async () => {
164
+ if (signal?.aborted) {
165
+ return;
166
+ }
167
+ timer = setTimeout(async () => {
135
168
  try {
136
169
  const port = await this.commandService.executeCommand<number>(this.portCommand);
137
- if (port) {
138
- pendingContent.resolve(port);
170
+ // An empty answer fails the attempt like a throw does: left
171
+ // unanswered, it neither resolves nor re-queues, and the lookup
172
+ // stays pending with nothing logged.
173
+ if (!port) {
174
+ throw new Error(`Port command '${this.portCommand}' answered without a port.`);
139
175
  }
176
+ pendingContent.resolve(port);
140
177
  } catch (error) {
141
178
  counter++;
179
+ const message = error instanceof Error ? error.message : String(error);
180
+ this.logger.debug(`[${this.logComponent}] Port command '${this.portCommand}' attempt ${counter} failed: ${message}`);
142
181
  if (this.findPortAttempts >= 0 && counter > this.findPortAttempts) {
143
182
  pendingContent.reject(error);
144
183
  } else {
@@ -175,7 +214,12 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
175
214
  if (channel instanceof ForwardingChannel) {
176
215
  socket.on('error', error => channel.onErrorEmitter.fire(error));
177
216
  }
178
- socket.connect({ port });
217
+ // `127.0.0.1`, not the `localhost` Node dials when no host is given, and it
218
+ // has to match the head: the socket launchers bind `127.0.0.1` by default,
219
+ // so on a dual-stack machine where `localhost` resolves to `::1` first the
220
+ // dial fails as ECONNREFUSED with nothing in the message naming the address
221
+ // family as the cause.
222
+ socket.connect({ port, host: '127.0.0.1' });
179
223
  setTimeout(() => connected.reject('Timeout reached.'), this.connectTimeoutMs);
180
224
  return connected.promise;
181
225
  }
@@ -185,7 +229,9 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
185
229
  * relay both ways. Called once, after the socket is created and the
186
230
  * pre-forward buffer is about to be replayed.
187
231
  */
188
- protected abstract forwardToSocketConnection(clientChannel: Channel, socket: net.Socket): Disposable;
232
+ protected forwardToSocketConnection(clientChannel: Channel, socket: net.Socket): Disposable {
233
+ return new SocketChannelForwarder(clientChannel, socket, this.clock);
234
+ }
189
235
 
190
236
  /**
191
237
  * Re-fire pre-forward buffered `MessageProvider`s on the channel's internal
package/src/node/index.ts CHANGED
@@ -8,3 +8,5 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  export * from './abstract-socket-forwarding-connection-handler';
11
+ export * from './session-bound-frontend-connection-service';
12
+ export * from './socket-channel-forwarder';