@hydranium/client-theia 1.0.0-next.18 → 1.0.0-next.181

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 (89) hide show
  1. package/README.md +39 -6
  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 +9 -4
  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 +133 -0
  16. package/lib/browser/editor-disk-sync.d.ts.map +1 -0
  17. package/lib/browser/editor-disk-sync.js +232 -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 +98 -0
  35. package/lib/browser/session-aware-connection-source.d.ts.map +1 -0
  36. package/lib/browser/session-aware-connection-source.js +167 -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 +24 -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 +121 -0
  47. package/lib/common/framed-socket-write-buffer.d.ts.map +1 -0
  48. package/lib/common/framed-socket-write-buffer.js +190 -0
  49. package/lib/common/framed-socket-write-buffer.js.map +1 -0
  50. package/lib/common/index.d.ts +12 -0
  51. package/lib/common/index.d.ts.map +1 -0
  52. package/lib/common/index.js +31 -0
  53. package/lib/common/index.js.map +1 -0
  54. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts +12 -8
  55. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
  56. package/lib/node/abstract-socket-forwarding-connection-handler.js +70 -13
  57. package/lib/node/abstract-socket-forwarding-connection-handler.js.map +1 -1
  58. package/lib/node/index.d.ts +2 -0
  59. package/lib/node/index.d.ts.map +1 -1
  60. package/lib/node/index.js +2 -0
  61. package/lib/node/index.js.map +1 -1
  62. package/lib/node/session-bound-frontend-connection-service.d.ts +77 -0
  63. package/lib/node/session-bound-frontend-connection-service.d.ts.map +1 -0
  64. package/lib/node/session-bound-frontend-connection-service.js +128 -0
  65. package/lib/node/session-bound-frontend-connection-service.js.map +1 -0
  66. package/lib/node/socket-channel-forwarder.d.ts +54 -0
  67. package/lib/node/socket-channel-forwarder.d.ts.map +1 -0
  68. package/lib/node/socket-channel-forwarder.js +93 -0
  69. package/lib/node/socket-channel-forwarder.js.map +1 -0
  70. package/lib/testing/stub-inversify-context.js.map +1 -1
  71. package/lib/testing/stub-output-channel.js.map +1 -1
  72. package/package.json +35 -20
  73. package/src/browser/channel-logger.ts +9 -4
  74. package/src/browser/connection-diagnostics-contribution.ts +142 -0
  75. package/src/browser/connection-reporter.ts +121 -0
  76. package/src/browser/editor-disk-sync.ts +236 -0
  77. package/src/browser/hydranium-file-service.ts +56 -0
  78. package/src/browser/index.ts +5 -0
  79. package/src/browser/log-level-preference.ts +11 -0
  80. package/src/browser/memory-diagnostics-contribution.ts +268 -45
  81. package/src/browser/session-aware-connection-source.ts +179 -0
  82. package/src/common/clock.ts +20 -0
  83. package/src/common/connection-resilience-options.ts +24 -0
  84. package/src/common/framed-socket-write-buffer.ts +227 -0
  85. package/src/common/index.ts +15 -0
  86. package/src/node/abstract-socket-forwarding-connection-handler.ts +61 -15
  87. package/src/node/index.ts +2 -0
  88. package/src/node/session-bound-frontend-connection-service.ts +155 -0
  89. package/src/node/socket-channel-forwarder.ts +99 -0
