Last active
September 15, 2022 00:21
-
-
Save jclab-joseph/d4258a4f8c2d19c15ccc8dfb27540f16 to your computer and use it in GitHub Desktop.
node stream backpressure test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const streams = require('stream'); | |
const StreamLimiter = require('throttle'); | |
const uuid = require('uuid'); | |
class TestDuplex extends streams.Duplex { | |
nextWrite = null | |
constructor() { | |
super({ | |
highWaterMark: 128 | |
}); | |
} | |
_read(size) { | |
if (this.nextWrite) { | |
this.nextWrite(); | |
this.nextWrite = null; | |
} | |
} | |
_write(chunk, encoding, callback) { | |
const ret = this.push(chunk); | |
if (ret) { | |
callback(); | |
} else { | |
console.log('internal buffer is full'); | |
this.nextWrite = () => { | |
callback(); | |
} | |
} | |
} | |
} | |
const testDuplex = new TestDuplex(); | |
const deque = []; | |
const doit = () => { | |
const a = Buffer.from(uuid.v4()); | |
deque.push(...a); | |
testDuplex.write(a, () => { | |
setImmediate(() => doit()); | |
}); | |
} | |
doit(); | |
testDuplex | |
.pipe(new StreamLimiter(128 * 8)) | |
.on('data', (data) => { | |
for (let i=0; i<data.length; i++) { | |
const a = data[i]; | |
const b = deque.shift(); | |
if (a !== b) { | |
throw new Error(`WRONG DATA ${a} !== ${b}`); | |
} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
WARNING
DO NOT WRITE AGAIN BEFORE WRITE IS DONE.
BELOW IS NOT WORKING. (
this.nextWrite
is overwritten.)