fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 27s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 29s

The outbound pump pulled a @Ws handler's iterator as fast as it yielded,
whatever the peer read. With a slow client, 10,000 frames of 64 KiB were
all pulled at once and sat in the send buffer: 640 MiB.

WsSocket gains one optional member, drained(): it resolves once the
socket's send buffer is at or below the adapter's high-water mark
(WS_HIGH_WATER_MARK, 1 MiB, internal), or the socket has closed. The
pump awaits it before each pull, so the buffer peaks at the mark plus
one frame. A close ends the wait and the abort path runs the iterator's
return(), as before. A socket without drained() is never waited on.

Per runtime:
- Node: ws.bufferedAmount, released by each send's write callback;
- Bun: getBufferedAmount(), released by the server's drain callback;
- Deno: polls bufferedAmount every 10 ms, only while over the mark;
- workerd reports no buffered amount, so the edge never waits.

The Deno poll also waits while the socket is CONNECTING. Deno hands the
socket over before it opens, and a handler that yielded at once had its
first value pulled into a socket that was not open yet. The pump then
gave up, so the client saw no frame and a 1005 close.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-23 00:29:41 -05:00
1 parent 3455b421a4
commit 1603bcca53
10 files changed
+616 -8

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
// #41 (CARD-26, D23) on Bun: the outbound pump waits while the socket is backed up. Bun has no
// `bufferedAmount` property; the adapter reads `getBufferedAmount()` and waits on `drain`.
// Node twin: test/ws-backpressure.test.ts, which explains the cases.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Ws, Module } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { rawWs } from '../helpers/raw-ws.ts';
const FRAMES = 10_000;
const FRAME = 64 * 1024;
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const state = { pulled: 0, returned: false };
@Route('/bp')
class Flood {
@Ws('/flood')
flood() {
return (async function* () {
try {
for (let i = 0; i < FRAMES; i++) {
state.pulled++;
yield frame(i);
}
} finally {
state.returned = true;
}
})();
}
}
@Module({ mountpoint: '/', controllers: [Flood] })
class M {}
async function serve() {
state.pulled = 0;
state.returned = false;
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
return { server, port: server.port };
}
test('serveBun: ws outbound stops pulling while the client is not reading, then delivers in order (T1)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
const stalled = state.pulled;
await sleep(200);
expect(state.pulled).toBe(stalled);
expect(stalled).toBeLessThan(FRAMES / 10);
expect(await client.readAll(FRAMES)).toEqual({ received: FRAMES, inOrder: true });
expect(state.pulled).toBe(FRAMES);
client.destroy();
} finally {
server.stop(true);
}
}, 60_000);
test('serveBun: ws outbound ends the wait and calls return() when the client goes away (T2)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
expect(state.pulled).toBeLessThan(FRAMES / 10);
client.destroy();
await sleep(300);
expect(state.returned).toBe(true);
expect(state.pulled).toBeLessThan(FRAMES / 10);
} finally {
server.stop(true);
}
}, 60_000);
+114
View File
@@ -0,0 +1,114 @@
// #41 (CARD-26, D23) on Deno: the outbound pump waits while the socket is backed up. Deno's
// WebSocket fires no drain event, so the adapter polls `bufferedAmount` while over the mark.
// Node twin: test/ws-backpressure.test.ts, which explains the cases.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assert, assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Ws, Module } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { rawWs } from '../helpers/raw-ws.ts';
const FRAMES = 10_000;
const FRAME = 64 * 1024;
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const state = { pulled: 0, returned: false };
@Route('/bp')
class Flood {
@Ws('/flood')
flood() {
return (async function* () {
try {
for (let i = 0; i < FRAMES; i++) {
state.pulled++;
yield frame(i);
}
} finally {
state.returned = true;
}
})();
}
}
@Route('/early')
class Early {
// Yields before Deno's socket has left CONNECTING. The pump used to pull 'hi', find the socket
// not open, and give up: the client got no frame and a close without a code (1005).
@Ws('/hi')
hi() {
return (async function* () {
yield 'hi';
await new Promise<never>(() => {});
})();
}
}
@Module({ mountpoint: '/', controllers: [Flood, Early] })
class M {}
async function serve() {
state.pulled = 0;
state.returned = false;
let port = 0;
const server = await serveDeno(createApp({ modules: [M] }), {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await sleep(50);
return { server, port };
}
Deno.test('serveDeno: ws outbound stops pulling while the client is not reading, then delivers in order (T1)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
const stalled = state.pulled;
await sleep(200);
assertEquals(state.pulled, stalled);
assert(stalled < FRAMES / 10, `pulled ${stalled} of ${FRAMES} with nobody reading`);
assertEquals(await client.readAll(FRAMES), { received: FRAMES, inOrder: true });
assertEquals(state.pulled, FRAMES);
client.destroy();
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: ws outbound ends the wait and calls return() when the client goes away (T2)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
assert(state.pulled < FRAMES / 10);
client.destroy();
await sleep(300);
assertEquals(state.returned, true);
assert(state.pulled < FRAMES / 10);
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: a ws route that yields at once still delivers its first frame', async () => {
const { server, port } = await serve();
try {
const first = await new Promise<string>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/early/hi`);
ws.onmessage = (e) => {
resolve(String(e.data));
ws.close();
};
ws.onclose = (e) => reject(new Error(`closed ${e.code} before any frame`));
});
assertEquals(first, 'hi');
} finally {
await server.shutdown();
}
});
+83
View File
@@ -0,0 +1,83 @@
// A WebSocket client over a bare `node:net` socket, for the backpressure tests (#41) on Deno and
// Bun. The platform `WebSocket` reads as fast as it can and cannot be told to stop; a TCP socket
// can be paused, which is the "client reads slowly" those tests need. Server frames are unmasked,
// and every frame these tests send is the same size, so frames are found by offset alone.
import net from 'node:net';
export interface RawWs {
/** Stop reading: the server's send buffer is all that can grow. */
pause(): void;
/** Resume reading; resolves once `count` frames have arrived, reporting whether they were in order. */
readAll(count: number): Promise<{ received: number; inOrder: boolean }>;
destroy(): void;
}
/**
* Opens `ws://127.0.0.1:<port><path>` and resolves once the 101 is in. Each server frame must be
* a text frame of exactly `payload` bytes (> 65535, so a 10-byte header) whose first 8 bytes are
* its zero-padded index.
*/
export function rawWs(port: number, path: string, payload: number): Promise<RawWs> {
const total = payload + 10;
const socket = net.connect(port, '127.0.0.1');
let head = '';
let upgraded = false;
let pos = 0;
let digits = '';
let received = 0;
let inOrder = true;
let onFrame = () => {};
const consume = (chunk: Uint8Array) => {
let i = 0;
while (i < chunk.length) {
if (pos < 18) {
if (pos === 0 && chunk[i] !== 0x81) inOrder = false;
if (pos >= 10) digits += String.fromCharCode(chunk[i]);
if (pos === 17) {
if (Number(digits) !== received) inOrder = false;
digits = '';
}
pos++;
i++;
} else {
const skip = Math.min(total - pos, chunk.length - i);
pos += skip;
i += skip;
}
if (pos === total) {
pos = 0;
received++;
onFrame();
}
}
};
return new Promise((resolve, reject) => {
socket.once('error', reject);
socket.on('data', (chunk: Uint8Array) => {
if (upgraded) return consume(chunk);
head += new TextDecoder('latin1').decode(chunk);
const end = head.indexOf('\r\n\r\n');
if (end < 0) return;
upgraded = true;
const rest = chunk.subarray(chunk.length - (head.length - end - 4));
resolve({
pause: () => socket.pause(),
readAll: (count) =>
new Promise((done) => {
onFrame = () => {
if (received === count) done({ received, inOrder });
};
socket.resume();
}),
destroy: () => socket.destroy(),
});
consume(rest);
});
socket.write(
`GET ${path} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
);
});
}
+109
View File
@@ -0,0 +1,109 @@
// #41 (CARD-26, D23): the outbound pump waits while the socket is backed up.
//
// Over a real `ws` server on Node: a route that can produce 10,000 frames of 64 KiB (640 MiB)
// for a client that has stopped reading. Without backpressure the pump pulls all of them into
// the send buffer at once; with it, it stops pulling after about the high-water mark plus what
// the kernel's socket buffers absorb. The Deno and Bun twins live in test/deno and test/bun; the
// exact "mark plus one frame" bound is pinned with a fake socket in ws-core.test.ts.
import { describe, it, expect } from 'vitest';
import WebSocket from 'ws';
import { createHttpServer, type WsRouteDef } from '../src/http';
const FRAMES = 10_000;
const FRAME = 64 * 1024;
/** Frame `i`: its index, zero-padded, then filler up to 64 KiB. */
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
const url = (server: import('http').Server, path: string) => {
const a = server.address();
if (a && typeof a === 'object') return `ws://127.0.0.1:${a.port}${path}`;
throw new Error('no address');
};
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
describe('ws outbound backpressure (#41)', () => {
it('stops pulling while the client is not reading, then delivers every frame in order (T1)', async () => {
let pulled = 0;
const wsRoutes: WsRouteDef[] = [
{
pattern: '/flood',
open: async () =>
(async function* () {
for (let i = 0; i < FRAMES; i++) {
pulled++;
yield frame(i);
}
})(),
},
];
const server = createHttpServer([], wsRoutes);
await new Promise<void>((resolve) => server.listen(0, resolve));
const client = new WebSocket(url(server, '/flood'));
await new Promise((resolve) => client.once('upgrade', resolve));
// The client stops reading from TCP: the server's send buffer is all that can grow.
(client as any)._socket.pause();
await sleep(300);
const stalled = pulled;
await sleep(200);
// Pulling has stopped, far short of the 10,000 frames on offer: about the 1 MiB mark plus the
// kernel's socket buffers. Before #41 every frame was pulled at once, 640 MiB in memory.
expect(pulled).toBe(stalled);
expect(stalled).toBeLessThan(FRAMES / 10);
let next = 0;
let inOrder = true;
const done = new Promise<void>((resolve) => {
client.on('message', (data) => {
if (data.toString('latin1', 0, 8) !== String(next).padStart(8, '0')) inOrder = false;
if (++next === FRAMES) resolve();
});
});
(client as any)._socket.resume();
await done;
expect(inOrder).toBe(true);
expect(pulled).toBe(FRAMES);
client.close();
server.close();
}, 60_000);
it('calls the iterator return() when the client goes away while the pump waits (T2)', async () => {
let pulled = 0;
let returned = false;
const wsRoutes: WsRouteDef[] = [
{
pattern: '/flood',
open: async () =>
(async function* () {
try {
for (let i = 0; i < FRAMES; i++) {
pulled++;
yield frame(i);
}
} finally {
returned = true;
}
})(),
},
];
const server = createHttpServer([], wsRoutes);
await new Promise<void>((resolve) => server.listen(0, resolve));
const client = new WebSocket(url(server, '/flood'));
await new Promise((resolve) => client.once('upgrade', resolve));
(client as any)._socket.pause();
await sleep(300);
expect(pulled).toBeLessThan(FRAMES / 10); // waiting, not finished
client.terminate();
await sleep(200);
expect(returned).toBe(true);
expect(pulled).toBeLessThan(FRAMES / 10);
server.close();
}, 30_000);
});
+103
View File
@@ -152,3 +152,106 @@ describe('runWsConnection correlation', () => {
expect(open.transport).toBe('ws');
});
});
describe('runWsConnection outbound backpressure (#41)', () => {
/** A fake socket with a send buffer that only empties when the test says so. */
function bufferedSocket(mark: number) {
const fake = fakeSocket();
let buffered = 0;
let wake: (() => void) | null = null;
const socket: WsSocket = Object.assign(Object.create(fake.socket), {
send: (d: string) => {
fake.sent.push(d);
buffered += d.length;
},
drained: () =>
buffered <= mark || fake.ac.signal.aborted
? Promise.resolve()
: new Promise<void>((resolve) => {
wake = resolve;
fake.ac.signal.addEventListener('abort', () => resolve(), { once: true });
}),
});
const flush = () => {
buffered = 0;
wake?.();
wake = null;
};
return { ...fake, socket, flush, buffered: () => buffered };
}
const flood = (count: number, size: number, onPull: () => void, onReturn = () => {}) => ({
pattern: '/ws',
open: async () =>
(async function* () {
try {
for (let i = 0; i < count; i++) {
onPull();
yield String(i).padStart(size, '0');
}
} finally {
onReturn();
}
})(),
});
it('pulls nothing more once the buffer is over the mark: it peaks at the mark plus one frame (T1)', async () => {
let pulled = 0;
const { socket, flush, buffered, sent } = bufferedSocket(10);
const run = runWsConnection(socket, req, { def: flood(100, 4, () => pulled++), params: {} });
await new Promise((resolve) => setTimeout(resolve, 10));
expect(pulled).toBe(3); // 4 + 4 + 4 = 12 > 10: waits after the third frame
expect(buffered()).toBeLessThanOrEqual(10 + 4);
while (pulled < 100) {
flush();
await new Promise((resolve) => setTimeout(resolve, 0));
}
flush();
await run;
expect(sent.map(Number)).toEqual([...Array(100).keys()]);
});
it('ends the wait on close and calls the iterator return(), without an unhandled rejection (T2)', async () => {
let pulled = 0;
let returned = false;
const unhandled: unknown[] = [];
const onUnhandled = (err: unknown) => unhandled.push(err);
process.on('unhandledRejection', onUnhandled);
try {
const { socket, ac } = bufferedSocket(0);
const run = runWsConnection(socket, req, {
def: flood(100, 4, () => pulled++, () => (returned = true)),
params: {},
});
await new Promise((resolve) => setTimeout(resolve, 10));
expect(pulled).toBe(1);
ac.abort(); // the peer went away
await run;
await new Promise((resolve) => setTimeout(resolve, 10));
expect(returned).toBe(true);
expect(pulled).toBe(1);
expect(unhandled).toEqual([]);
} finally {
process.off('unhandledRejection', onUnhandled);
}
});
it('never waits below the mark: drained() answers at once and every frame goes out (T3)', async () => {
let waits = 0;
const { socket, sent } = fakeSocket();
const counted: WsSocket = Object.assign(Object.create(socket), {
drained: () => {
waits++;
return Promise.resolve();
},
});
await runWsConnection(counted, req, { def: flood(50, 4, () => {}), params: {} });
expect(sent).toHaveLength(50);
expect(waits).toBe(51); // once before each pull, the last one being the pull that ends it
});
});