@celljs/rpc 4.34.0 → 4.36.0

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 (90) hide show
  1. package/README.md +6 -0
  2. package/README.zh-cn.md +6 -0
  3. package/esm/common/protocol/json-rpc.d.ts +2 -0
  4. package/esm/common/protocol/json-rpc.js +2 -0
  5. package/esm/common/protocol/json-rpc.js.map +1 -1
  6. package/esm/common/transport/index.d.ts +1 -0
  7. package/esm/common/transport/index.js +1 -0
  8. package/esm/common/transport/index.js.map +1 -1
  9. package/esm/common/transport/rpc-websocket-client.d.ts +139 -0
  10. package/esm/common/transport/rpc-websocket-client.js +404 -0
  11. package/esm/common/transport/rpc-websocket-client.js.map +1 -0
  12. package/esm/common/transport/websocket-transport.d.ts +10 -19
  13. package/esm/common/transport/websocket-transport.js +50 -121
  14. package/esm/common/transport/websocket-transport.js.map +1 -1
  15. package/esm/node/connection/index.d.ts +1 -0
  16. package/esm/node/connection/index.js +1 -0
  17. package/esm/node/connection/index.js.map +1 -1
  18. package/esm/node/connection/rpc-push-channel.d.ts +43 -0
  19. package/esm/node/connection/rpc-push-channel.js +83 -0
  20. package/esm/node/connection/rpc-push-channel.js.map +1 -0
  21. package/esm/node/websocket/index.d.ts +1 -0
  22. package/esm/node/websocket/index.js +1 -0
  23. package/esm/node/websocket/index.js.map +1 -1
  24. package/esm/node/websocket/rpc-websocket-server.d.ts +1 -2
  25. package/esm/node/websocket/rpc-websocket-server.js +10 -19
  26. package/esm/node/websocket/rpc-websocket-server.js.map +1 -1
  27. package/esm/node/websocket/websocket-upgrades.d.ts +46 -0
  28. package/esm/node/websocket/websocket-upgrades.js +76 -0
  29. package/esm/node/websocket/websocket-upgrades.js.map +1 -0
  30. package/lib/common/protocol/json-rpc.d.ts +2 -0
  31. package/lib/common/protocol/json-rpc.d.ts.map +1 -1
  32. package/lib/common/protocol/json-rpc.js +2 -0
  33. package/lib/common/protocol/json-rpc.js.map +1 -1
  34. package/lib/common/transport/index.d.ts +1 -0
  35. package/lib/common/transport/index.d.ts.map +1 -1
  36. package/lib/common/transport/index.js +1 -0
  37. package/lib/common/transport/index.js.map +1 -1
  38. package/lib/common/transport/rpc-websocket-client.d.ts +140 -0
  39. package/lib/common/transport/rpc-websocket-client.d.ts.map +1 -0
  40. package/lib/common/transport/rpc-websocket-client.js +408 -0
  41. package/lib/common/transport/rpc-websocket-client.js.map +1 -0
  42. package/lib/common/transport/rpc-websocket-client.spec.d.ts +2 -0
  43. package/lib/common/transport/rpc-websocket-client.spec.d.ts.map +1 -0
  44. package/lib/common/transport/rpc-websocket-client.spec.js +162 -0
  45. package/lib/common/transport/rpc-websocket-client.spec.js.map +1 -0
  46. package/lib/common/transport/websocket-transport.d.ts +10 -19
  47. package/lib/common/transport/websocket-transport.d.ts.map +1 -1
  48. package/lib/common/transport/websocket-transport.js +50 -121
  49. package/lib/common/transport/websocket-transport.js.map +1 -1
  50. package/lib/node/connection/index.d.ts +1 -0
  51. package/lib/node/connection/index.d.ts.map +1 -1
  52. package/lib/node/connection/index.js +1 -0
  53. package/lib/node/connection/index.js.map +1 -1
  54. package/lib/node/connection/rpc-push-channel.d.ts +44 -0
  55. package/lib/node/connection/rpc-push-channel.d.ts.map +1 -0
  56. package/lib/node/connection/rpc-push-channel.js +87 -0
  57. package/lib/node/connection/rpc-push-channel.js.map +1 -0
  58. package/lib/node/connection/rpc-push-channel.spec.d.ts +2 -0
  59. package/lib/node/connection/rpc-push-channel.spec.d.ts.map +1 -0
  60. package/lib/node/connection/rpc-push-channel.spec.js +59 -0
  61. package/lib/node/connection/rpc-push-channel.spec.js.map +1 -0
  62. package/lib/node/websocket/index.d.ts +1 -0
  63. package/lib/node/websocket/index.d.ts.map +1 -1
  64. package/lib/node/websocket/index.js +1 -0
  65. package/lib/node/websocket/index.js.map +1 -1
  66. package/lib/node/websocket/rpc-websocket-server.d.ts +1 -2
  67. package/lib/node/websocket/rpc-websocket-server.d.ts.map +1 -1
  68. package/lib/node/websocket/rpc-websocket-server.js +10 -19
  69. package/lib/node/websocket/rpc-websocket-server.js.map +1 -1
  70. package/lib/node/websocket/websocket-upgrades.d.ts +47 -0
  71. package/lib/node/websocket/websocket-upgrades.d.ts.map +1 -0
  72. package/lib/node/websocket/websocket-upgrades.js +80 -0
  73. package/lib/node/websocket/websocket-upgrades.js.map +1 -0
  74. package/lib/node/websocket/websocket-upgrades.spec.d.ts +2 -0
  75. package/lib/node/websocket/websocket-upgrades.spec.d.ts.map +1 -0
  76. package/lib/node/websocket/websocket-upgrades.spec.js +64 -0
  77. package/lib/node/websocket/websocket-upgrades.spec.js.map +1 -0
  78. package/package.json +4 -4
  79. package/src/common/protocol/json-rpc.ts +2 -0
  80. package/src/common/transport/index.ts +1 -0
  81. package/src/common/transport/rpc-websocket-client.spec.ts +164 -0
  82. package/src/common/transport/rpc-websocket-client.ts +476 -0
  83. package/src/common/transport/websocket-transport.ts +51 -126
  84. package/src/node/connection/index.ts +3 -1
  85. package/src/node/connection/rpc-push-channel.spec.ts +61 -0
  86. package/src/node/connection/rpc-push-channel.ts +98 -0
  87. package/src/node/websocket/index.ts +1 -0
  88. package/src/node/websocket/rpc-websocket-server.ts +5 -16
  89. package/src/node/websocket/websocket-upgrades.spec.ts +64 -0
  90. package/src/node/websocket/websocket-upgrades.ts +95 -0
