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 6 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
44 changes: 43 additions & 1 deletion lib/web/websocket/frame.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict'

const { maxUnsigned16Bit } = require('./constants')
const { maxUnsigned16Bit, opcodes } = require('./constants')

const BUFFER_SIZE = 8 * 1024

Expand Down Expand Up @@ -89,6 +89,48 @@ class WebsocketFrameSend {

return buffer
}

/**
* @param {Uint8Array} buffer
*/
static createFastTextFrame (buffer) {
const maskKey = generateMask()

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 */ | opcodes.TEXT /* opcode TEXT */
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 @@ -31,16 +31,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