@hydranium/client-theia 1.0.0-next.123 → 1.0.0-next.127

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 (47) hide show
  1. package/README.md +33 -6
  2. package/lib/browser/channel-logger.d.ts +4 -3
  3. package/lib/browser/channel-logger.d.ts.map +1 -1
  4. package/lib/browser/channel-logger.js +9 -4
  5. package/lib/browser/channel-logger.js.map +1 -1
  6. package/lib/browser/editor-disk-sync.d.ts +133 -0
  7. package/lib/browser/editor-disk-sync.d.ts.map +1 -0
  8. package/lib/browser/editor-disk-sync.js +232 -0
  9. package/lib/browser/editor-disk-sync.js.map +1 -0
  10. package/lib/browser/hydranium-file-service.d.ts +44 -0
  11. package/lib/browser/hydranium-file-service.d.ts.map +1 -0
  12. package/lib/browser/hydranium-file-service.js +61 -0
  13. package/lib/browser/hydranium-file-service.js.map +1 -0
  14. package/lib/browser/index.d.ts +2 -0
  15. package/lib/browser/index.d.ts.map +1 -1
  16. package/lib/browser/index.js +2 -0
  17. package/lib/browser/index.js.map +1 -1
  18. package/lib/common/clock.d.ts +19 -0
  19. package/lib/common/clock.d.ts.map +1 -0
  20. package/lib/common/clock.js +13 -0
  21. package/lib/common/clock.js.map +1 -0
  22. package/lib/common/index.d.ts +1 -0
  23. package/lib/common/index.d.ts.map +1 -1
  24. package/lib/common/index.js +4 -3
  25. package/lib/common/index.js.map +1 -1
  26. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts +8 -7
  27. package/lib/node/abstract-socket-forwarding-connection-handler.d.ts.map +1 -1
  28. package/lib/node/abstract-socket-forwarding-connection-handler.js +22 -6
  29. package/lib/node/abstract-socket-forwarding-connection-handler.js.map +1 -1
  30. package/lib/node/index.d.ts +1 -0
  31. package/lib/node/index.d.ts.map +1 -1
  32. package/lib/node/index.js +1 -0
  33. package/lib/node/index.js.map +1 -1
  34. package/lib/node/socket-channel-forwarder.d.ts +54 -0
  35. package/lib/node/socket-channel-forwarder.d.ts.map +1 -0
  36. package/lib/node/socket-channel-forwarder.js +93 -0
  37. package/lib/node/socket-channel-forwarder.js.map +1 -0
  38. package/package.json +12 -6
  39. package/src/browser/channel-logger.ts +9 -4
  40. package/src/browser/editor-disk-sync.ts +236 -0
  41. package/src/browser/hydranium-file-service.ts +56 -0
  42. package/src/browser/index.ts +2 -0
  43. package/src/common/clock.ts +20 -0
  44. package/src/common/index.ts +4 -3
  45. package/src/node/abstract-socket-forwarding-connection-handler.ts +13 -8
  46. package/src/node/index.ts +1 -0
  47. package/src/node/socket-channel-forwarder.ts +99 -0
