@celljs/rpc 4.9.1 → 4.10.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 (34) hide show
  1. package/README.md +1 -0
  2. package/README.zh-cn.md +1 -0
  3. package/cell.schema.json +4 -0
  4. package/esm/node/websocket/rpc-websocket-server.d.ts +2 -0
  5. package/esm/node/websocket/rpc-websocket-server.js +8 -7
  6. package/esm/node/websocket/rpc-websocket-server.js.map +1 -1
  7. package/esm/node/websocket/websocket-connection.d.ts +13 -2
  8. package/esm/node/websocket/websocket-connection.js +27 -9
  9. package/esm/node/websocket/websocket-connection.js.map +1 -1
  10. package/esm/node/websocket/websocket-frames.d.ts +26 -2
  11. package/esm/node/websocket/websocket-frames.js +65 -7
  12. package/esm/node/websocket/websocket-frames.js.map +1 -1
  13. package/lib/node/rpc-websocket.spec.js +29 -0
  14. package/lib/node/rpc-websocket.spec.js.map +1 -1
  15. package/lib/node/websocket/rpc-websocket-server.d.ts +2 -0
  16. package/lib/node/websocket/rpc-websocket-server.d.ts.map +1 -1
  17. package/lib/node/websocket/rpc-websocket-server.js +8 -7
  18. package/lib/node/websocket/rpc-websocket-server.js.map +1 -1
  19. package/lib/node/websocket/websocket-connection.d.ts +13 -2
  20. package/lib/node/websocket/websocket-connection.d.ts.map +1 -1
  21. package/lib/node/websocket/websocket-connection.js +26 -8
  22. package/lib/node/websocket/websocket-connection.js.map +1 -1
  23. package/lib/node/websocket/websocket-frames.d.ts +26 -2
  24. package/lib/node/websocket/websocket-frames.d.ts.map +1 -1
  25. package/lib/node/websocket/websocket-frames.js +66 -8
  26. package/lib/node/websocket/websocket-frames.js.map +1 -1
  27. package/lib/node/websocket/websocket-frames.spec.js +27 -2
  28. package/lib/node/websocket/websocket-frames.spec.js.map +1 -1
  29. package/package.json +4 -4
  30. package/src/node/rpc-websocket.spec.ts +31 -0
  31. package/src/node/websocket/rpc-websocket-server.ts +4 -1
  32. package/src/node/websocket/websocket-connection.ts +33 -11
  33. package/src/node/websocket/websocket-frames.spec.ts +31 -3
  34. package/src/node/websocket/websocket-frames.ts +70 -8
@@ -18,6 +18,8 @@ export interface RpcWebSocketOptions {
18
18
  heartbeat?: number;
19
19
  /** Milliseconds a call to a client waits for its answer. Default 30000. */
20
20
  callTimeout?: number;
21
+ /** Compress messages with permessage-deflate when a page of a browser offers it. Default true. */
22
+ deflate?: boolean;
21
23
  }
22
24
 
