I’m authoring an Open Telemetry instrumentation library for internal use – we use streams – a lot- and because of their proneness to blow up in your face, we’d like to temporarily instrument them as much as possible so we can gain insights on their behaviour in the wild.
One thing I’ve always found tricky, is how to listen to “write” events of Writable
streams – similar to how Readable.on('data', fn)
works.
what I’ve resorted to over the years was this simplistic monkey-patch of write
method, like so:
app.get('/foo', (req, res) => {
// count invocations of 'write'
let count = 0
const _write = res.write
res.write = function(chunk) {
++count
_write(chunk)
}
})
This works – but it always feels particularly awkward and I wonder if there’s a more reasonable way to go about it – I’m not entirely clear on how Node response internals work – does it expect me to provide all 3 arguments like it’s documented here? Do I also need to return _write(chunk)
because it participates in the backpressure control mechanism?
Hard to tell from the documentation and the last thing I want is to rewire a response stream incorrectly.
I could eventually dive into Express internals and find out but I wonder if there a more official way of tackling this.
Sidenote: I’m not going insane – I’m not suggesting I want to be sending a Telemetry event for every single write call – the plan is to log first/last and perhaps some avg duration between calls.