Skip to content

Commit

Permalink
add websocket-stream
Browse files Browse the repository at this point in the history
  • Loading branch information
tsctx committed Sep 9, 2024
1 parent 068520e commit 5e86207
Showing 1 changed file with 34 additions and 9 deletions.
43 changes: 34 additions & 9 deletions benchmarks/websocket-benchmark.mjs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
// @ts-check

import { bench } from './_util/runner.js'
import { WebSocket } from '../index.js'
import * as undici from '../index.js'
import { WebSocket as WsWebSocket } from 'ws'

/**
* @typedef {object} WebSocketImpl
* @property {(buffer: Uint8Array | string) => void} send
* @property {(code?: number, reason?: string) => void} close
* @property {string} binaryType
*/
const {
WebSocket,
// @ts-ignore https://github.com/nodejs/undici/pull/3560
WebSocketStream
} = undici

/**
* @type {Record<string, { fn: (ws: WebSocketImpl, binary: string | Uint8Array) => import('./_util/runner.js').BenchMarkHandler; connect: (url: string) => Promise<WebSocketImpl>; binaries: (string | Uint8Array)[] }>}
* @type {Record<string, { fn: (ws: any, binary: string | Uint8Array) => import('./_util/runner.js').BenchMarkHandler; connect: (url: string) => Promise<any>; binaries: (string | Uint8Array)[] }>}
*/
const experiments = {}
/**
Expand All @@ -21,7 +20,7 @@ const experiments = {}
const experimentsInfo = {}

/**
* @type {WebSocketImpl[]}
* @type {any[]}
*/
const connections = []

Expand Down Expand Up @@ -77,6 +76,32 @@ experiments['undici'] = {
binaries
}

if (typeof WebSocketStream === 'function') {
experiments['undici - stream'] = {
fn: (ws, binary) => {
const { readable, writable } = ws
/** @type {ReadableStreamDefaultReader<string | Uint8Array>} */
const reader = readable.getReader()
/** @type {WritableStreamDefaultWriter<string | BufferSource>} */
const writer = writable.getWriter()
return async (ev) => {
ev.start()
await writer.write(binary)
await reader.read()
ev.end()
}
},

connect: async (url) => {
const ws = new WebSocketStream(url)

return await ws.opened
},

binaries
}
}

experiments['ws'] = {
fn: (ws, binary) => {
if (!(ws instanceof WsWebSocket)) {
Expand Down

0 comments on commit 5e86207

Please sign in to comment.