23
25
  /**
@@ -105,6 +107,7 @@ export class RpcWebSocketServer implements ServerAware, ApplicationLifecycle<App
105
107
  const socketConnection = WebSocketConnection.open(socket, checked.key, head ?? Buffer.alloc(0), {
106
108
  maxPayload: this.options?.maxPayload ?? 1048576,
107
109
  heartbeat: this.options?.heartbeat ?? 30000,
110
+ deflate: checked.deflate && this.options?.deflate !== false,
108
111
  });
109
112
  const connection = new RpcConnectionImpl(socketConnection, request, (c, r) => this.dispatch(c, r), this.options?.callTimeout ?? 30000);
110
113
  this.connections.add(connection);
@@ -168,4 +171,4 @@ export class RpcWebSocketServer implements ServerAware, ApplicationLifecycle<App
168
171
  const status = res.statusCode;
169
172
  return JsonRpc.error(id, status === 404 ? JsonRpc.METHOD_NOT_FOUND : JsonRpc.SERVER_ERROR, text && text.length < 500 ? text : `HTTP ${status}`, { status });
170
173
  }
171
- }
174
+ }
@@ -4,13 +4,18 @@ import type { Duplex } from 'node:stream';
4
4
  // The emitter alone: a process with only WebSocket connections (ta exec-server) does not load the framework.
5
5
  import { Emitter } from '@celljs/core/lib/common/utils/emitter';
6
6
  import type { Event } from '@celljs/core/lib/common/utils/event';
7
- import { WebSocketFrameParser, WebSocketFrames, WebSocketProtocolError } from './websocket-frames';
7
+ import { WebSocketDeflate, WebSocketFrameParser, WebSocketFrames, WebSocketProtocolError } from './websocket-frames';
8
8
 
9
9
  export interface WebSocketConnectionOptions {
10
10
  /** Largest message, in bytes. */
11
11
  maxPayload: number;
12
12
  /** Milliseconds between pings; a peer that answered none of them is dropped. 0: no pings. */
13
13
  heartbeat: number;
14
+ /**
15
+ * Messages compressed with permessage-deflate (RFC 7692), both ways: pass the `deflate` of `check`,
16
+ * whether the client offered it. Default false.
17
+ */
18
+ deflate?: boolean;
14
19
  }
15
20
 
16
21
  /** The server side of one WebSocket connection (RFC 6455) on the socket of an upgraded request: text messages. */
