walter-ws 1.2.1 → 1.3.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.
- package/package.json +1 -1
- package/src/client.js +52 -4
- package/src/frame.js +114 -1
- package/src/index.d.ts +15 -1
- package/src/index.js +13 -1
- package/src/index.mjs +3 -0
package/package.json
CHANGED
package/src/client.js
CHANGED
|
@@ -6,6 +6,10 @@ const { EventEmitter } = require('node:events');
|
|
|
6
6
|
const { READY_STATES, CLOSE_CODES } = require('./constants');
|
|
7
7
|
const { WalterConnection } = require('./connection');
|
|
8
8
|
const { CLIENT_KEY_POOL, ACCEPT_CACHE } = require('./server');
|
|
9
|
+
const { prepareClientFrame } = require('./frame');
|
|
10
|
+
|
|
11
|
+
// Global TLS 1.3 / 1.2 session ticket cache keyed by "hostname:port" for 1-RTT / 0-RTT reconnects
|
|
12
|
+
const TLS_SESSION_CACHE = new Map();
|
|
9
13
|
|
|
10
14
|
let keyPoolIdx = 0;
|
|
11
15
|
|
|
@@ -70,6 +74,8 @@ class WalterClient extends EventEmitter {
|
|
|
70
74
|
handshakeTimeout: options.handshakeTimeout ?? 10000,
|
|
71
75
|
skipUTF8Validation: options.skipUTF8Validation ?? false,
|
|
72
76
|
rawBuffer: options.rawBuffer ?? false,
|
|
77
|
+
tlsOptions: options.tlsOptions || null,
|
|
78
|
+
sessionReuse: options.sessionReuse ?? true,
|
|
73
79
|
autoReconnect: options.autoReconnect ?? false,
|
|
74
80
|
reconnectInterval: options.reconnectInterval ?? 1000,
|
|
75
81
|
maxReconnectInterval: options.maxReconnectInterval ?? 30000,
|
|
@@ -133,17 +139,29 @@ class WalterClient extends EventEmitter {
|
|
|
133
139
|
|
|
134
140
|
reqLines += '\r\n';
|
|
135
141
|
|
|
142
|
+
const sessionKey = `${this._hostname}:${this._port}`;
|
|
143
|
+
const cachedSession =
|
|
144
|
+
isSecure && this.options.sessionReuse ? TLS_SESSION_CACHE.get(sessionKey) : undefined;
|
|
145
|
+
|
|
136
146
|
const socket = isSecure
|
|
137
147
|
? tls.connect({
|
|
138
|
-
host: this._hostname,
|
|
139
|
-
port: this._port,
|
|
140
|
-
servername: this._hostname,
|
|
148
|
+
host: this.options.tlsOptions?.host || this._hostname,
|
|
149
|
+
port: this.options.tlsOptions?.port || this._port,
|
|
150
|
+
servername: this.options.tlsOptions?.servername || this._hostname,
|
|
151
|
+
...(cachedSession ? { session: cachedSession } : {}),
|
|
152
|
+
...(this.options.tlsOptions || {}),
|
|
141
153
|
})
|
|
142
154
|
: net.connect({
|
|
143
155
|
host: this._hostname,
|
|
144
156
|
port: this._port,
|
|
145
157
|
});
|
|
146
158
|
|
|
159
|
+
if (isSecure && this.options.sessionReuse) {
|
|
160
|
+
socket.on('session', (session) => {
|
|
161
|
+
TLS_SESSION_CACHE.set(sessionKey, session);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
147
165
|
socket.setNoDelay(true);
|
|
148
166
|
this._req = socket;
|
|
149
167
|
|
|
@@ -337,7 +355,11 @@ class WalterClient extends EventEmitter {
|
|
|
337
355
|
this._sendQueue = [];
|
|
338
356
|
for (const item of queue) {
|
|
339
357
|
if (this.readyState === READY_STATES.OPEN && this._connection) {
|
|
340
|
-
|
|
358
|
+
if (item.frame) {
|
|
359
|
+
this._connection.socket.write(item.frame, item.callback);
|
|
360
|
+
} else {
|
|
361
|
+
this._connection.send(item.data, item.options, item.callback);
|
|
362
|
+
}
|
|
341
363
|
}
|
|
342
364
|
}
|
|
343
365
|
}
|
|
@@ -361,6 +383,32 @@ class WalterClient extends EventEmitter {
|
|
|
361
383
|
this._connection.send(data, options, callback);
|
|
362
384
|
}
|
|
363
385
|
|
|
386
|
+
/**
|
|
387
|
+
* Sends a pre-compiled client frame Buffer directly to the socket with 0 CPU / 0 masking overhead.
|
|
388
|
+
* @param {Buffer} preMaskedFrame
|
|
389
|
+
* @param {Function} [callback]
|
|
390
|
+
*/
|
|
391
|
+
sendFrame(preMaskedFrame, callback) {
|
|
392
|
+
if (!this._connection || this.readyState !== READY_STATES.OPEN) {
|
|
393
|
+
if (this.options.offlineQueue && !this._explicitClose) {
|
|
394
|
+
this._sendQueue.push({ frame: preMaskedFrame, callback });
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
throw new Error(`WebSocket is not open: readyState ${this.readyState}`);
|
|
398
|
+
}
|
|
399
|
+
this._connection.socket.write(preMaskedFrame, callback);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Pre-encodes and pre-masks a static client message into a reusable Buffer.
|
|
404
|
+
* @param {string|Buffer|Uint8Array} data
|
|
405
|
+
* @param {object} [options]
|
|
406
|
+
* @returns {Buffer}
|
|
407
|
+
*/
|
|
408
|
+
prepareFrame(data, options) {
|
|
409
|
+
return prepareClientFrame(data, options);
|
|
410
|
+
}
|
|
411
|
+
|
|
364
412
|
/**
|
|
365
413
|
* Sends an object serialized as JSON text.
|
|
366
414
|
* @param {any} obj
|
package/src/frame.js
CHANGED
|
@@ -21,6 +21,25 @@ function fillRandomMask(targetBuffer, targetOffset) {
|
|
|
21
21
|
maskPoolOffset += 4;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
// Zero-GC 256KB Ring Buffer Pool for small frames (<= 256B) to eliminate V8 Garbage Collection pauses
|
|
25
|
+
const RING_POOL_SIZE = 256 * 1024;
|
|
26
|
+
const ringPool = Buffer.allocUnsafeSlow(RING_POOL_SIZE);
|
|
27
|
+
let ringOffset = 0;
|
|
28
|
+
|
|
29
|
+
function allocRingBuffer(size) {
|
|
30
|
+
if (size <= 256) {
|
|
31
|
+
// Keep 4-byte alignment for fast 32-bit Uint32Array operations
|
|
32
|
+
const alignedOffset = (ringOffset + 3) & ~3;
|
|
33
|
+
if (alignedOffset + size <= RING_POOL_SIZE) {
|
|
34
|
+
ringOffset = alignedOffset + size;
|
|
35
|
+
return ringPool.subarray(alignedOffset, ringOffset);
|
|
36
|
+
}
|
|
37
|
+
ringOffset = size;
|
|
38
|
+
return ringPool.subarray(0, size);
|
|
39
|
+
}
|
|
40
|
+
return Buffer.allocUnsafe(size);
|
|
41
|
+
}
|
|
42
|
+
|
|
24
43
|
/**
|
|
25
44
|
* Custom Error class for WebSocket protocol errors with corresponding close code.
|
|
26
45
|
*/
|
|
@@ -204,7 +223,7 @@ function encodeFrame(options) {
|
|
|
204
223
|
|
|
205
224
|
const maskKeyLength = mask ? 4 : 0;
|
|
206
225
|
const totalLen = headerLength + maskKeyLength + payloadLength;
|
|
207
|
-
const frame = Buffer.allocUnsafe(totalLen);
|
|
226
|
+
const frame = options.usePool === false ? Buffer.allocUnsafe(totalLen) : allocRingBuffer(totalLen);
|
|
208
227
|
|
|
209
228
|
// Byte 0: FIN (bit 7), RSV1-3 (bits 6-4 = 0), Opcode (bits 3-0)
|
|
210
229
|
frame[0] = (fin ? 0x80 : 0x00) | (opcode & 0x0f);
|
|
@@ -454,13 +473,107 @@ function prepareMessage(data, options = {}) {
|
|
|
454
473
|
fin: true,
|
|
455
474
|
mask: false,
|
|
456
475
|
returnParts: false,
|
|
476
|
+
usePool: false,
|
|
457
477
|
});
|
|
458
478
|
}
|
|
459
479
|
|
|
480
|
+
/**
|
|
481
|
+
* Pre-encodes and pre-masks a client-side (masked) WebSocket message into a dedicated reusable Buffer.
|
|
482
|
+
* Ideal for static client packets like IDENTIFY, HEARTBEAT (`{"op":1,"d":null}`), or SUBSCRIBE frames,
|
|
483
|
+
* allowing `ws.sendFrame(preMasked)` to write directly to the socket with 0 CPU, 0 allocation, and 0 XOR.
|
|
484
|
+
*
|
|
485
|
+
* @param {string|Buffer|Uint8Array} data
|
|
486
|
+
* @param {object} [options]
|
|
487
|
+
* @param {boolean} [options.binary]
|
|
488
|
+
* @returns {Buffer}
|
|
489
|
+
*/
|
|
490
|
+
function prepareClientFrame(data, options = {}) {
|
|
491
|
+
const isBinary =
|
|
492
|
+
options.binary ?? (Buffer.isBuffer(data) || ArrayBuffer.isView(data));
|
|
493
|
+
const opcode = isBinary ? OPCODES.BINARY : OPCODES.TEXT;
|
|
494
|
+
const payload =
|
|
495
|
+
typeof data === 'string' || Buffer.isBuffer(data)
|
|
496
|
+
? data
|
|
497
|
+
: ArrayBuffer.isView(data)
|
|
498
|
+
? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
|
|
499
|
+
: String(data);
|
|
500
|
+
|
|
501
|
+
return encodeFrame({
|
|
502
|
+
opcode,
|
|
503
|
+
payload,
|
|
504
|
+
fin: true,
|
|
505
|
+
mask: true,
|
|
506
|
+
returnParts: false,
|
|
507
|
+
usePool: false,
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Ultra-fast zero-parse JSON string field extractor directly on a raw Buffer.
|
|
513
|
+
* Avoids `JSON.parse()` on massive payloads (e.g., 20KB GUILD_UPDATE) when only 1-2 fields are needed.
|
|
514
|
+
*
|
|
515
|
+
* Example:
|
|
516
|
+
* const idPrefix = Buffer.from('"id":"');
|
|
517
|
+
* const id = extractString(rawBuf, idPrefix);
|
|
518
|
+
*
|
|
519
|
+
* @param {Buffer} buf - Raw UTF-8 message Buffer
|
|
520
|
+
* @param {Buffer|string} prefix - Exact prefix before the string value (e.g., `"id":"` or `"vanity_url_code":"`)
|
|
521
|
+
* @param {number} [startOffset=0] - Optional byte offset to start searching from
|
|
522
|
+
* @returns {string|null}
|
|
523
|
+
*/
|
|
524
|
+
function extractString(buf, prefix, startOffset = 0) {
|
|
525
|
+
const idx = buf.indexOf(prefix, startOffset);
|
|
526
|
+
if (idx === -1) return null;
|
|
527
|
+
const prefixLen = Buffer.isBuffer(prefix) ? prefix.length : Buffer.byteLength(prefix);
|
|
528
|
+
const valStart = idx + prefixLen;
|
|
529
|
+
const quoteEnd = buf.indexOf(0x22, valStart); // 0x22 = '"'
|
|
530
|
+
if (quoteEnd === -1) return null;
|
|
531
|
+
return buf.toString('utf8', valStart, quoteEnd);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Ultra-fast zero-parse JSON integer/float field extractor directly on a raw Buffer.
|
|
536
|
+
*
|
|
537
|
+
* Example:
|
|
538
|
+
* const interval = extractNumber(rawBuf, '"heartbeat_interval":');
|
|
539
|
+
*
|
|
540
|
+
* @param {Buffer} buf - Raw UTF-8 message Buffer
|
|
541
|
+
* @param {Buffer|string} prefix - Exact prefix before the numeric value (e.g., `"heartbeat_interval":`)
|
|
542
|
+
* @param {number} [startOffset=0] - Optional byte offset to start searching from
|
|
543
|
+
* @returns {number|null}
|
|
544
|
+
*/
|
|
545
|
+
function extractNumber(buf, prefix, startOffset = 0) {
|
|
546
|
+
const idx = buf.indexOf(prefix, startOffset);
|
|
547
|
+
if (idx === -1) return null;
|
|
548
|
+
const prefixLen = Buffer.isBuffer(prefix) ? prefix.length : Buffer.byteLength(prefix);
|
|
549
|
+
let i = idx + prefixLen;
|
|
550
|
+
const len = buf.length;
|
|
551
|
+
|
|
552
|
+
// Skip optional whitespace
|
|
553
|
+
while (i < len && (buf[i] === 0x20 || buf[i] === 0x09)) i++;
|
|
554
|
+
|
|
555
|
+
let num = 0;
|
|
556
|
+
let hasDigits = false;
|
|
557
|
+
while (i < len) {
|
|
558
|
+
const c = buf[i];
|
|
559
|
+
if (c >= 0x30 && c <= 0x39) {
|
|
560
|
+
num = num * 10 + (c - 0x30);
|
|
561
|
+
hasDigits = true;
|
|
562
|
+
i++;
|
|
563
|
+
} else {
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return hasDigits ? num : null;
|
|
568
|
+
}
|
|
569
|
+
|
|
460
570
|
module.exports = {
|
|
461
571
|
WebSocketProtocolError,
|
|
462
572
|
applyMask,
|
|
463
573
|
encodeFrame,
|
|
464
574
|
prepareMessage,
|
|
575
|
+
prepareClientFrame,
|
|
576
|
+
extractString,
|
|
577
|
+
extractNumber,
|
|
465
578
|
FrameParser,
|
|
466
579
|
};
|
package/src/index.d.ts
CHANGED
|
@@ -40,6 +40,9 @@ export interface SendOptions {
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
export function prepareMessage(data: string | Buffer | Uint8Array, options?: { binary?: boolean }): Buffer;
|
|
43
|
+
export function prepareClientFrame(data: string | Buffer | Uint8Array, options?: { binary?: boolean }): Buffer;
|
|
44
|
+
export function extractString(buf: Buffer, prefix: Buffer | string, startOffset?: number): string | null;
|
|
45
|
+
export function extractNumber(buf: Buffer, prefix: Buffer | string, startOffset?: number): number | null;
|
|
43
46
|
|
|
44
47
|
export class WalterConnection extends EventEmitter {
|
|
45
48
|
id: number;
|
|
@@ -135,6 +138,10 @@ export interface WalterClientOptions {
|
|
|
135
138
|
protocols?: string | string[];
|
|
136
139
|
maxPayload?: number;
|
|
137
140
|
handshakeTimeout?: number;
|
|
141
|
+
skipUTF8Validation?: boolean;
|
|
142
|
+
rawBuffer?: boolean;
|
|
143
|
+
tlsOptions?: Record<string, any>;
|
|
144
|
+
sessionReuse?: boolean;
|
|
138
145
|
autoReconnect?: boolean;
|
|
139
146
|
reconnectInterval?: number;
|
|
140
147
|
maxReconnectInterval?: number;
|
|
@@ -150,14 +157,19 @@ export class WalterClient extends EventEmitter {
|
|
|
150
157
|
static WalterClient: typeof WalterClient;
|
|
151
158
|
static WalterConnection: typeof WalterConnection;
|
|
152
159
|
static prepareMessage: typeof prepareMessage;
|
|
160
|
+
static prepareClientFrame: typeof prepareClientFrame;
|
|
161
|
+
static extractString: typeof extractString;
|
|
162
|
+
static extractNumber: typeof extractNumber;
|
|
153
163
|
static CONNECTING: 0;
|
|
154
164
|
static OPEN: 1;
|
|
155
165
|
static CLOSING: 2;
|
|
156
166
|
static CLOSED: 3;
|
|
157
167
|
|
|
158
|
-
url: URL;
|
|
168
|
+
url: URL | string;
|
|
159
169
|
readyState: 0 | 1 | 2 | 3;
|
|
160
170
|
protocol: string | null;
|
|
171
|
+
_socket?: net.Socket;
|
|
172
|
+
socket?: net.Socket;
|
|
161
173
|
onopen: ((event: { target: WalterClient }) => void) | null;
|
|
162
174
|
onmessage: ((event: { data: string | Buffer; isBinary: boolean; target: WalterClient }) => void) | null;
|
|
163
175
|
onclose: ((event: { code: number; reason: string; target: WalterClient }) => void) | null;
|
|
@@ -165,6 +177,8 @@ export class WalterClient extends EventEmitter {
|
|
|
165
177
|
|
|
166
178
|
constructor(url: string | URL, options?: WalterClientOptions);
|
|
167
179
|
send(data: string | Buffer | Uint8Array, options?: SendOptions | ((err?: Error) => void), callback?: (err?: Error) => void): void;
|
|
180
|
+
sendFrame(preMaskedFrame: Buffer, callback?: (err?: Error) => void): void;
|
|
181
|
+
prepareFrame(data: string | Buffer | Uint8Array, options?: { binary?: boolean }): Buffer;
|
|
168
182
|
sendJSON(obj: unknown, callback?: (err?: Error) => void): void;
|
|
169
183
|
ping(data?: Buffer | string, callback?: (err?: Error) => void): void;
|
|
170
184
|
pong(data?: Buffer | string, callback?: (err?: Error) => void): void;
|
package/src/index.js
CHANGED
|
@@ -3,7 +3,16 @@
|
|
|
3
3
|
const { WalterServer, computeAcceptKey, isValidSecWebSocketKey } = require('./server');
|
|
4
4
|
const { WalterClient } = require('./client');
|
|
5
5
|
const { WalterConnection } = require('./connection');
|
|
6
|
-
const {
|
|
6
|
+
const {
|
|
7
|
+
FrameParser,
|
|
8
|
+
encodeFrame,
|
|
9
|
+
prepareMessage,
|
|
10
|
+
prepareClientFrame,
|
|
11
|
+
extractString,
|
|
12
|
+
extractNumber,
|
|
13
|
+
applyMask,
|
|
14
|
+
WebSocketProtocolError,
|
|
15
|
+
} = require('./frame');
|
|
7
16
|
const { GUID, READY_STATES, OPCODES, CLOSE_CODES, isValidCloseCode } = require('./constants');
|
|
8
17
|
|
|
9
18
|
// Drop-in compatibility with standard `ws` package (`const WebSocket = require('walter-ws')`)
|
|
@@ -16,6 +25,9 @@ WalterClient.WalterConnection = WalterConnection;
|
|
|
16
25
|
WalterClient.FrameParser = FrameParser;
|
|
17
26
|
WalterClient.encodeFrame = encodeFrame;
|
|
18
27
|
WalterClient.prepareMessage = prepareMessage;
|
|
28
|
+
WalterClient.prepareClientFrame = prepareClientFrame;
|
|
29
|
+
WalterClient.extractString = extractString;
|
|
30
|
+
WalterClient.extractNumber = extractNumber;
|
|
19
31
|
WalterClient.applyMask = applyMask;
|
|
20
32
|
WalterClient.computeAcceptKey = computeAcceptKey;
|
|
21
33
|
WalterClient.isValidSecWebSocketKey = isValidSecWebSocketKey;
|