@@ -0,0 +1,236 @@
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 { SystemClock, TIMED_OUT } from '@hydranium/protocol';
11
+ import type { FrontendApplicationContribution } from '@theia/core/lib/browser';
12
+ import { ILogger } from '@theia/core/lib/common/logger';
13
+ import URI from '@theia/core/lib/common/uri';
14
+ import { inject, injectable, optional } from '@theia/core/shared/inversify';
15
+ import { EditorManager } from '@theia/editor/lib/browser/editor-manager';
16
+ import type { EditorWidget } from '@theia/editor/lib/browser/editor-widget';
17
+ import type { FileResourceVersion } from '@theia/filesystem/lib/browser/file-resource';
18
+ import { FileService, type TextFileContent } from '@theia/filesystem/lib/browser/file-service';
19
+ import { Clock } from '../common/clock';
20
+
21
+ /**
22
+ * The members of Theia's Monaco editor model {@link EditorDiskSync} reads and
23
+ * resets. `contentChanges`, `resourceVersion` and `run` are `protected` there,
24
+ * so {@link isResyncableEditorDocument} checks for them at runtime: a Theia
25
+ * that renames them yields a document it refuses, and the sync then leaves it
26
+ * alone.
27
+ */
28
+ export interface ResyncableEditorDocument {
29
+ readonly uri: string;
30
+ readonly dirty: boolean;
31
+ getText(): string;
32
+ revert(options: { soft: boolean }): Promise<void>;
33
+ /** The edits the next save applies to the file, in place of the whole text. */
34
+ readonly contentChanges: unknown[];
35
+ /** The file version the next save expects to find on disk. */
36
+ resourceVersion: FileResourceVersion | undefined;
37
+ /** Queue `operation` behind the model's saves and syncs in progress. */
38
+ run(operation: () => Promise<void>): Promise<void>;
39
+ /** Awaited by each save before it takes the pending edits. */
40
+ onModelWillSaveModel(listener: () => Promise<void>): { dispose(): void };
41
+ }
42
+
43
+ /** Whether `document` carries the members of {@link ResyncableEditorDocument}. */
44
+ export function isResyncableEditorDocument(document: object): document is ResyncableEditorDocument {
45
+ return (
46
+ 'uri' in document &&
47
+ typeof document.uri === 'string' &&
48
+ 'dirty' in document &&
49
+ 'getText' in document &&
50
+ typeof document.getText === 'function' &&
51
+ 'revert' in document &&
52
+ typeof document.revert === 'function' &&
53
+ 'contentChanges' in document &&
54
+ Array.isArray(document.contentChanges) &&
55
+ 'resourceVersion' in document &&
56
+ 'run' in document &&
57
+ typeof document.run === 'function' &&
58
+ 'onModelWillSaveModel' in document &&
59
+ typeof document.onModelWillSaveModel === 'function'
60
+ );
61
+ }
62
+
63
+ /**
64
+ * Keeps a dirty editor's save from applying edits its file already holds, as
65
+ * the file does once the server saves a document the editor shows unsaved.
66
+ *
67
+ * Theia keeps such an editor dirty, and its next save corrupts the file: the
68
+ * save applies the editor's pending edits to the file rather than writing the
69
+ * whole text, and the file already holds them, so each is applied twice.
70
+ * Theia's check that the file has not changed since the editor read it passes
71
+ * whenever the new file has the old one's size, so no conflict is reported. A
72
+ * revert alone keeps the pending edits.
73
+ *
74
+ * Before each save of the editor it reads the file. When the file holds the
75
+ * text the buffer held as the save began, it drops the edits pending then and
76
+ * has the save expect the file's version, so the save writes only the edits
77
+ * made after that point, a save participant's included, onto the file as it
78
+ * is. The save is not cancelled: it completes and is reported as saved. Save
79
+ * All relies on this check, since it saves a diagram and then an editor on the
80
+ * same file at once, before the file watcher has reported the diagram's write.
81
+ * The buffer is taken when the save calls its will-save listeners. Theia runs
82
+ * its save participants one after another, each behind an await, and its
83
+ * first one awaits before it edits, so none has changed the buffer by then. A
84
+ * participant ordered ahead of it that edits before its first await makes the
85
+ * file and the taken text differ, and the save applies every edit again.
86
+ *
87
+ * On each change the file watcher reports, it marks the editor clean when the
88
+ * file holds exactly its buffer. The file is compared with the buffer after
89
+ * it has been read, and the editor is marked in the same step, so a keystroke
90
+ * made while the file was read leaves the editor dirty. This sync waits behind
91
+ * a save in flight: that save drops the edits it sent from the pending ones
92
+ * when it finishes, and a sync before then would have it drop the edits typed
93
+ * meanwhile.
94
+ *
95
+ * An editor whose file holds neither text is left to Theia's own save,
96
+ * same-size gap included, and so is one whose file cannot be read within
97
+ * {@link readTimeoutMs}, or whose check throws.
98
+ *
99
+ * The adopter binds it as a `FrontendApplicationContribution`.
100
+ */
101
+ @injectable()
102
+ export class EditorDiskSync implements FrontendApplicationContribution {
103
+ @inject(FileService) protected readonly fileService!: FileService;
104
+ @inject(EditorManager) protected readonly editorManager!: EditorManager;
105
+ @inject(ILogger) protected readonly logger!: ILogger;
106
+ /** Times {@link readTimeoutMs}: the container's {@link Clock}, or a `SystemClock`. */
107
+ @inject(Clock) @optional() protected readonly clock: Clock = new SystemClock();
108
+ /** Whether an editor's document has failed {@link isResyncableEditorDocument}; warned of once. */
109
+ protected warnedUnsyncable = false;
110
+ /**
111
+ * How long a check waits for the file. The editor's save, and every later
112
+ * save and sync of that editor, waits for the check.
113
+ */
114
+ protected readTimeoutMs = 1_000;
115
+
116
+ onStart(): void {
117
+ this.fileService.onDidFilesChange(event => {
118
+ for (const change of event.changes) {
119
+ this.checkFile(change.resource);
120
+ }
121
+ });
122
+ this.editorManager.onCreated(widget => this.guardSaves(widget));
123
+ for (const widget of this.editorManager.all) {
124
+ this.guardSaves(widget);
125
+ }
126
+ }
127
+
128
+ /** Check `widget`'s document before each of its saves, for as long as the widget lives. */
129
+ protected guardSaves(widget: EditorWidget): void {
130
+ const document = this.resyncable(widget.editor.document);
131
+ if (document) {
132
+ const registration = document.onModelWillSaveModel(() => this.isolate(() => this.dropChangesOnDisk(document)));
133
+ widget.onDidDispose(() => registration.dispose());
134
+ }
135
+ }
136
+
137
+ /** Check each dirty document an editor shows on `uri`, behind that document's save in flight. */
138
+ protected checkFile(uri: URI): void {
139
+ for (const document of this.dirtyDocuments(uri)) {
140
+ void document.run(() => this.isolate(() => this.syncIfOnDisk(document)));
141
+ }
142
+ }
143
+
144
+ /** Read the file of `document` if it is dirty, and sync it if the file holds its buffer. */
145
+ protected async syncIfOnDisk(document: ResyncableEditorDocument): Promise<void> {
146
+ if (!document.dirty) {
147
+ return;
148
+ }
149
+ const content = await this.readFile(document);
150
+ if (content && document.getText() === content.value) {
151
+ this.syncFromDisk(document, { etag: content.etag, mtime: content.mtime, encoding: content.encoding });
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Before a save of `document`, drop the edits pending now if its file holds
157
+ * the buffer as it is now, and take the file's version. The buffer and the
158
+ * count are taken before the first await, while the save is still calling
159
+ * its will-save listeners; an edit made after that stays pending, and the
160
+ * save writes it onto the file.
161
+ */
162
+ protected async dropChangesOnDisk(document: ResyncableEditorDocument): Promise<void> {
163
+ if (!document.dirty) {
164
+ return;
165
+ }
166
+ const text = document.getText();
167
+ const pending = document.contentChanges.length;
168
+ const content = await this.readFile(document);
169
+ if (content?.value === text) {
170
+ document.contentChanges.splice(0, pending);
171
+ document.resourceVersion = { etag: content.etag, mtime: content.mtime, encoding: content.encoding };
172
+ }
173
+ }
174
+
175
+ /**
176
+ * The file of `document`, or `undefined` when it is gone, cannot be read, or
177
+ * is not read within {@link readTimeoutMs}.
178
+ */
179
+ protected async readFile(document: ResyncableEditorDocument): Promise<TextFileContent | undefined> {
180
+ const read = this.fileService.read(new URI(document.uri)).catch(() => undefined);
181
+ const content = await this.clock.raceTimer(read, this.readTimeoutMs);
182
+ return content === TIMED_OUT ? undefined : content;
183
+ }
184
+
185
+ /**
186
+ * Run `check`, and log its failure rather than pass it on. A will-save
187
+ * listener that rejects makes Theia drop the save without writing, and a
188
+ * sync that rejects goes unhandled.
189
+ */
190
+ protected async isolate(check: () => Promise<void>): Promise<void> {
191
+ try {
192
+ await check();
193
+ } catch (err: unknown) {
194
+ void this.logger.error('EditorDiskSync: checking an editor against its file failed; the editor is left as it is.', err);
195
+ }
196
+ }
197
+
198
+ /** The dirty documents open in an editor on `uri`, each once however many editors show it. */
199
+ protected dirtyDocuments(uri: URI): ResyncableEditorDocument[] {
200
+ const target = uri.toString();
201
+ const documents = new Set<ResyncableEditorDocument>();
202
+ for (const widget of this.editorManager.all) {
203
+ const document = this.resyncable(widget.editor.document);
204
+ if (document && document.uri === target && document.dirty) {
205
+ documents.add(document);
206
+ }
207
+ }
208
+ return [...documents];
209
+ }
210
+
211
+ /** `document` if it carries the members the sync resets; otherwise `undefined`, warned of once. */
212
+ protected resyncable(document: object): ResyncableEditorDocument | undefined {
213
+ if (isResyncableEditorDocument(document)) {
214
+ return document;
215
+ }
216
+ if (!this.warnedUnsyncable) {
217
+ this.warnedUnsyncable = true;
218
+ void this.logger.warn(
219
+ 'EditorDiskSync: an editor document lacks the Monaco model members the sync resets, so such editors are not synced with their files.'
220
+ );
221
+ }
222
+ return undefined;
223
+ }
224
+
225
+ /**
226
+ * Take `version` as the file `document` was last saved to, with nothing
227
+ * pending, and mark it clean. Synchronous throughout: a soft revert only
228
+ * marks the document clean, and reads nothing. The revert also cancels a
229
+ * save queued behind the sync, which would have written the same text.
230
+ */
231
+ protected syncFromDisk(document: ResyncableEditorDocument, version: FileResourceVersion): void {
232
+ document.contentChanges.splice(0, document.contentChanges.length);
233
+ document.resourceVersion = version;
234
+ void document.revert({ soft: true });
235
+ }
236
+ }
@@ -0,0 +1,56 @@
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 type URI from '@theia/core/lib/common/uri';
11
+ import { injectable } from '@theia/core/shared/inversify';
12
+ import { FileService, type UpdateTextFileOptions } from '@theia/filesystem/lib/browser/file-service';
13
+ import { ETAG_DISABLED } from '@theia/filesystem/lib/common/files';
14
+
15
+ /**
16
+ * Theia's `FileService`, refusing an incremental save once the file has
17
+ * changed since the editor read it.
18
+ *
19
+ * Theia's own check, which `write` and `update` share, passes a file whose
20
+ * mtime moved on when its size still matches the etag the editor read. That
21
+ * is safe for `write`, which replaces the file with the whole text, but
22
+ * `update` applies the editor's pending edits to the file as it is, so after a
23
+ * same-size change, the server saving those very edits included, it applies
24
+ * them a second time. Here `update` hands that check the etag with a `!`
25
+ * appended, which no file's etag can match: Theia writes an etag as the mtime
26
+ * in base 29 followed by the size in base 31, digits and lower-case letters
27
+ * only. An advanced mtime is then enough for Theia to refuse with its
28
+ * `FILE_MODIFIED_SINCE`. The editor's save then falls back to `write` with the
29
+ * whole text, which Theia checks as before: it writes when the size is
30
+ * unchanged, and asks the user otherwise. A same-size change by another
31
+ * process is therefore overwritten by that write rather than merged with the
32
+ * editor's edits. `write` is left as it is.
33
+ *
34
+ * It is the safety net behind `EditorDiskSync`, which acts only when the
35
+ * file holds the editor's buffer: a file holding some of the edits, as when a
36
+ * save participant ordered ahead of Theia's first one edits before its first
37
+ * await, is left to this check.
38
+ *
39
+ * A write within the file system's mtime resolution of the read goes unseen,
40
+ * as it does for Theia's own check. A file whose mtime moves while its text
41
+ * stays the same costs a whole-text write rather than the edits.
42
+ *
43
+ * The adopter binds it with `rebind(FileService).to(HydraniumFileService).inSingletonScope()`.
44
+ */
45
+ @injectable()
46
+ export class HydraniumFileService extends FileService {
47
+ override update(
48
+ resource: URI,
49
+ changes: Parameters<FileService['update']>[1],
50
+ options: UpdateTextFileOptions
51
+ ): ReturnType<FileService['update']> {
52
+ const strict =
53
+ typeof options.etag === 'string' && options.etag !== ETAG_DISABLED ? { ...options, etag: `${options.etag}!` } : options;
54
+ return super.update(resource, changes, strict);
55
+ }
56
+ }
@@ -14,3 +14,5 @@ export * from './browser-capture';
14
14
  export * from './memory-diagnostics-contribution';
15
15
  export * from './session-aware-connection-source';
16
16
  export * from './connection-diagnostics-contribution';
17
+ export * from './editor-disk-sync';
18
+ export * from './hydranium-file-service';
@@ -0,0 +1,20 @@
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 type { Clock as ProtocolClock } from '@hydranium/protocol';
11
+
12
+ /**
13
+ * The protocol's `Clock`, as a Theia container binds it: type and injection
14
+ * token under one identifier, as Theia declares its own. The framework's
15
+ * frontend and backend classes that time or bound something inject it as
16
+ * optional, and use a `SystemClock` when the container binds none, so a
17
+ * container can supply another clock.
18
+ */
19
+ export type Clock = ProtocolClock;
20
+ export const Clock = Symbol('Clock');
@@ -7,8 +7,9 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
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.
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
13
  export * from './framed-socket-write-buffer';
14
14
  export * from './connection-resilience-options';
15
+ 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
 
@@ -190,7 +193,9 @@ export abstract class AbstractSocketForwardingConnectionHandler implements Conne
190
193
  * relay both ways. Called once, after the socket is created and the
191
194
  * pre-forward buffer is about to be replayed.
192
195
  */
193
- protected abstract forwardToSocketConnection(clientChannel: Channel, socket: net.Socket): Disposable;
196
+ protected forwardToSocketConnection(clientChannel: Channel, socket: net.Socket): Disposable {
197
+ return new SocketChannelForwarder(clientChannel, socket, this.clock);
198
+ }
194
199
 
195
200
  /**
196
201
  * Re-fire pre-forward buffered `MessageProvider`s on the channel's internal
package/src/node/index.ts CHANGED
@@ -9,3 +9,4 @@
9
9
 
10
10
  export * from './abstract-socket-forwarding-connection-handler';
11
11
  export * from './session-bound-frontend-connection-service';
12
+ export * from './socket-channel-forwarder';
@@ -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
+ }