Skip to content

Commit

Permalink
websocket: improve performance of generate mask
Browse files Browse the repository at this point in the history
  • Loading branch information
tsctx committed May 5, 2024
1 parent 5d54543 commit 61fd2e8
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 8 deletions.
22 changes: 22 additions & 0 deletions benchmarks/websocket/generate-mask.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { randomFillSync, randomBytes } from 'node:crypto'
import { bench, group, run } from 'mitata'

const BUFFER_SIZE = 16384

const buf = randomFillSync(Buffer.allocUnsafe(BUFFER_SIZE), 0, BUFFER_SIZE)
let bufIdx = 0

function generateMask () {
if (bufIdx + 4 > BUFFER_SIZE) {
bufIdx = 0
randomFillSync(buf, 0, BUFFER_SIZE)
}
return [buf[bufIdx++], buf[bufIdx++], buf[bufIdx++], buf[bufIdx++]]
}

group('generate', () => {
bench('generateMask', () => generateMask())
bench('crypto.randomBytes(4)', () => randomBytes(4))
})

await run()
33 changes: 25 additions & 8 deletions lib/web/websocket/frame.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,43 @@

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

const BUFFER_SIZE = 16386

/** @type {import('crypto')} */
let crypto
let buffer = null
let bufIdx = 0

try {
crypto = require('node:crypto')
/* c8 ignore next 3 */
} catch {

}

function generateMask () {
if (buffer === null) {
buffer = crypto.randomFillSync(Buffer.allocUnsafe(BUFFER_SIZE), 0, BUFFER_SIZE)
}
if (bufIdx + 4 > BUFFER_SIZE) {
bufIdx = 0
crypto.randomFillSync(buffer, 0, BUFFER_SIZE)
}
return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]]
}

class WebsocketFrameSend {
/**
* @param {Buffer|undefined} data
*/
constructor (data) {
this.frameData = data
this.maskKey = crypto.randomBytes(4)
}

createFrame (opcode) {
const bodyLength = this.frameData?.byteLength ?? 0
const frameData = this.frameData
const maskKey = generateMask()
const bodyLength = frameData?.byteLength ?? 0

/** @type {number} */
let payloadLength = bodyLength // 0-125
Expand All @@ -43,10 +60,10 @@ class WebsocketFrameSend {
buffer[0] = (buffer[0] & 0xF0) + opcode // opcode

/*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */
buffer[offset - 4] = this.maskKey[0]
buffer[offset - 3] = this.maskKey[1]
buffer[offset - 2] = this.maskKey[2]
buffer[offset - 1] = this.maskKey[3]
buffer[offset - 4] = maskKey[0]
buffer[offset - 3] = maskKey[1]
buffer[offset - 2] = maskKey[2]
buffer[offset - 1] = maskKey[3]

buffer[1] = payloadLength

Expand All @@ -61,8 +78,8 @@ class WebsocketFrameSend {
buffer[1] |= 0x80 // MASK

// mask body
for (let i = 0; i < bodyLength; i++) {
buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]
for (let i = 0; i < bodyLength; ++i) {
buffer[offset + i] = frameData[i] ^ maskKey[i & 3]
}

return buffer
Expand Down

0 comments on commit 61fd2e8

Please sign in to comment.