@@ -1,4 +1,5 @@
1
1
  import { JsonRpc } from '../protocol';
2
+ import { RpcWebSocketClient } from './rpc-websocket-client';
2
3
  import { RpcTransport } from './transport-protocol';
3
4
 
4
5
  export interface WebSocketTransportOptions {
@@ -18,30 +19,23 @@ export interface WebSocketTransportOptions {
18
19
  connectTimeout?: number;
19
20
  }
20
21
 
21
- interface Pending {
22
- resolve(response: JsonRpc.Response): void;
23
- timer: ReturnType<typeof setTimeout>;
24
- }
25
-
26
22
  /**
27
23
  * JSON-RPC over one WebSocket connection for all services (methods are `<service>/<method>`), which
28
- * the server can call back over (`@RpcClient`). While no connection can be opened (no `WebSocket` in
29
- * this runtime, a server or platform without WebSocket support) calls go to the fallback transport.
30
- * A connection that closes answers its pending calls with {@link JsonRpc.CONNECTION_CLOSED}: they are
31
- * not sent again, since they may have run.
24
+ * the server can call back over (`@RpcClient`): an {@link RpcWebSocketClient}. While no connection can
25
+ * be opened (no `WebSocket` in this runtime, a server or platform without WebSocket support) calls go
26
+ * to the fallback transport. A connection that closes answers its pending calls with
27
+ * {@link JsonRpc.CONNECTION_CLOSED}: they are not sent again, since they may have run.
32
28
  */
33
29
  export class WebSocketTransport implements RpcTransport {
34
30
 
35
31
  static readonly MAX_RECONNECT_DELAY = 30000;
36
32
 
37
- protected socket?: WebSocket;
38
- protected opening?: Promise<WebSocket | undefined>;
39
- protected readonly pending = new Map<JsonRpc.Id, Pending>();
40
- protected seq = 0;
33
+ protected client?: RpcWebSocketClient;
34
+ protected resolving?: Promise<RpcWebSocketClient>;
41
35
  protected retryAt = 0;
42
36
  protected delay: number;
43
- protected reconnectTimer?: ReturnType<typeof setTimeout>;
44
37
  protected closed = false;
38
+ protected retryTimer?: ReturnType<typeof setTimeout>;
45
39
 
46
40
  constructor(protected readonly options: WebSocketTransportOptions) {
47
41
  this.delay = options.reconnectDelay ?? 1000;
@@ -49,140 +43,71 @@ export class WebSocketTransport implements RpcTransport {
49
43
 
50
44
  /** Whether calls go over a WebSocket connection now. */
51
45
  get connected(): boolean {
52
- return this.socket?.readyState === 1;
46
+ return this.client?.connected ?? false;
53
47
  }
54
48
 
55
49
  async call(service: string, method: string, params: unknown[]): Promise<JsonRpc.Response> {
56
- const socket = await this.connect();
57
- if (!socket) {
50
+ const client = await this.connect();
51
+ if (!client) {
58
52
  return this.options.fallback.call(service, method, params);
59
53
  }
60
- const id = ++this.seq;
61
- return new Promise<JsonRpc.Response>(resolve => {
62
- const timeout = this.options.callTimeout ?? 60000;
63
- const timer = setTimeout(() => {
64
- this.pending.delete(id);
65
- resolve(JsonRpc.error(id, JsonRpc.TIMEOUT, `No response to ${service}.${method} within ${timeout} ms.`));
66
- }, timeout);
67
- this.pending.set(id, { resolve, timer });
68
- socket.send(JSON.stringify(JsonRpc.request(id, `${service}/${method}`, params)));
69
- });
54
+ return client.call(`${service}/${method}`, params);
70
55
  }
71
56
 
72
57
  /** Opens the connection (calls open it when needed); undefined while none can be made. */
73
- connect(): Promise<WebSocket | undefined> {
58
+ async connect(): Promise<RpcWebSocketClient | undefined> {
74
59
  if (this.closed || typeof WebSocket === 'undefined') {
75
- return Promise.resolve(undefined);
60
+ return undefined;
76
61
  }
77
- if (this.socket && this.socket.readyState === 1) {
78
- return Promise.resolve(this.socket);
79
- }
80
- if (this.opening) {
81
- return this.opening;
62
+ const client = await (this.resolving ??= this.create());
63
+ if (client.connected) {
64
+ return client;
82
65
  }
83
66
  if (Date.now() < this.retryAt) {
84
- return Promise.resolve(undefined);
67
+ return undefined;
68
+ }
69
+ try {
70
+ await client.connect();
71
+ this.delay = this.options.reconnectDelay ?? 1000;
72
+ return client;
73
+ } catch {
74
+ // No WebSocket endpoint (yet): HTTP for a while, then try again; on its own when the server pushes.
75
+ this.retryAt = Date.now() + this.delay;
76
+ this.delay = Math.min(this.delay * 2, WebSocketTransport.MAX_RECONNECT_DELAY);
77
+ if (this.options.keepAlive) {
78
+ clearTimeout(this.retryTimer);
79
+ this.retryTimer = setTimeout(() => void this.connect(), this.retryAt - Date.now());
80
+ }
81
+ return undefined;
85
82
  }
86
- this.opening = this.open().finally(() => {
87
- this.opening = undefined;
88
- });
89
- return this.opening;
90
83
  }
91
84
 
92
85
  /** Closes the connection for good: later calls use the fallback. */
93
86
  close(): void {
94
87
  this.closed = true;
95
- clearTimeout(this.reconnectTimer);
96
- this.socket?.close(1000);
88
+ clearTimeout(this.retryTimer);
89
+ this.client?.close();
97
90
  }
98
91
 
99
- protected async open(): Promise<WebSocket | undefined> {
92
+ protected async create(): Promise<RpcWebSocketClient> {
100
93
  const url = await this.options.url();
101
- return new Promise<WebSocket | undefined>(resolve => {
102
- let opened = false;
103
- let failed = false;
104
- const socket = new WebSocket(url);
105
- // No WebSocket endpoint (yet): HTTP for a while, then try again.
106
- const fail = () => {
107
- clearTimeout(timer);
108
- if (failed) {
109
- return;
110
- }
111
- failed = true;
112
- this.retryAt = Date.now() + this.delay;
113
- this.delay = Math.min(this.delay * 2, WebSocketTransport.MAX_RECONNECT_DELAY);
114
- resolve(undefined);
115
- this.scheduleReconnect();
116
- };
117
- // A server that never answers the upgrade (Bun < 1.4 behind node:http) must not hold the calls;
118
- // nor a client whose close() of a connecting socket does not fire close (the WebSocket of Node.js 22).
119
- const timer = setTimeout(() => {
120
- socket.close();
121
- fail();
122
- }, this.options.connectTimeout ?? 5000);
123
- socket.onopen = () => {
124
- if (failed) {
125
- socket.close(1000);
126
- return;
127
- }
128
- clearTimeout(timer);
129
- opened = true;
130
- this.socket = socket;
131
- this.delay = this.options.reconnectDelay ?? 1000;
132
- resolve(socket);
133
- };
134
- socket.onmessage = event => this.receive(socket, event.data);
135
- socket.onerror = () => undefined;
136
- socket.onclose = () => {
137
- if (!opened) {
138
- fail();
139
- return;
140
- }
141
- this.socket = undefined;
142
- this.failPending();
143
- this.scheduleReconnect();
144
- };
94
+ this.client = new RpcWebSocketClient({
95
+ createSocket: () => new WebSocket(url),
96
+ reconnect: !!this.options.keepAlive,
97
+ reconnectDelayMs: this.options.reconnectDelay ?? 1000,
98
+ maxReconnectDelayMs: WebSocketTransport.MAX_RECONNECT_DELAY,
99
+ // A server that never answers the upgrade (Bun < 1.4 behind node:http) must not hold the calls.
100
+ openTimeoutMs: this.options.connectTimeout ?? 5000,
101
+ waitForOpenMs: 0,
102
+ stallMs: 0,
103
+ callTimeoutMs: this.options.callTimeout ?? 60000,
104
+ handle: request =>
105
+ this.options.handle?.(request) ??
106
+ Promise.resolve(JsonRpc.error(request.id ?? null, JsonRpc.METHOD_NOT_FOUND, `No @RpcClient for ${request.method}.`)),
145
107
  });
146
- }
147
-
148
- protected scheduleReconnect(): void {
149
- if (!this.options.keepAlive || this.closed) {
150
- return;
151
- }
152
- clearTimeout(this.reconnectTimer);
153
- this.reconnectTimer = setTimeout(() => void this.connect(), Math.max(this.retryAt - Date.now(), this.delay));
154
- }
155
-
156
- protected failPending(): void {
157
- for (const [id, pending] of this.pending) {
158
- clearTimeout(pending.timer);
159
- pending.resolve(JsonRpc.error(id, JsonRpc.CONNECTION_CLOSED, 'The WebSocket connection closed before the response arrived; the call may or may not have run.'));
160
- }
161
- this.pending.clear();
162
- }
163
-
164
- protected receive(socket: WebSocket, data: unknown): void {
165
- let message: unknown;
166
- try {
167
- message = JSON.parse(String(data));
168
- } catch {
169
- return;
170
- }
171
- if (JsonRpc.isResponse(message)) {
172
- const pending = message.id === null ? undefined : this.pending.get(message.id);
173
- if (pending) {
174
- clearTimeout(pending.timer);
175
- this.pending.delete(message.id!);
176
- pending.resolve(message);
177
- }
178
- } else if (JsonRpc.isRequest(message)) {
179
- const request = message;
180
- const handle = this.options.handle ?? (async (r: JsonRpc.Request) => JsonRpc.error(r.id ?? null, JsonRpc.METHOD_NOT_FOUND, `No @RpcClient for ${r.method}.`));
181
- void handle(request).then(response => {
182
- if (request.id !== undefined && socket.readyState === 1) {
183
- socket.send(JSON.stringify(response));
184
- }
185
- });
108
+ if (this.closed) {
109
+ this.client.close();
186
110
  }
111
+ return this.client;
187
112
  }
188
113
  }
@@ -1,3 +1,5 @@
1
1
  export * from './connection-protocol';
2
2
  export * from './rpc-context';
3
- export * from './rpc-connection-manager';export * from './rpc-connection';
3
+ export * from './rpc-connection-manager';
4
+ export * from './rpc-connection';
5
+ export * from './rpc-push-channel';
@@ -0,0 +1,61 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { RpcPushChannel } from './rpc-push-channel';
3
+
4
+ function setup(maxBacklogBytes = 1000) {
5
+ const batches: string[][] = [];
6
+ const answers: (() => void)[] = [];
7
+ const state = { closed: false, overflowed: 0 };
8
+ const channel = new RpcPushChannel<string>({
9
+ maxBacklogBytes,
10
+ streamed: item => item.startsWith('delta'),
11
+ send: batch => {
12
+ batches.push(batch);
13
+ return new Promise<void>(done => answers.push(done));
14
+ },
15
+ closed: () => state.closed,
16
+ overflow: () => state.overflowed++,
17
+ });
18
+ return { channel, batches, answers, state };
19
+ }
20
+
21
+ const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
22
+
23
+ describe('RpcPushChannel', () => {
24
+ it('sends what comes in one turn together, and the next batch once the client answered', async () => {
25
+ const { channel, batches, answers } = setup();
26
+ channel.push('a', 1);
27
+ channel.push('b', 1);
28
+ await sleep(5);
29
+ channel.push('c', 1);
30
+ await sleep(5);
31
+ expect(batches).toEqual([['a', 'b']]);
32
+ answers[0]();
33
+ await sleep(5);
34
+ expect(batches).toEqual([['a', 'b'], ['c']]);
35
+ });
36
+
37
+ it('holds streamed items for the interval after the first, and sends any other at once with them', async () => {
38
+ const { channel, batches, answers } = setup();
39
+ channel.push('delta 1', 1);
40
+ await sleep(5);
41
+ answers[0]();
42
+ channel.push('delta 2', 1);
43
+ await sleep(5);
44
+ expect(batches).toEqual([['delta 1']]);
45
+ channel.push('end', 1);
46
+ await sleep(5);
47
+ expect(batches).toEqual([['delta 1'], ['delta 2', 'end']]);
48
+ });
49
+
50
+ it('drops the queue and tells once a client falls too far behind, and sends nothing once closed', async () => {
51
+ const { channel, batches, state } = setup(2);
52
+ channel.push('a', 1);
53
+ channel.push('b', 1);
54
+ channel.push('c', 1);
55
+ expect(state.overflowed).toBe(1);
56
+ channel.push('d', 1);
57
+ state.closed = true;
58
+ await sleep(5);
59
+ expect(batches).toEqual([]);
60
+ });
61
+ });
@@ -0,0 +1,98 @@
1
+ export interface RpcPushChannelOptions<T> {
2
+ /** Sends a batch to the client; the next waits until it settles (the client answered, or the call failed). */
3
+ send(batch: T[]): Promise<unknown>;
4
+ /** Whether the connection is closed: nothing is sent then. */
5
+ closed(): boolean;
6
+ /** Called once a client falls more than `maxBacklogBytes` behind; its queue is dropped. */
7
+ overflow(): void;
8
+ /** Bytes a client may fall behind. */
9
+ maxBacklogBytes: number;
10
+ /** Items of this kind leave at most once per `intervalMs`, the first of a while at once; others leave at once. */
11
+ streamed?(item: T): boolean;
12
+ /** Default 30. */
13
+ intervalMs?: number;
14
+ }
15
+
16
+ /**
17
+ * What the server pushes to one client (`@RpcClient`), one call at a time: the next batch leaves when the client has
18
+ * answered the last, so that a slow client costs a bounded queue (`maxBacklogBytes`, then `overflow`) and nothing
19
+ * while nothing flows. Items that come by the hundred (`streamed`: the deltas of a reply) leave at most once an
20
+ * interval, the first of them at once; any other leaves at once, with what is queued, so that nothing a user waits
21
+ * for is held back. Items of the same turn of the event loop leave together.
22
+ */
23
+ export class RpcPushChannel<T> {
24
+ protected queue: T[] = [];
25
+ protected queuedBytes = 0;
26
+ protected timer?: ReturnType<typeof setTimeout>;
27
+ protected sending = false;
28
+ protected lastFlushAt = Number.NEGATIVE_INFINITY;
29
+ /** When the timer fires, on the clock of `performance.now()`. */
30
+ protected dueAt = 0;
31
+ /** The queue holds an item that should not wait. */
32
+ protected urgent = false;
33
+ /** The queue holds a streamed item. */
34
+ protected streamed = false;
35
+
36
+ constructor(protected readonly options: RpcPushChannelOptions<T>) {}
37
+
38
+ /** Queues an item of `bytes` (its size as sent, about). */
39
+ push(item: T, bytes: number): void {
40
+ this.queue.push(item);
41
+ this.queuedBytes += bytes;
42
+ if (this.queuedBytes > this.options.maxBacklogBytes) {
43
+ this.clear();
44
+ this.options.overflow();
45
+ return;
46
+ }
47
+ const streamed = this.options.streamed?.(item) ?? false;
48
+ this.streamed ||= streamed;
49
+ this.urgent ||= !streamed;
50
+ this.schedule();
51
+ }
52
+
53
+ /** Drops what is queued. */
54
+ clear(): void {
55
+ clearTimeout(this.timer);
56
+ this.timer = undefined;
57
+ this.queue = [];
58
+ this.queuedBytes = 0;
59
+ this.urgent = false;
60
+ this.streamed = false;
61
+ }
62
+
63
+ /** A timer, not a direct send: the items of the same turn of the event loop leave together. */
64
+ protected schedule(): void {
65
+ const due = this.urgent ? 0 : this.lastFlushAt + (this.options.intervalMs ?? 30);
66
+ if (this.timer !== undefined && this.dueAt <= due) {
67
+ return;
68
+ }
69
+ clearTimeout(this.timer);
70
+ this.dueAt = due;
71
+ this.timer = setTimeout(() => this.flush(), Math.max(0, due - performance.now()));
72
+ }
73
+
74
+ protected flush(): void {
75
+ this.timer = undefined;
76
+ if (this.sending || !this.queue.length || this.options.closed()) {
77
+ return;
78
+ }
79
+ const batch = this.queue;
80
+ this.queue = [];
81
+ this.queuedBytes = 0;
82
+ if (this.streamed) {
83
+ this.lastFlushAt = performance.now();
84
+ }
85
+ this.urgent = false;
86
+ this.streamed = false;
87
+ this.sending = true;
88
+ this.options
89
+ .send(batch)
90
+ .catch(() => undefined)
91
+ .finally(() => {
92
+ this.sending = false;
93
+ if (this.queue.length) {
94
+ this.schedule();
95
+ }
96
+ });
97
+ }
98
+ }
@@ -1,4 +1,5 @@
1
1
  export * from './websocket-frames';
2
2
  export * from './websocket-connection';
3
3
  export * from './websocket-exchange';
4
+ export * from './websocket-upgrades';
4
5
  export * from './rpc-websocket-server';
@@ -8,6 +8,7 @@ import { RPC_CONNECTION_KEY, RpcConnectionManager, RpcWebSocketGuard } from '../
8
8
  import { RpcConnectionImpl } from '../connection/rpc-connection';
9
9
  import { WebSocketConnection } from './websocket-connection';
10
10
  import { WebSocketExchange } from './websocket-exchange';
11
+ import { WebSocketUpgrades } from './websocket-upgrades';
11
12
 
12
13
  export interface RpcWebSocketOptions {
13
14
  /** Origins besides the server's own that may connect (`https://app.example.com`), or `*`. */
@@ -55,10 +56,9 @@ export class RpcWebSocketServer implements ServerAware, ApplicationLifecycle<App
55
56
  @Autowired(Logger)
56
57
  protected readonly logger: Logger;
57
58
 
58
- protected server?: Server;
59
59
  protected path: string;
60
60
  protected base: string;
61
- protected listener?: (request: IncomingMessage, socket: Duplex, head: Buffer) => void;
61
+ protected unroute?: () => void;
62
62
 
63
63
  async setServer(server: Server): Promise<void> {
64
64
  if (this.transport !== 'websocket' || typeof server?.on !== 'function') {
@@ -70,26 +70,15 @@ export class RpcWebSocketServer implements ServerAware, ApplicationLifecycle<App
70
70
  }
71
71
  this.base = (await this.pathResolver.resolve(this.rpcPath)).replace(/\/$/, '');
72
72
  this.path = `${this.base}/${RPC_WEBSOCKET_PATH}`;
73
- this.listener = (request, socket, head) => this.upgrade(request, socket, head);
74
- this.server = server;
75
- server.on('upgrade', this.listener);
73
+ this.unroute = WebSocketUpgrades.of(server).route(this.path, (request, socket, head) => this.upgrade(request, socket, head));
76
74
  }
77
75
 
78
76
  onStop(): void {
79
- if (this.server && this.listener) {
80
- this.server.off('upgrade', this.listener);
81
- }
77
+ this.unroute?.();
82
78
  this.connections.closeAll();
83
79
  }
84
80
 
85
81
  protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {
86
- if ((request.url ?? '').split('?')[0] !== this.path) {
87
- // Another listener (the HMR socket of cell dev) may want it; nobody else would answer.
88
- if (this.server!.listenerCount('upgrade') === 1) {
89
- socket.destroy();
90
- }
91
- return;
92
- }
93
82
  const checked = WebSocketConnection.check(request);
94
83
  if ('status' in checked) {
95
84
  WebSocketConnection.refuse(socket, checked.status, checked.message);
@@ -104,7 +93,7 @@ export class RpcWebSocketServer implements ServerAware, ApplicationLifecycle<App
104
93
  WebSocketConnection.refuse(socket, 401, 'Not authorized.');
105
94
  return;
106
95
  }
107
- const socketConnection = WebSocketConnection.open(socket, checked.key, head ?? Buffer.alloc(0), {
96
+ const socketConnection = WebSocketConnection.open(socket, checked.key, head, {
108
97
  maxPayload: this.options?.maxPayload ?? 1048576,
109
98
  heartbeat: this.options?.heartbeat ?? 30000,
110
99
  deflate: checked.deflate && this.options?.deflate !== false,
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { EventEmitter } from 'node:events';
3
+ import type { IncomingMessage } from 'node:http';
4
+ import { Duplex } from 'node:stream';
5
+ import { WebSocketUpgrades } from './websocket-upgrades';
6
+
7
+ class FakeSocket extends Duplex {
8
+ written = '';
9
+ destroyedHere = false;
10
+ override _read(): void {}
11
+ override _write(chunk: Buffer, _encoding: string, done: () => void): void {
12
+ this.written += chunk.toString();
13
+ done();
14
+ }
15
+ override _destroy(error: Error | null, done: (error: Error | null) => void): void {
16
+ this.destroyedHere = true;
17
+ done(error);
18
+ }
19
+ }
20
+
21
+ function upgrade(server: EventEmitter, url: string): FakeSocket {
22
+ const socket = new FakeSocket();
23
+ server.emit('upgrade', { url, headers: {} } as IncomingMessage, socket, Buffer.alloc(0));
24
+ return socket;
25
+ }
26
+
27
+ describe('WebSocketUpgrades', () => {
28
+ it('routes by path, the longest prefix first, with one listener for all routes', () => {
29
+ const server = new EventEmitter();
30
+ const seen: string[] = [];
31
+ const upgrades = WebSocketUpgrades.of(server as never);
32
+ upgrades.route('/api/ws', (_r, _s, _h, url) => seen.push(`ws ${url.search}`));
33
+ upgrades.route('/r/', (_r, _s, _h, url) => seen.push(`r ${url.pathname}`), { prefix: true });
34
+ upgrades.route('/r/hub/', () => seen.push('hub'), { prefix: true });
35
+ expect(WebSocketUpgrades.of(server as never)).toBe(upgrades);
36
+ expect(server.listenerCount('upgrade')).toBe(1);
37
+ upgrade(server, '/api/ws?token=t');
38
+ upgrade(server, '/r/abc');
39
+ upgrade(server, '/r/hub/x');
40
+ expect(seen).toEqual(['ws ?token=t', 'r /r/abc', 'hub']);
41
+ });
42
+
43
+ it('refuses with 404 what no route takes, unless the server has another listener that may', () => {
44
+ const server = new EventEmitter();
45
+ const dispose = WebSocketUpgrades.of(server as never).route('/api/ws', () => undefined);
46
+ expect(upgrade(server, '/nothing').written).toStartWith('HTTP/1.1 404');
47
+ const other = () => undefined;
48
+ server.on('upgrade', other);
49
+ expect(upgrade(server, '/nothing').written).toBe('');
50
+ server.off('upgrade', other);
51
+ dispose();
52
+ expect(server.listenerCount('upgrade')).toBe(0);
53
+ });
54
+
55
+ it('will not take a path twice, and a handler that throws loses only its socket', () => {
56
+ const server = new EventEmitter();
57
+ const upgrades = WebSocketUpgrades.of(server as never);
58
+ upgrades.route('/a', () => {
59
+ throw new Error('broken');
60
+ });
61
+ expect(() => upgrades.route('/a', () => undefined)).toThrow('/a');
62
+ expect(upgrade(server, '/a').destroyedHere).toBe(true);
63
+ });
64
+ });
@@ -0,0 +1,95 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { Duplex } from 'node:stream';
3
+ import { WebSocketConnection } from './websocket-connection';
4
+
5
+ /** What answers the upgrade requests of one route: `head` are the bytes already read after the request. */
6
+ export type WebSocketUpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer, url: URL) => void;
7
+
8
+ /** The part of a Node.js HTTP server the routes need. */
9
+ export interface WebSocketUpgradeServer {
10
+ on(event: 'upgrade', listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;
11
+ off(event: 'upgrade', listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;
12
+ listenerCount(event: 'upgrade'): number;
13
+ }
14
+
15
+ interface Route {
16
+ path: string;
17
+ /** The path and all below it (`/r/` takes `/r/abc`), not only the path itself. */
18
+ prefix: boolean;
19
+ handler: WebSocketUpgradeHandler;
20
+ }
21
+
22
+ /**
23
+ * The upgrade requests of one HTTP server, routed by path: one `upgrade` listener for all that answer WebSocket
24
+ * connections on it (the RPC socket of Cell, those of an application), so that none has to guess whether another
25
+ * will answer a request it does not take. A request no route takes is refused with 404, unless the server has
26
+ * listeners of its own besides (the HMR socket of a dev server), which may take it.
27
+ *
28
+ * ```ts
29
+ * const dispose = WebSocketUpgrades.of(server).route('/api/exec', (request, socket, head) => exec.accept(request, socket, head));
30
+ * ```
31
+ */
32
+ export class WebSocketUpgrades {
33
+ protected static readonly servers = new WeakMap<WebSocketUpgradeServer, WebSocketUpgrades>();
34
+
35
+ protected readonly routes: Route[] = [];
36
+ protected readonly listener = (request: IncomingMessage, socket: Duplex, head: Buffer) => this.dispatch(request, socket, head);
37
+
38
+ /** The routes of `server`: the same for everyone that asks, listening while it has a route. */
39
+ static of(server: WebSocketUpgradeServer): WebSocketUpgrades {
40
+ let upgrades = WebSocketUpgrades.servers.get(server);
41
+ if (!upgrades) {
42
+ upgrades = new WebSocketUpgrades(server);
43
+ WebSocketUpgrades.servers.set(server, upgrades);
44
+ }
45
+ return upgrades;
46
+ }
47
+
48
+ protected constructor(protected readonly server: WebSocketUpgradeServer) {}
49
+
50
+ /**
51
+ * Routes the upgrade requests of `path` (and, with `prefix`, of the paths below it) to `handler`; a path taken
52
+ * already throws. Returns what removes the route.
53
+ */
54
+ route(path: string, handler: WebSocketUpgradeHandler, options: { prefix?: boolean } = {}): () => void {
55
+ const prefix = !!options.prefix;
56
+ if (this.routes.some(route => route.path === path && route.prefix === prefix)) {
57
+ throw new Error(`Upgrade requests of ${path} have a route already.`);
58
+ }
59
+ const route: Route = { path, prefix, handler };
60
+ this.routes.push(route);
61
+ // The longest path first: `/api/ws/x` before `/api/`.
62
+ this.routes.sort((a, b) => b.path.length - a.path.length);
63
+ if (this.routes.length === 1) {
64
+ this.server.on('upgrade', this.listener);
65
+ }
66
+ return () => {
67
+ const index = this.routes.indexOf(route);
68
+ if (index >= 0) {
69
+ this.routes.splice(index, 1);
70
+ if (this.routes.length === 0) {
71
+ this.server.off('upgrade', this.listener);
72
+ }
73
+ }
74
+ };
75
+ }
76
+
77
+ /** The route of a path, or undefined. */
78
+ match(path: string): WebSocketUpgradeHandler | undefined {
79
+ return this.routes.find(route => (route.prefix ? path.startsWith(route.path) : path === route.path))?.handler;
80
+ }
81
+
82
+ protected dispatch(request: IncomingMessage, socket: Duplex, head: Buffer): void {
83
+ const url = new URL(request.url ?? '/', 'http://localhost');
84
+ const handler = this.match(url.pathname);
85
+ if (handler) {
86
+ try {
87
+ handler(request, socket, head ?? Buffer.alloc(0), url);
88
+ } catch {
89
+ socket.destroy();
90
+ }
91
+ } else if (this.server.listenerCount('upgrade') === 1) {
92
+ WebSocketConnection.refuse(socket, 404, 'Not found.');
93
+ }
94
+ }
95
+ }