@hydranium/client-theia 1.0.0-next.9 → 1.0.0-next.91

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 (55) 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/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
  34. package/lib/node/abstract-socket-forwarding-connection-handler.js +6 -1
  35. package/lib/node/abstract-socket-forwarding-connection-handler.js.map +1 -1
  36. package/lib/node/index.d.ts +1 -0
  37. package/lib/node/index.d.ts.map +1 -1
  38. package/lib/node/index.js +1 -0
  39. package/lib/node/index.js.map +1 -1
  40. package/lib/node/session-bound-frontend-connection-service.d.ts +77 -0
  41. package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
  42. package/lib/node/session-bound-frontend-connection-service.js +128 -0
  43. package/lib/node/session-bound-frontend-connection-service.js.map +1 -0
  44. package/package.json +16 -7
  45. package/src/browser/connection-diagnostics-contribution.ts +142 -0
  46. package/src/browser/index.ts +2 -0
  47. package/src/browser/log-level-preference.ts +11 -0
  48. package/src/browser/memory-diagnostics-contribution.ts +268 -45
  49. package/src/browser/session-aware-connection-source.ts +179 -0
  50. package/src/common/connection-resilience-options.ts +24 -0
  51. package/src/common/framed-socket-write-buffer.ts +227 -0
  52. package/src/common/index.ts +14 -0
  53. package/src/node/abstract-socket-forwarding-connection-handler.ts +6 -1
  54. package/src/node/index.ts +1 -0
  55. package/src/node/session-bound-frontend-connection-service.ts +155 -0
@@ -14,7 +14,7 @@ import {
14
14
  type StartProfilingArgs
15
15
  } from '@hydranium/protocol';
16
16
  import { captureBrowserRuntime, formatBrowserRuntime } from './browser-capture';
17
- import { CommandContribution, MessageService, type Command, type CommandRegistry } from '@theia/core';
17
+ import { CommandContribution, MessageService, nls, type Command, type CommandRegistry } from '@theia/core';
18
18
  import { inject, injectable, optional, type interfaces } from '@theia/core/shared/inversify';
19
19
  import { OutputChannelManager, type OutputChannel } from '@theia/output/lib/browser/output-channel';
20
20
 
@@ -54,6 +54,17 @@ export const MemoryDiagnosticsService = Symbol('MemoryDiagnosticsService');
54
54
  export type HostMemoryDiagnosticsService = HostDiagnosticsProtocol;
55
55
  export const HostMemoryDiagnosticsService = Symbol('HostMemoryDiagnosticsService');
56
56
 
57
+ /**
58
+ * What a `report` call captured, as a code rather than a prose fragment. The
59
+ * sentences it appears in are authored once per code, because a fragment
60
+ * substituted into a sentence is itself translatable text and a translator
61
+ * given the sentence alone cannot inflect around a hole.
62
+ */
63
+ export type DiagnosticsSubject = 'server-state' | 'pod-memory' | 'latency' | 'backend-state' | 'profile';
64
+
65
+ /** Which process a heap snapshot is taken of; a code, for the reason {@link DiagnosticsSubject} is one. */
66
+ export type HeapSnapshotTarget = 'server' | 'backend';
67
+
57
68
  /**
58
69
  * Memory-diagnostics commands, one per layer reachable from the frontend. Full
59
70
  * multi-line snapshots are appended to the configured output channel; a one-line
@@ -88,76 +99,162 @@ export class MemoryDiagnosticsContribution implements CommandContribution {
88
99
  * localized apart, leaving a button or an instruction that names a command
89
100
  * the user cannot find.
90
101
  */
91
- protected readonly stopProfilingLabel: string = 'Stop Profiling (Server)';
102
+ protected readonly stopProfilingLabel: string = nls.localize(
103
+ 'hydranium/client-theia/command-stop-profiling-server',
104
+ 'Stop Profiling (Server)'
105
+ );
92
106
 