@@ -0,0 +1,155 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { BackendApplicationConfigProvider } from '@theia/core/lib/node/backend-application-config-provider';
11
+ import { SocketWriteBuffer } from '@theia/core/lib/common/messaging/socket-write-buffer';
12
+ import { WebsocketFrontendConnectionService } from '@theia/core/lib/node/messaging/websocket-frontend-connection-service';
13
+ import { injectable, type interfaces } from '@theia/core/shared/inversify';
14
+ import { type ConnectionResilienceOptions } from '../common/connection-resilience-options';
15
+ import {
16
+ CONNECTION_LOG_PREFIX as PREFIX,
17
+ createFramedSocketWriteBuffer,
18
+ supportsConnectionResilience,
19
+ warnConnectionResilienceUnavailable
20
+ } from '../common/framed-socket-write-buffer';
21
+
22
+ /**
23
+ * Socket Theia hands the disconnect handler, read off the base signature rather
24
+ * than imported, which spares a direct `socket.io` dependency carried purely
25
+ * for a parameter type.
26
+ */
27
+ export type FrontendSocket = Parameters<WebsocketFrontendConnectionService['handleSocketDisconnect']>[0];
28
+
29
+ /**
30
+ * Channel Theia hands the disconnect handler, read off the base signature so
31
+ * this package's emitted declarations name only
32
+ * `WebsocketFrontendConnectionService`.
33
+ *
34
+ * `ReconnectableSocketChannel` is not exported by every Theia release in the
35
+ * supported range, so importing it would make those declarations unresolvable
36
+ * for an adopter on one of them — a compile error for a feature they may not
37
+ * even be using.
38
+ */
39
+ export type FrontendChannel = Parameters<WebsocketFrontendConnectionService['handleSocketDisconnect']>[1];
40
+
41
+ /**
42
+ * Ignores a disconnect from a socket that no longer belongs to the frontend.
43
+ *
44
+ * A frontend that loses its network reconnects on a new socket within seconds;
45
+ * the server only notices the old one is gone when its next heartbeat write
46
+ * fails, which is a whole ping interval later. For that stretch both sockets are
47
+ * registered against the same session, and Theia's disconnect handler tears the
48
+ * session off its socket without checking which one just died. The late
49
+ * notification from the abandoned socket therefore cuts the healthy one loose.
50
+ * The frontend sees a connected socket and never retries, so the session is dead
51
+ * until the page is reloaded.
52
+ *
53
+ * Changed here: only the socket the session is currently using may act on a
54
+ * disconnect. The handler is rewritten rather than wrapped because the problem
55
+ * sits inside the listener Theia installs; the rest of the body is Theia's.
56
+ *
57
+ * Re-diff against Theia when the supported range moves: `override` catches a changed signature,
58
+ * not a changed body, so this copy can go stale in silence.
59
+ */
60
+ @injectable()
61
+ export class SessionBoundFrontendConnectionService extends WebsocketFrontendConnectionService {
62
+ /** Socket each frontend's channel is currently bound to, with the time it was bound. */
63
+ protected readonly bindings = new Map<string, { socketId: string; boundAt: number }>();
64
+ /** When a frontend's live socket went away, so the reconnect gap can be reported. */
65
+ protected readonly offlineSince = new Map<string, number>();
66
+
67
+ override handleSocketDisconnect(socket: FrontendSocket, channel: FrontendChannel, frontEndId: string): void {
68
+ const previous = this.bindings.get(frontEndId);
69
+ this.bindings.set(frontEndId, { socketId: socket.id, boundAt: Date.now() });
70
+
71
+ const wentOfflineAt = this.offlineSince.get(frontEndId);
72
+ this.offlineSince.delete(frontEndId);
73
+ const replacing = previous ? `, replacing socket ${previous.socketId}` : '';
74
+ const gap = wentOfflineAt === undefined ? '' : `, after ${Date.now() - wentOfflineAt} ms offline`;
75
+ console.info(`${PREFIX} frontend ${frontEndId} channel bound to socket ${socket.id}${replacing}${gap}`);
76
+
77
+ socket.on('disconnect', reason => {
78
+ const bound = this.bindings.get(frontEndId);
79
+ if (bound?.socketId !== socket.id) {
80
+ // Either a superseded socket being reaped late, or one outliving `closeConnection`, which
81
+ // deletes the binding. Neither owns the channel, so neither may disconnect it, arm a close
82
+ // timeout, or close a connection that is no longer in `connectionsByFrontend`.
83
+ const owner = bound
84
+ ? `socket ${bound.socketId} owns it (bound ${Date.now() - bound.boundAt} ms ago)`
85
+ : 'the connection is already closed';
86
+ console.info(`${PREFIX} ignoring disconnect of stale socket ${socket.id} (frontend ${frontEndId}, ${reason}); ${owner}`);
87
+ return;
88
+ }
89
+
90
+ // From here on: Theia's own handler body, unchanged apart from naming the socket.
91
+ this.offlineSince.set(frontEndId, Date.now());
92
+ console.info(`${PREFIX} socket ${socket.id} (frontend ${frontEndId}) disconnected: ${reason}`);
93
+ channel.disconnect();
94
+ const timeout = this.connectionTimeout();
95
+ const isMarkedForClose = this.channelsMarkedForClose.delete(frontEndId);
96
+ if (timeout === 0 || isMarkedForClose) {
97
+ this.closeConnection(frontEndId, reason);
98
+ } else if (timeout > 0) {
99
+ console.info(`${PREFIX} close timeout for frontend ${frontEndId} set to ${timeout} ms`);
100
+ this.closeTimeouts.set(
101
+ frontEndId,
102
+ setTimeout(() => this.closeConnection(frontEndId, reason), timeout)
103
+ );
104
+ }
105
+ // timeout < 0: never close the back end.
106
+ });
107
+ }
108
+
109
+ protected override closeConnection(frontEndId: string, reason: string): void {
110
+ console.info(`${PREFIX} closing frontend ${frontEndId}: ${reason}`);
111
+ this.bindings.delete(frontEndId);
112
+ this.offlineSince.delete(frontEndId);
113
+ super.closeConnection(frontEndId, reason);
114
+ }
115
+
116
+ /** Mirrors Theia's private `frontendConnectionTimeout`, including `Number('')` resolving to 0.
117
+ * Private there, so the copy is forced; re-diff it with the handler above. */
118
+ protected connectionTimeout(): number {
119
+ const envValue = Number(process.env['FRONTEND_CONNECTION_TIMEOUT']);
120
+ if (!isNaN(envValue)) {
121
+ return envValue;
122
+ }
123
+ return BackendApplicationConfigProvider.get().frontendConnectionTimeout;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Replaces the server pieces that decide how a session survives a reconnect.
129
+ *
130
+ * `FrontendConnectionService` is bound `toService(WebsocketFrontendConnectionService)`,
131
+ * so rebinding the concrete class is enough. The buffer stays transient (one per
132
+ * connection), matching Theia's `bind(SocketWriteBuffer).toSelf()`; the frontend
133
+ * counterpart is bound by `bindConnectionResilience` in a `frontendPreload`
134
+ * module, which is the only point early enough on that side.
135
+ *
136
+ * Does nothing but warn on a Theia too old to expose the buffer binding, so the
137
+ * package keeps one supported range rather than splitting its floor for this
138
+ * feature. Returns whether the hardening was installed, for an adopter that
139
+ * wants to branch on it.
140
+ */
141
+ export function bindConnectionResilience(
142
+ bind: interfaces.Bind,
143
+ isBound: interfaces.IsBound,
144
+ rebind: interfaces.Rebind,
145
+ options: ConnectionResilienceOptions = {}
146
+ ): boolean {
147
+ if (!supportsConnectionResilience(isBound)) {
148
+ warnConnectionResilienceUnavailable('backend');
149
+ return false;
150
+ }
151
+ bind(SessionBoundFrontendConnectionService).toSelf().inSingletonScope();
152
+ rebind(WebsocketFrontendConnectionService).toService(SessionBoundFrontendConnectionService);
153
+ rebind(SocketWriteBuffer).toDynamicValue(() => createFramedSocketWriteBuffer(options.bufferBytes));
154
+ return true;
155
+ }
@@ -0,0 +1,99 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { type Clock, SystemClock } from '@hydranium/protocol';
11
+ import { type Channel, Disposable, DisposableCollection, type MessageProvider } from '@theia/core';
12
+ import type * as net from 'node:net';
13
+ import {
14
+ createMessageConnection,
15
+ type Message,
16
+ type MessageConnection,
17
+ SocketMessageReader,
18
+ SocketMessageWriter
19
+ } from 'vscode-jsonrpc/node';
20
+
21
+ /**
22
+ * Relays JSON-RPC messages between a Theia browser-frontend {@link Channel} and
23
+ * a server's TCP socket — the backend half of a head's transport. The server
24
+ * speaks vscode-jsonrpc (Content-Length framed) on the socket; the frontend
25
+ * speaks the same protocol over the channel. This forwarder decodes each side
26
+ * and re-emits on the other.
27
+ *
28
+ * Behaves as `@eclipse-glsp/theia-integration`'s `SocketConnectionForwarder`
29
+ * does, and both heads use it, except that when the channel closes, the writes
30
+ * still queued go out before the socket ends. A page going away sends its last
31
+ * messages and closes its channel in the same tick, and the writer takes
32
+ * several turns per message, so destroying the socket on the close loses them.
33
+ */
34
+ export class SocketChannelForwarder implements Disposable {
35
+ protected readonly toDispose = new DisposableCollection();
36
+ /** The last write to the socket; the writer runs its writes one at a time, so this settles last. */
37
+ protected lastWrite: Promise<void> = Promise.resolve();
38
+ /**
39
+ * How long {@link endSocket} waits for the queued writes before it destroys
40
+ * the socket anyway. Without a bound, a server that stops reading holds the
41
+ * socket open for good, and with it the server's end of the connection.
42
+ */
43
+ protected readonly flushTimeoutMs: number = 10_000;
44
+
45
+ constructor(
46
+ protected readonly channel: Channel,
47
+ protected readonly socket: net.Socket,
48
+ /** Times {@link flushTimeoutMs}. */
49
+ protected readonly clock: Clock = new SystemClock()
50
+ ) {
51
+ const reader = new SocketMessageReader(socket);
52
+ const writer = new SocketMessageWriter(socket);
53
+ const connection = createMessageConnection(reader, writer);
54
+ // Nothing here destroys the socket directly. `SocketMessageWriter.dispose()`
55
+ // destroys it itself, which covers both `dispose` and `endSocket`; and
56
+ // `connection.onClose` fires only from the reader's or writer's own close,
57
+ // which for a socket means the socket has already gone — so a destroy
58
+ // handler there is downstream of the effect it would be trying to cause.
59
+ this.toDispose.pushAll([
60
+ reader.listen(message => this.writeToChannel(message)),
61
+ channel.onMessage(provider => {
62
+ // A failed write means the socket is gone, which its own close reports.
63
+ this.lastWrite = writer.write(this.decodeChannelMessage(provider)).catch(() => undefined);
64
+ }),
65
+ channel.onClose(() => void this.endSocket(connection)),
66
+ connection.onClose(() => channel.close()),
67
+ Disposable.create(() => {
68
+ channel.close();
69
+ connection.dispose();
70
+ })
71
+ ]);
72
+ }
73
+
74
+ /**
75
+ * Dispose `connection`, which destroys the socket, once the writes queued
76
+ * before the channel closed are out, or {@link flushTimeoutMs} has passed. A
77
+ * write has settled once the socket handed its bytes to the OS, and
78
+ * destroying the socket then loses nothing.
79
+ */
80
+ protected async endSocket(connection: MessageConnection): Promise<void> {
81
+ await this.clock.raceTimer(this.lastWrite, this.flushTimeoutMs);
82
+ connection.dispose();
83
+ }
84
+
85
+ protected decodeChannelMessage(provider: MessageProvider): Message {
86
+ const buffer = provider().readBytes();
87
+ return JSON.parse(new TextDecoder().decode(buffer)) as Message;
88
+ }
89
+
90
+ protected writeToChannel(message: Message): void {
91
+ const writeBuffer = this.channel.getWriteBuffer();
92
+ writeBuffer.writeBytes(new TextEncoder().encode(JSON.stringify(message)));
93
+ writeBuffer.commit();
94
+ }
95
+
96
+ dispose(): void {
97
+ this.toDispose.dispose();
98
+ }
99
+ }