@@ -23,6 +28,8 @@ export class WebSocketConnection {
23
28
  protected readonly parser: WebSocketFrameParser;
24
29
  protected readonly decoder = new TextDecoder('utf-8', { fatal: true });
25
30
  protected fragments: Buffer[] = [];
31
+ /** The message of the fragments is compressed. */
32
+ protected compressed = false;
26
33
  protected fragmentsLength = 0;
27
34
  protected state: 'open' | 'closing' | 'closed' = 'open';
28
35
  protected alive = true;
@@ -37,8 +44,11 @@ export class WebSocketConnection {
37
44
  return major > 1 || (major === 1 && minor >= 4);
38
45
  }
39
46
 
40
- /** The key of an upgrade request that can become a connection, or why not (status and message). */
41
- static check(request: IncomingMessage): { key: string } | { status: number, message: string } {
47
+ /**
48
+ * The key of an upgrade request that can become a connection, and whether its client is a page that
49
+ * offered permessage-deflate (for `WebSocketConnectionOptions.deflate`); or why not (status and message).
50
+ */
51
+ static check(request: IncomingMessage): { key: string, deflate: boolean } | { status: number, message: string } {
42
52
  const upgrade = String(request.headers.upgrade ?? '').toLowerCase();
43
53
  const connection = String(request.headers.connection ?? '').toLowerCase();
44
54
  const key = request.headers['sec-websocket-key'];
@@ -51,7 +61,10 @@ export class WebSocketConnection {
51
61
  if (typeof key !== 'string' || Buffer.from(key, 'base64').length !== 16) {
52
62
  return { status: 400, message: 'Missing or invalid Sec-WebSocket-Key.' };
53
63
  }
54
- return { key };
64
+ // Pages of browsers, which send their origin: the clients on networks that wait for bytes. Others (a
65
+ // backend, a host next to the server) gain little, and the client of Bun before 1.4 inflates some wrong.
66
+ const deflate = !!request.headers.origin && WebSocketDeflate.offered(request.headers['sec-websocket-extensions']);
67
+ return { key, deflate };
55
68
  }
56
69
 
57
70
  static accept(key: string): string {
@@ -60,7 +73,8 @@ export class WebSocketConnection {
60
73
 
61
74
  /** Answers the upgrade request and starts reading; `head` are the bytes already read after it. */
62
75
  static open(socket: Duplex, key: string, head: Buffer, options: WebSocketConnectionOptions): WebSocketConnection {
63
- socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${WebSocketConnection.accept(key)}\r\n\r\n`);
76
+ const extensions = options.deflate ? `Sec-WebSocket-Extensions: ${WebSocketDeflate.RESPONSE}\r\n` : '';
77
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${WebSocketConnection.accept(key)}\r\n${extensions}\r\n`);
64
78
  const connection = new WebSocketConnection(socket, options);
65
79
  connection.start(head);
66
80
  return connection;
@@ -74,7 +88,7 @@ export class WebSocketConnection {
74
88
  }
75
89
 
76
90
  constructor(protected readonly socket: Duplex, protected readonly options: WebSocketConnectionOptions) {
77
- this.parser = new WebSocketFrameParser(options.maxPayload);
91
+ this.parser = new WebSocketFrameParser(options.maxPayload, !!options.deflate);
78
92
  }
79
93
 
80
94
  get onMessage(): Event<string> {
@@ -91,7 +105,12 @@ export class WebSocketConnection {
91
105
 
92
106
  send(text: string): void {
93
107
  if (this.state === 'open') {
94
- this.socket.write(WebSocketFrames.encode(WebSocketFrames.TEXT, Buffer.from(text)));
108
+ const data = Buffer.from(text);
109
+ if (this.options.deflate && data.length >= WebSocketDeflate.MIN_BYTES) {
110
+ this.socket.write(WebSocketFrames.encode(WebSocketFrames.TEXT, WebSocketDeflate.compress(data), true));
111
+ } else {
112
+ this.socket.write(WebSocketFrames.encode(WebSocketFrames.TEXT, data));
113
+ }
95
114
  }
96
115
  }
97
116
 
@@ -130,14 +149,14 @@ export class WebSocketConnection {
130
149
  try {
131
150
  for (const frame of this.parser.push(chunk)) {
132
151
  this.alive = true;
133
- this.handle(frame.opcode, frame.fin, frame.payload);
152
+ this.handle(frame.opcode, frame.fin, frame.payload, frame.compressed);
134
153
  }
135
154
  } catch (error) {
136
155
  this.close(error instanceof WebSocketProtocolError ? error.code : 1011, error instanceof Error ? error.message : '');
137
156
  }
138
157
  }
139
158
 
140
- protected handle(opcode: number, fin: boolean, payload: Buffer): void {
159
+ protected handle(opcode: number, fin: boolean, payload: Buffer, compressed = false): void {
141
160
  switch (opcode) {
142
161
  case WebSocketFrames.PING:
143
162
  this.socket.write(WebSocketFrames.encode(WebSocketFrames.PONG, payload));
@@ -161,6 +180,7 @@ export class WebSocketConnection {
161
180
  if (this.fragments.length) {
162
181
  throw new WebSocketProtocolError(1002, 'A new message started inside a fragmented one.');
163
182
  }
183
+ this.compressed = compressed;
164
184
  break;
165
185
  case WebSocketFrames.CONTINUATION:
166
186
  if (!this.fragments.length) {
@@ -174,9 +194,11 @@ export class WebSocketConnection {
174
194
  }
175
195
  this.fragments.push(payload);
176
196
  if (fin) {
177
- const message = this.fragments.length === 1 ? this.fragments[0] : Buffer.concat(this.fragments);
197
+ const joined = this.fragments.length === 1 ? this.fragments[0] : Buffer.concat(this.fragments);
198
+ const message = this.compressed ? WebSocketDeflate.decompress(joined, this.options.maxPayload) : joined;
178
199
  this.fragments = [];
179
200
  this.fragmentsLength = 0;
201
+ this.compressed = false;
180
202
  let text: string;
181
203
  try {
182
204
  text = this.decoder.decode(message);
@@ -199,4 +221,4 @@ export class WebSocketConnection {
199
221
  this.onMessageEmitter.dispose();
200
222
  this.onCloseEmitter.dispose();
201
223
  }
202
- }
224
+ }
@@ -1,13 +1,13 @@
1
1
  import { describe, expect, it } from 'bun:test';
2
- import { WebSocketFrameParser, WebSocketFrames, WebSocketProtocolError } from './websocket-frames';
2
+ import { WebSocketDeflate, WebSocketFrameParser, WebSocketFrames, WebSocketProtocolError } from './websocket-frames';
3
3
 
4
4
  /** A frame as a client sends it: masked. */
5
- function clientFrame(opcode: number, payload: Buffer, fin = true): Buffer {
5
+ function clientFrame(opcode: number, payload: Buffer, fin = true, compressed = false): Buffer {
6
6
  const plain = WebSocketFrames.encode(opcode, payload);
7
7
  const headerLength = plain.length - payload.length;
8
8
  const mask = Buffer.from([1, 2, 3, 4]);
9
9
  const header = Buffer.from(plain.subarray(0, headerLength));
10
- header[0] = (fin ? 0x80 : 0) | opcode;
10
+ header[0] = (fin ? 0x80 : 0) | (compressed ? 0x40 : 0) | opcode;
11
11
  header[1] |= 0x80;
12
12
  const masked = Buffer.from(payload.map((b, i) => b ^ mask[i & 3]));
13
13
  return Buffer.concat([header, mask, masked]);
@@ -59,4 +59,32 @@ describe('WebSocketFrames', () => {
59
59
  it('writes the code and reason of a close frame', () => {
60
60
  expect([...WebSocketFrames.closePayload(1001, 'bye')]).toEqual([3, 233, 98, 121, 101]);
61
61
  });
62
+
63
+ it('reads a compressed message once permessage-deflate is agreed, and only then', () => {
64
+ const text = Buffer.from(JSON.stringify({ messages: Array.from({ length: 200 }, (_, i) => ({ role: 'assistant', text: `line ${i}` })) }));
65
+ const compressed = WebSocketDeflate.compress(text);
66
+ expect(compressed.length).toBeLessThan(text.length / 3);
67
+ expect(WebSocketFrames.encode(WebSocketFrames.TEXT, compressed, true)[0]).toBe(0xc1);
68
+ const [frame] = new WebSocketFrameParser(1 << 20, true).push(clientFrame(WebSocketFrames.TEXT, compressed, true, true));
69
+ expect(frame.compressed).toBe(true);
70
+ expect(WebSocketDeflate.decompress(frame.payload, 1 << 20).equals(text)).toBe(true);
71
+ expect(protocolError(() => new WebSocketFrameParser(1 << 20).push(clientFrame(WebSocketFrames.TEXT, compressed, true, true))).code).toBe(1002);
72
+ expect(protocolError(() => new WebSocketFrameParser(1 << 20, true).push(clientFrame(WebSocketFrames.CONTINUATION, compressed, true, true))).code).toBe(1002);
73
+ expect(protocolError(() => new WebSocketFrameParser(1 << 20, true).push(clientFrame(WebSocketFrames.PING, Buffer.from('x'), true, true))).code).toBe(1002);
74
+ });
75
+
76
+ it('refuses a compressed message that inflates past the largest, or does not inflate', () => {
77
+ const compressed = WebSocketDeflate.compress(Buffer.alloc(5000, 'a'));
78
+ expect(protocolError(() => WebSocketDeflate.decompress(compressed, 4000)).code).toBe(1009);
79
+ expect(protocolError(() => WebSocketDeflate.decompress(Buffer.from([0xff, 0xff, 0xff]), 4000)).code).toBe(1007);
80
+ });
81
+
82
+ it('takes the offers of permessage-deflate of browsers, not one that narrows the window of the server', () => {
83
+ expect(WebSocketDeflate.offered('permessage-deflate; client_max_window_bits')).toBe(true);
84
+ expect(WebSocketDeflate.offered('permessage-deflate')).toBe(true);
85
+ expect(WebSocketDeflate.offered('permessage-deflate; server_max_window_bits=10')).toBe(false);
86
+ expect(WebSocketDeflate.offered('permessage-deflate; server_max_window_bits=10, permessage-deflate')).toBe(true);
87
+ expect(WebSocketDeflate.offered(undefined)).toBe(false);
88
+ expect(WebSocketDeflate.offered('x-webkit-deflate-frame')).toBe(false);
89
+ });
62
90
  });
@@ -1,3 +1,5 @@
1
+ import { constants, deflateRawSync, inflateRawSync } from 'node:zlib';
2
+
1
3
  /** An error of the peer that closes the connection with `code` (RFC 6455 §7.4). */
2
4
  export class WebSocketProtocolError extends Error {
3
5
  constructor(readonly code: number, message: string) {
@@ -7,6 +9,8 @@ export class WebSocketProtocolError extends Error {
7
9
 
8
10
  export interface WebSocketFrame {
9
11
  fin: boolean;
12
+ /** RSV1: the message of this first frame is compressed (permessage-deflate). */
13
+ compressed: boolean;
10
14
  opcode: number;
11
15
  payload: Buffer;
12
16
  }
@@ -20,11 +24,12 @@ export namespace WebSocketFrames {
20
24
  export const PING = 0x9;
21
25
  export const PONG = 0xa;
22
26
 
23
- export function encode(opcode: number, payload: Buffer = Buffer.alloc(0)): Buffer {
27
+ /** A frame of one whole message; `compressed` sets RSV1, for a payload of `WebSocketDeflate.compress`. */
28
+ export function encode(opcode: number, payload: Buffer = Buffer.alloc(0), compressed = false): Buffer {
24
29
  const length = payload.length;
25
30
  const size = length < 126 ? 2 : length < 65536 ? 4 : 10;
26
31
  const header = Buffer.alloc(size);
27
- header[0] = 0x80 | opcode;
32
+ header[0] = 0x80 | (compressed ? 0x40 : 0) | opcode;
28
33
  if (length < 126) {
29
34
  header[1] = length;
30
35
  } else if (length < 65536) {
@@ -55,7 +60,11 @@ export namespace WebSocketFrames {
55
60
  export class WebSocketFrameParser {
56
61
  protected buffer: Buffer = Buffer.alloc(0);
57
62
 
58
- constructor(protected readonly maxPayload: number) {}
63
+ /** With `deflate` (negotiated permessage-deflate), RSV1 may be set. */
64
+ constructor(
65
+ protected readonly maxPayload: number,
66
+ protected readonly deflate = false,
67
+ ) {}
59
68
 
60
69
  /** The frames completed by `chunk`; throws a {@link WebSocketProtocolError} on frames the protocol forbids. */
61
70
  push(chunk: Buffer): WebSocketFrame[] {
@@ -74,7 +83,8 @@ export class WebSocketFrameParser {
74
83
  }
75
84
  const fin = (buffer[0] & 0x80) !== 0;
76
85
  const opcode = buffer[0] & 0x0f;
77
- if ((buffer[0] & 0x70) !== 0) {
86
+ const compressed = (buffer[0] & 0x40) !== 0;
87
+ if ((buffer[0] & (this.deflate ? 0x30 : 0x70)) !== 0) {
78
88
  throw new WebSocketProtocolError(1002, 'Reserved bits are set.');
79
89
  }
80
90
  if (![0, 1, 2, 8, 9, 10].includes(opcode)) {
@@ -102,8 +112,11 @@ export class WebSocketFrameParser {
102
112
  length = high * 0x100000000 + buffer.readUInt32BE(6);
103
113
  offset = 10;
104
114
  }
105
- if (WebSocketFrames.isControl(opcode) && (length > 125 || !fin)) {
106
- throw new WebSocketProtocolError(1002, 'Control frames are at most 125 bytes and not fragmented.');
115
+ if (WebSocketFrames.isControl(opcode) && (length > 125 || !fin || compressed)) {
116
+ throw new WebSocketProtocolError(1002, 'Control frames are at most 125 bytes, not fragmented and not compressed.');
117
+ }
118
+ if (compressed && opcode === WebSocketFrames.CONTINUATION) {
119
+ throw new WebSocketProtocolError(1002, 'Only the first frame of a message says it is compressed.');
107
120
  }
108
121
  if (length > this.maxPayload) {
109
122
  throw new WebSocketProtocolError(1009, `The message is larger than ${this.maxPayload} bytes.`);
@@ -117,6 +130,55 @@ export class WebSocketFrameParser {
117
130
  payload[i] ^= mask[i & 3];
118
131
  }
119
132
  this.buffer = buffer.subarray(offset + 4 + length);
120
- return { fin, opcode, payload };
133
+ return { fin, compressed, opcode, payload };
134
+ }
135
+ }
136
+ /** The tail of a block of deflate flushed with Z_SYNC_FLUSH: left out of a message, put back to inflate it (RFC 7692 §7.2.1). */
137
+ const TAIL = Buffer.from([0x00, 0x00, 0xff, 0xff]);
138
+
139
+ /**
140
+ * permessage-deflate (RFC 7692) without context takeover in either direction: each message is deflated
141
+ * on its own, so that a connection keeps no compressor between messages. JSON shrinks to a third or less,
142
+ * which is what a slow network waits for.
143
+ */
144
+ export namespace WebSocketDeflate {
145
+ /** What the server answers in `Sec-WebSocket-Extensions` to an offer it takes. */
146
+ export const RESPONSE = 'permessage-deflate; server_no_context_takeover; client_no_context_takeover';
147
+ /** Smaller messages go as they are: a frame of them is about as small compressed. */
148
+ export const MIN_BYTES = 1024;
149
+
150
+ /**
151
+ * Whether the client offers permessage-deflate as this server does it: an offer that limits the
152
+ * server's window (`server_max_window_bits` under 15) is not taken, the others are.
153
+ */
154
+ export function offered(header: string | string[] | undefined): boolean {
155
+ const offers = (Array.isArray(header) ? header.join(',') : (header ?? '')).split(',');
156
+ return offers.some(offer => {
157
+ const [name, ...params] = offer.split(';').map(part => part.trim().toLowerCase());
158
+ if (name !== 'permessage-deflate') {
159
+ return false;
160
+ }
161
+ return params.every(param => {
162
+ const [key, value] = param.split('=').map(part => part.trim().replace(/^"|"$/g, ''));
163
+ return key !== 'server_max_window_bits' || value === '15';
164
+ });
165
+ });
121
166
  }
122
- }
167
+
168
+ export function compress(data: Buffer): Buffer {
169
+ const deflated = deflateRawSync(data, { level: 3, finishFlush: constants.Z_SYNC_FLUSH });
170
+ return deflated.subarray(0, deflated.length - TAIL.length);
171
+ }
172
+
173
+ /** Throws a {@link WebSocketProtocolError} for what does not inflate, or inflates past `maxBytes`. */
174
+ export function decompress(data: Buffer, maxBytes: number): Buffer {
175
+ try {
176
+ return inflateRawSync(Buffer.concat([data, TAIL]), { maxOutputLength: maxBytes, finishFlush: constants.Z_SYNC_FLUSH });
177
+ } catch (error) {
178
+ if ((error as { code?: string }).code === 'ERR_BUFFER_TOO_LARGE') {
179
+ throw new WebSocketProtocolError(1009, `The message is larger than ${maxBytes} bytes.`);
180
+ }
181
+ throw new WebSocketProtocolError(1007, 'A compressed message does not inflate.');
182
+ }
183
+ }
184
+ }