93
107
  registerCommands(registry: CommandRegistry): void {
94
108
  const { category } = this.options;
95
- registry.registerCommand(this.command('dumpServerState', 'Dump Server State', category), {
96
- execute: () => this.report('server state', () => this.diagnostics.dumpServerState({ label: new Date().toISOString() }), ['heap'])
97
- });
98
- registry.registerCommand(this.command('dumpPodMemory', 'Dump Pod Memory', category), {
99
- execute: () => this.report('pod memory', () => this.diagnostics.dumpPodMemory(), ['current', 'rss sum'])
100
- });
101
- registry.registerCommand(this.command('dumpFrontendState', 'Dump Frontend State', category), {
102
- execute: () => this.dumpFrontendState()
103
- });
104
- registry.registerCommand(this.command('writeHeapSnapshot', 'Write Heap Snapshot (Server)', category), {
105
- execute: () => this.writeSnapshot('server', label => this.diagnostics.writeHeapSnapshot({ label }))
106
- });
109
+ registry.registerCommand(
110
+ this.command({
111
+ id: 'dumpServerState',
112
+ label: nls.localize('hydranium/client-theia/command-dump-server-state', 'Dump Server State'),
113
+ category
114
+ }),
115
+ {
116
+ execute: () =>
117
+ this.report('server-state', () => this.diagnostics.dumpServerState({ label: new Date().toISOString() }), ['heap'])
118
+ }
119
+ );
120
+ registry.registerCommand(
121
+ this.command({
122
+ id: 'dumpPodMemory',
123
+ label: nls.localize('hydranium/client-theia/command-dump-pod-memory', 'Dump Pod Memory'),
124
+ category
125
+ }),
126
+ {
127
+ execute: () => this.report('pod-memory', () => this.diagnostics.dumpPodMemory(), ['current', 'rss sum'])
128
+ }
129
+ );
130
+ registry.registerCommand(
131
+ this.command({
132
+ id: 'dumpFrontendState',
133
+ label: nls.localize('hydranium/client-theia/command-dump-frontend-state', 'Dump Frontend State'),
134
+ category
135
+ }),
136
+ {
137
+ execute: () => this.dumpFrontendState()
138
+ }
139
+ );
140
+ registry.registerCommand(
141
+ this.command({
142
+ id: 'writeHeapSnapshot',
143
+ label: nls.localize('hydranium/client-theia/command-write-heap-snapshot-server', 'Write Heap Snapshot (Server)'),
144
+ category
145
+ }),
146
+ {
147
+ execute: () => this.writeSnapshot('server', label => this.diagnostics.writeHeapSnapshot({ label }))
148
+ }
149
+ );
107
150
  // Sampled profiling of the server process — sampling does NOT pause it (unlike
108
151
  // the heap snapshot). Start/Stop are the manual pair; Record wraps a fixed window.
109
- registry.registerCommand(this.command('startProfiling', 'Start Profiling (Server)', category), {
110
- execute: () => this.startProfiling()
111
- });
112
- registry.registerCommand(this.command('stopProfiling', this.stopProfilingLabel, category), {
152
+ registry.registerCommand(
153
+ this.command({
154
+ id: 'startProfiling',
155
+ label: nls.localize('hydranium/client-theia/command-start-profiling-server', 'Start Profiling (Server)'),
156
+ category
157
+ }),
158
+ {
159
+ execute: () => this.startProfiling()
160
+ }
161
+ );
162
+ registry.registerCommand(this.command({ id: 'stopProfiling', label: this.stopProfilingLabel, category }), {
113
163
  execute: () => this.stopProfiling()
114
164
  });
115
165
  registry.registerCommand(
116
- this.command('recordProfile', `Record Performance Profile (Server, ${Math.round(this.recordDurationMs / 1000)}s)`, category),
166
+ this.command({
167
+ id: 'recordProfile',
168
+ // The window length rides the substitution path rather than a
169
+ // template literal: an extractor reads the source text, so an
170
+ // interpolated default is never in the catalogue at all.
171
+ label: nls.localize(
172
+ 'hydranium/client-theia/command-record-profile',
173
+ 'Record Performance Profile (Server, {0}s)',
174
+ this.recordDurationSeconds()
175
+ ),
176
+ category
177
+ }),
117
178
  {
118
179
  execute: () => this.recordProfile()
119
180
  }
120
181
  );
121
- registry.registerCommand(this.command('dumpLatency', 'Dump RPC/LSP Latency (Server)', category), {
122
- execute: () => this.report('RPC/LSP latency', async () => formatLatencyReport(await this.diagnostics.getLatency()), ['window'])
123
- });
182
+ registry.registerCommand(
183
+ this.command({
184
+ id: 'dumpLatency',
185
+ label: nls.localize('hydranium/client-theia/command-dump-latency', 'Dump RPC/LSP Latency (Server)'),
186
+ category
187
+ }),
188
+ {
189
+ execute: () => this.report('latency', async () => formatLatencyReport(await this.diagnostics.getLatency()), ['window'])
190
+ }
191
+ );
124
192
  // Host (Theia backend) process commands — registered only when the
125
193
  // optional host-diagnostics service is bound (see HostMemoryDiagnosticsService).
126
194
  const hostDiagnostics = this.hostDiagnostics;
127
195
  if (hostDiagnostics) {
128
- registry.registerCommand(this.command('dumpBackendState', 'Dump Backend State', category), {
129
- execute: () => this.report('backend state', () => hostDiagnostics.dumpHostState({ label: new Date().toISOString() }), ['heap'])
130
- });
131
- registry.registerCommand(this.command('writeBackendHeapSnapshot', 'Write Heap Snapshot (Backend)', category), {
132
- execute: () => this.writeSnapshot('backend', label => hostDiagnostics.writeHostHeapSnapshot({ label }))
133
- });
196
+ registry.registerCommand(
197
+ this.command({
198
+ id: 'dumpBackendState',
199
+ label: nls.localize('hydranium/client-theia/command-dump-backend-state', 'Dump Backend State'),
200
+ category
201
+ }),
202
+ {
203
+ execute: () =>
204
+ this.report('backend-state', () => hostDiagnostics.dumpHostState({ label: new Date().toISOString() }), ['heap'])
205
+ }
206
+ );
207
+ registry.registerCommand(
208
+ this.command({
209
+ id: 'writeBackendHeapSnapshot',
210
+ label: nls.localize('hydranium/client-theia/command-write-heap-snapshot-backend', 'Write Heap Snapshot (Backend)'),
211
+ category
212
+ }),
213
+ {
214
+ execute: () => this.writeSnapshot('backend', label => hostDiagnostics.writeHostHeapSnapshot({ label }))
215
+ }
216
+ );
134
217
  }
135
218
  }
136
219
 
137
- protected command(id: string, label: string, category: string): Command {
138
- return { id: `${this.options.commandIdPrefix}.${id}`, label, category };
220
+ /**
221
+ * Takes an object rather than positional arguments so that `label` — the one
222
+ * user-facing member — is addressable by name. A lint rule guarding the
223
+ * localization of labels has only syntax to work with, and a selector for an
224
+ * argument position would equally catch `id`, which must stay a bare literal.
225
+ */
226
+ protected command(spec: { id: string; label: string; category: string }): Command {
227
+ return { id: `${this.options.commandIdPrefix}.${spec.id}`, label: spec.label, category: spec.category };
228
+ }
229
+
230
+ /** The record window as whole seconds, for the label and the toast that must agree on it. */
231
+ protected recordDurationSeconds(): number {
232
+ return Math.round(this.recordDurationMs / 1000);
139
233
  }
140
234
 
141
235
  /** Run a snapshot call, append the full result to the channel, toast the first matching summary line. */
142
- protected async report(what: string, produce: () => Promise<string>, summaryKeys: string[]): Promise<void> {
236
+ protected async report(subject: DiagnosticsSubject, produce: () => Promise<string>, summaryKeys: string[]): Promise<void> {
143
237
  try {
144
238
  const snapshot = await produce();
145
239
  this.channel().appendLine(snapshot);
146
240
  this.channel().appendLine('');
147
- this.messageService.info(this.summarize(snapshot, what, summaryKeys), { timeout: 5000 });
241
+ this.messageService.info(this.summarize(snapshot, subject, summaryKeys), { timeout: 5000 });
148
242
  } catch (error) {
149
- this.messageService.error(`Failed to dump ${what}: ${this.errorMessage(error)}`);
243
+ this.messageService.error(this.dumpFailedMessage(subject, this.errorMessage(error)));
150
244
  }
151
245
  }
152
246
 
153
- protected async writeSnapshot(target: string, produce: (label: string) => Promise<string>): Promise<void> {
247
+ protected async writeSnapshot(target: HeapSnapshotTarget, produce: (label: string) => Promise<string>): Promise<void> {
154
248
  try {
155
- this.messageService.info(`Writing ${target} heap snapshot — this briefly pauses that process...`, { timeout: 3000 });
249
+ this.messageService.info(this.writingSnapshotMessage(target), { timeout: 3000 });
156
250
  const filePath = await produce(new Date().toISOString());
157
- this.channel().appendLine(`Heap snapshot (${target}) written to ${filePath}`);
158
- this.messageService.info(`Heap snapshot (${target}) written to ${filePath}`, { timeout: 8000 });
251
+ // One sentence, shown in both places: two literals of equal value can be
252
+ // localized apart, leaving the channel and the toast naming different files.
253
+ const written = this.wroteSnapshotMessage(target, filePath);
254
+ this.channel().appendLine(written);
255
+ this.messageService.info(written, { timeout: 8000 });
159
256
  } catch (error) {
160
- this.messageService.error(`Failed to write ${target} heap snapshot: ${this.errorMessage(error)}`);
257
+ this.messageService.error(this.writeSnapshotFailedMessage(target, this.errorMessage(error)));
161
258
  }
162
259
  }
163
260
 
@@ -166,7 +263,7 @@ export class MemoryDiagnosticsContribution implements CommandContribution {
166
263
  try {
167
264
  await this.diagnostics.startProfiling(this.profileDimensions);
168
265
  } catch (error) {
169
- this.messageService.error(`Failed to start profiling: ${this.errorMessage(error)}`);
266
+ this.messageService.error(this.startProfilingFailedMessage(this.errorMessage(error)));
170
267
  return;
171
268
  }
172
269
  // No timeout: the capture runs as long as the user wants it to, and an
@@ -174,7 +271,7 @@ export class MemoryDiagnosticsContribution implements CommandContribution {
174
271
  // toast is what keeps the action live, so this resolves only once the
175
272
  // user acts on it or dismisses it.
176
273
  const chosen = await this.messageService.info(
177
- 'Server profiling started — sampling does not stop the process.',
274
+ nls.localize('hydranium/client-theia/profiling-started', 'Server profiling started — sampling does not stop the process.'),
178
275
  { timeout: 0 },
179
276
  this.stopProfilingLabel
180
277
  );
@@ -188,15 +285,27 @@ export class MemoryDiagnosticsContribution implements CommandContribution {
188
285
  return this.report('profile', () => this.diagnostics.stopProfiling({ label: new Date().toISOString() }), ['duration']);
189
286
  }
190
287
 
288
+ /** One authored sentence for both start paths; identical literals in two places drift apart under translation. */
289
+ protected startProfilingFailedMessage(detail: string): string {
290
+ return nls.localize('hydranium/client-theia/error-start-profiling', 'Failed to start profiling: {0}', detail);
291
+ }
292
+
191
293
  /** Capture a fixed-length window: start, wait, stop, and report the result. */
192
294
  protected async recordProfile(): Promise<void> {
193
295
  try {
194
296
  await this.diagnostics.startProfiling(this.profileDimensions);
195
297
  } catch (error) {
196
- this.messageService.error(`Failed to start profiling: ${this.errorMessage(error)}`);
298
+ this.messageService.error(this.startProfilingFailedMessage(this.errorMessage(error)));
197
299
  return;
198
300
  }
199
- this.messageService.info(`Recording a ${Math.round(this.recordDurationMs / 1000)}s server performance profile...`, { timeout: 4000 });
301
+ this.messageService.info(
302
+ nls.localize(
303
+ 'hydranium/client-theia/recording-profile',
304
+ 'Recording a {0}s server performance profile...',
305
+ this.recordDurationSeconds()
306
+ ),
307
+ { timeout: 4000 }
308
+ );
200
309
  await this.delay(this.recordDurationMs);
201
310
  await this.stopProfiling();
202
311
  }
@@ -219,15 +328,129 @@ export class MemoryDiagnosticsContribution implements CommandContribution {
219
328
  }
220
329
 
221
330
  /** Pull the first line starting with one of `keys` for a one-line toast; full text is in the channel. */
222
- protected summarize(snapshot: string, what: string, keys: string[]): string {
331
+ protected summarize(snapshot: string, subject: DiagnosticsSubject, keys: string[]): string {
223
332
  const lines = snapshot.split('\n');
224
333
  for (const key of keys) {
225
334
  const line = lines.find(entry => entry.trim().startsWith(key));
226
335
  if (line) {
227
- return `Captured ${what} —${line.replace(new RegExp(`^\\s*${key}\\s*`), ` ${key} `)}`;
336
+ return this.capturedDetailMessage(subject, line.replace(new RegExp(`^\\s*${key}\\s*`), ` ${key} `));
228
337
  }
229
338
  }
230
- return `Captured ${what} (see the ${this.options.channelName} output channel)`;
339
+ return this.capturedChannelMessage(subject);
340
+ }
341
+
342
+ /**
343
+ * The captured-with-detail toast. The detail is a machine-formatted figure,
344
+ * so it is safe as a substitution parameter; the subject is not, hence one
345
+ * authored sentence per subject.
346
+ */
347
+ protected capturedDetailMessage(subject: DiagnosticsSubject, detail: string): string {
348
+ switch (subject) {
349
+ case 'server-state':
350
+ return nls.localize('hydranium/client-theia/captured-server-state-detail', 'Captured server state —{0}', detail);
351
+ case 'pod-memory':
352
+ return nls.localize('hydranium/client-theia/captured-pod-memory-detail', 'Captured pod memory —{0}', detail);
353
+ case 'latency':
354
+ return nls.localize('hydranium/client-theia/captured-latency-detail', 'Captured RPC/LSP latency —{0}', detail);
355
+ case 'backend-state':
356
+ return nls.localize('hydranium/client-theia/captured-backend-state-detail', 'Captured backend state —{0}', detail);
357
+ case 'profile':
358
+ return nls.localize('hydranium/client-theia/captured-profile-detail', 'Captured profile —{0}', detail);
359
+ }
360
+ }
361
+
362
+ /** The captured-without-detail toast; the channel name is adopter branding, not translatable text. */
363
+ protected capturedChannelMessage(subject: DiagnosticsSubject): string {
364
+ const channelName = this.options.channelName;
365
+ switch (subject) {
366
+ case 'server-state':
367
+ return nls.localize(
368
+ 'hydranium/client-theia/captured-server-state-channel',
369
+ 'Captured server state (see the {0} output channel)',
370
+ channelName
371
+ );
372
+ case 'pod-memory':
373
+ return nls.localize(
374
+ 'hydranium/client-theia/captured-pod-memory-channel',
375
+ 'Captured pod memory (see the {0} output channel)',
376
+ channelName
377
+ );
378
+ case 'latency':
379
+ return nls.localize(
380
+ 'hydranium/client-theia/captured-latency-channel',
381
+ 'Captured RPC/LSP latency (see the {0} output channel)',
382
+ channelName
383
+ );
384
+ case 'backend-state':
385
+ return nls.localize(
386
+ 'hydranium/client-theia/captured-backend-state-channel',
387
+ 'Captured backend state (see the {0} output channel)',
388
+ channelName
389
+ );
390
+ case 'profile':
391
+ return nls.localize(
392
+ 'hydranium/client-theia/captured-profile-channel',
393
+ 'Captured profile (see the {0} output channel)',
394
+ channelName
395
+ );
396
+ }
397
+ }
398
+
399
+ /** The failed-to-dump toast; the detail is a technical error string, safe as a parameter. */
400
+ protected dumpFailedMessage(subject: DiagnosticsSubject, detail: string): string {
401
+ switch (subject) {
402
+ case 'server-state':
403
+ return nls.localize('hydranium/client-theia/error-dump-server-state', 'Failed to dump server state: {0}', detail);
404
+ case 'pod-memory':
405
+ return nls.localize('hydranium/client-theia/error-dump-pod-memory', 'Failed to dump pod memory: {0}', detail);
406
+ case 'latency':
407
+ return nls.localize('hydranium/client-theia/error-dump-latency', 'Failed to dump RPC/LSP latency: {0}', detail);
408
+ case 'backend-state':
409
+ return nls.localize('hydranium/client-theia/error-dump-backend-state', 'Failed to dump backend state: {0}', detail);
410
+ case 'profile':
411
+ return nls.localize('hydranium/client-theia/error-dump-profile', 'Failed to dump profile: {0}', detail);
412
+ }
413
+ }
414
+
415
+ protected writingSnapshotMessage(target: HeapSnapshotTarget): string {
416
+ switch (target) {
417
+ case 'server':
418
+ return nls.localize(
419
+ 'hydranium/client-theia/writing-heap-snapshot-server',
420
+ 'Writing server heap snapshot — this briefly pauses that process...'
421
+ );
422
+ case 'backend':
423
+ return nls.localize(
424
+ 'hydranium/client-theia/writing-heap-snapshot-backend',
425
+ 'Writing backend heap snapshot — this briefly pauses that process...'
426
+ );
427
+ }
428
+ }
429
+
430
+ protected wroteSnapshotMessage(target: HeapSnapshotTarget, filePath: string): string {
431
+ switch (target) {
432
+ case 'server':
433
+ return nls.localize('hydranium/client-theia/wrote-heap-snapshot-server', 'Heap snapshot (server) written to {0}', filePath);
434
+ case 'backend':
435
+ return nls.localize('hydranium/client-theia/wrote-heap-snapshot-backend', 'Heap snapshot (backend) written to {0}', filePath);
436
+ }
437
+ }
438
+
439
+ protected writeSnapshotFailedMessage(target: HeapSnapshotTarget, detail: string): string {
440
+ switch (target) {
441
+ case 'server':
442
+ return nls.localize(
443
+ 'hydranium/client-theia/error-write-heap-snapshot-server',
444
+ 'Failed to write server heap snapshot: {0}',
445
+ detail
446
+ );
447
+ case 'backend':
448
+ return nls.localize(
449
+ 'hydranium/client-theia/error-write-heap-snapshot-backend',
450
+ 'Failed to write backend heap snapshot: {0}',
451
+ detail
452
+ );
453
+ }
231
454
  }
232
455
 
233
456
  protected errorMessage(error: unknown): string {
@@ -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
+ }