smartstream/test/backpressure.ts

62 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-11-12 21:34:55 +00:00
import { SmartDuplex, type ISmartDuplexOptions, StreamWrapper } from '../ts/index.js';
import * as smartdelay from '@push.rocks/smartdelay';
async function testBackpressure() {
const stream1 = new SmartDuplex({
2023-11-13 16:43:15 +00:00
name: 'stream1',
2023-11-12 21:34:55 +00:00
objectMode: true,
handleBackpressure: true,
writeFunction: async (chunk, tools) => {
console.log(`processed chunk ${chunk} in stream 1`);
return chunk; // Fast processing
}
});
const stream2 = new SmartDuplex({
2023-11-13 16:43:15 +00:00
name: 'stream2',
2023-11-12 21:34:55 +00:00
objectMode: true,
handleBackpressure: true,
writeFunction: async (chunk, tools) => {
2023-11-13 16:43:15 +00:00
await new Promise(resolve => setTimeout(resolve, 1)); // Slow processing
2023-11-12 21:34:55 +00:00
console.log(`processed chunk ${chunk} in stream 2`);
return chunk;
}
}); // This stream processes data more slowly
const stream3 = new SmartDuplex({
2023-11-13 16:43:15 +00:00
objectMode: true,
name: 'stream3',
handleBackpressure: true,
2023-11-12 21:34:55 +00:00
writeFunction: async (chunk, tools) => {
2023-11-13 16:43:15 +00:00
await new Promise(resolve => setTimeout(resolve, 200)); // Slow processing
console.log(`processed chunk ${chunk} in stream 3`);
2023-11-12 21:34:55 +00:00
}
});
stream1.pipe(stream2).pipe(stream3);
let backpressured = false;
2023-11-13 16:43:15 +00:00
for (let i = 0; i < 1000; i++) {
2023-11-12 21:34:55 +00:00
const canContinue = stream1.write(`Chunk ${i}`, 'utf8');
if (!canContinue) {
backpressured = true;
console.log(`Backpressure at chunk ${i}`);
}
}
stream1.end();
stream1.on('finish', () => {
console.log('Stream 1 finished processing.');
});
stream2.on('finish', () => {
console.log('Stream 2 finished processing.');
});
stream3.on('finish', () => {
console.log('Stream 3 finished processing.');
if (!backpressured) {
console.log('No backpressure was observed.');
}
});
}
testBackpressure();