Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

websocket: add fast-path for string input #3395

Merged
merged 7 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions lib/web/websocket/frame.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,49 @@ class WebsocketFrameSend {

return buffer
}

/**
* @param {string | Uint8Array} body
*/
static createFastTextFrame (body) {
const maskKey = generateMask()

const buffer = typeof body === 'string' ? Buffer.from(body) : body
tsctx marked this conversation as resolved.
Show resolved Hide resolved
const bodyLength = buffer.length

// mask body
for (let i = 0; i < bodyLength; ++i) {
buffer[i] ^= maskKey[i & 3]
}

let payloadLength = bodyLength
let offset = 6

if (bodyLength > maxUnsigned16Bit) {
offset += 8 // payload length is next 8 bytes
payloadLength = 127
} else if (bodyLength > 125) {
offset += 2 // payload length is next 2 bytes
payloadLength = 126
}
const head = Buffer.allocUnsafeSlow(offset)

head[0] = 0x80 /* FIN */ | 0x1 /* opcode TEXT */
tsctx marked this conversation as resolved.
Show resolved Hide resolved
head[1] = payloadLength | 0x80 /* MASK */
head[offset - 4] = maskKey[0]
head[offset - 3] = maskKey[1]
head[offset - 2] = maskKey[2]
head[offset - 1] = maskKey[3]

if (payloadLength === 126) {
head.writeUInt16BE(bodyLength, 2)
} else if (payloadLength === 127) {
head[2] = head[3] = 0
head.writeUIntBE(bodyLength, 4, 6)
}

return [head, buffer]
}
}

module.exports = {
Expand Down
17 changes: 13 additions & 4 deletions lib/web/websocket/sender.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,25 @@ class SendQueue {

add (item, cb, hint) {
if (hint !== sendHints.blob) {
const frame = createFrame(item, hint)
if (!this.#running) {
// fast-path
this.#socket.write(frame, cb)
// TODO(@tsctx): support fast-path for string on running
if (hint === sendHints.string) {
tsctx marked this conversation as resolved.
Show resolved Hide resolved
// special fast-path for string
const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item)
this.#socket.cork()
this.#socket.write(head)
this.#socket.write(body, cb)
this.#socket.uncork()
} else {
// direct writing
this.#socket.write(createFrame(item, hint), cb)
}
} else {
/** @type {SendQueueNode} */
const node = {
promise: null,
callback: cb,
frame
frame: createFrame(item, hint)
}
this.#queue.push(node)
}
Expand Down
Loading