Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

stream: emit pipe and unpipe on readable #7243

Open
wants to merge 1 commit into from

6 participants

@tjfontaine
Owner

Prior to this commit, 'pipe' and 'unpipe' events would only be emitted
on the writable, i.e. the destination to where the readable was being
piped. Now 'pipe' and 'unpipe' will be emitted on both sides of a
pipeline.

Relatedly, if the unpipe was triggered by an error in the writable that
error is now passed to the unpipe event.

@tjfontaine tjfontaine stream: emit pipe and unpipe on readable
Prior to this commit, 'pipe' and 'unpipe' events would only be emitted
on the writable, i.e. the destination to where the readable was being
piped. Now 'pipe' and 'unpipe' will be emitted on both sides of a
pipeline.

Relatedly, if the unpipe was triggered by an error in the writable that
error is now passed to the unpipe event.
a6eb330
@Nodejs-Jenkins

Thank you for contributing this pull request! Here are a few pointers to make sure your submission will be considered for inclusion.

The following commiters were not found in the CLA:

  • Timothy J Fontaine

You can fix all these things without opening another issue.

Please see CONTRIBUTING.md for more information

@aajenkins
@vkurchatkin

And what about Duplex? If someone is listening for pipe it will be broken.

@tjfontaine
Owner

Can you be more specific about why it will be broken, or how the failures will be evidenced?

@vkurchatkin

In case like readable.pipe(duplex).pipe(writable) the pipe event will be emitted twice on duplex and a user may assume that two streams were piped into it

@jonathanong

could make the writable emit piped and unpiped, but that's not an option. for backwards compatibility reasons, we can make those the readable's events.

@indutny
Owner

@vkurchatkin it won't be broken, because it is emitted with a destination of .pipe() that was unpiped.

@jonathanong

oh that's true. that would create some headaches though because now you have to make sure the destination is the correct stream.

duplex.on('unpipe', function (dest) {
  if (dest !== this) return
  // blah blah
})

i think the pros outweight the cons.

@vkurchatkin

@jonathanong nah, you can't do that, see L581:

dest.emit('pipe', src);
src.emit('pipe', dest);

you need to check if argument is writable. But what if it's a duplex, what does that mean?

Anyway, it's definitely a breaking change.

@indutny
Owner

@vkurchatkin triple equals check will work just fine, you should just know what you are doing :) But if you are talking about pipe + unpipe events and how the info gets propagated to the stream - this sounds like an issue. @tjfontaine perhaps we could add another argument to them, just to let users know on which side the event was triggered?

@vkurchatkin

I guess I have to write a couple of tests to express my concerns)

@indutny
Owner

Yes, this would be really useful.

@vkurchatkin

First one:

var common = require('../common');
var assert = require('assert');

var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var Duplex = require('stream').Duplex;

function read () {}
function write (ch, enc, cb) { cb(); }

var readable = new Readable;
var writable = new Writable;
var duplex = new Duplex;

readable._read = duplex._read = read;
writable._write = duplex._write = write;

var pipes = 0;

duplex.on('pipe', function () { pipes++; });

readable.pipe(duplex).pipe(writable);

process.on('exit', function () {
  assert(pipes === 1);
});
@vkurchatkin

Second one:

var common = require('../common');
var assert = require('assert');

var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var Duplex = require('stream').Duplex;

function read () {}
function write (ch, enc, cb) { cb(); }

var readable = new Readable;
var writable = new Writable;
var duplex = new Duplex;

readable._read = duplex._read = read;
writable._write = duplex._write = write;

duplex.on('pipe', function (src) { 
  assert(src.read);
});

readable.pipe(duplex).pipe(writable);
@vkurchatkin

Third:

var common = require('../common');
var assert = require('assert');

var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var Duplex = require('stream').Duplex;

function read () {}
function write (ch, enc, cb) { cb(); }

var readable = new Readable;
var writable = new Duplex;
var duplex = new Duplex;

readable._read = duplex._read = writable._read = read;
writable._write = duplex._write = write;

duplex.on('pipe', function (src) { 
  if (src instanceof Readable) {
    assert(src === readable);
  }
});

readable.pipe(duplex).pipe(writable);
@vkurchatkin

The first two demonstrate how this can break existing code. The last one demonstrates, that in a listener we can't even reliably tell if the stream is piped, or piped into.

@vkurchatkin

Ok, and now a somehow real life example of a terrible thing, that can happen:

var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var Transform = require('stream').Transform;
var inherits = require('util').inherits;

function MyWritable () {
  Writable.call(this);

  var writable = this;

  this.on('pipe', function (src) {
    src.on('error', function (err) {
      writable.emit('error', err);
    });
  });
}

inherits(MyWritable, Writable);

MyWritable.prototype._write = function (chunk, encoding, callback) {
  process.nextTick(callback);
}

function MyTransform () {
  Transform.call(this);

  var transform = this;

  this.on('pipe', function (src) {
    src.on('error', function (err) {
      transform.emit('error', err);
    });
  });
}

inherits(MyTransform, Transform);

MyTransform.prototype._transform = function (chunk, encoding, callback) {
  process.nextTick(callback);
}

var readable = new Readable;
readable._read = function () {};

var transform = new MyTransform;
var writable = new MyWritable;

readable.pipe(transform).pipe(writable);

writable.on('error', function () {
  console.log('error caught');
});

readable.emit('error', new Error('err'));

On master: error caught, with this patch: RangeError: Maximum call stack size exceeded

@tjfontaine
Owner

Certainly glad to have the conversation around this.

Even before reading @indutny's comments I had been considering 'pipe' arguments to always be (readable, writable) that way you could know which side of the pipe you are by doing this === readable.

I only added the 'pipe' change because it felt weird to inform both sides of an 'unpipe' event but not 'pipe', in reality I care more about informing users of the disposition of the 'unpipe' than I care about informing them that they have been piped.

@vkurchatkin

Still one edge case left: duplex.pipe(duplex). I think other names is the best option.

@indutny
Owner

@vkurchatkin I think all this problems could be avoided with (readable, writable) arguments, as suggested by @tjfontaine . Anyway, this is an API change and we realize it.

@jonathanong jonathanong referenced this pull request in koajs/koa
Closed

better stream error handling #184

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Mar 4, 2014
  1. @tjfontaine

    stream: emit pipe and unpipe on readable

    tjfontaine authored
    Prior to this commit, 'pipe' and 'unpipe' events would only be emitted
    on the writable, i.e. the destination to where the readable was being
    piped. Now 'pipe' and 'unpipe' will be emitted on both sides of a
    pipeline.
    
    Relatedly, if the unpipe was triggered by an error in the writable that
    error is now passed to the unpipe event.
This page is out of date. Refresh to see the latest.
View
40 doc/api/stream.markdown
@@ -209,6 +209,43 @@ descriptor) has been closed. Not all streams will emit this.
Emitted if there was an error receiving data.
+#### Event: 'pipe'
+
+* `src` {[Writable][] Stream} destination stream to where this readable is
+piping.
+
+This is emitted whenever the `pipe()` method is called on the readable
+stream, adding the writable to its set of destinations.
+
+```javascript
+var writer = getWritableStreamSomehow();
+var reader = getReadableStreamSomehow();
+reader.on('pipe', function(dest) {
+ console.error('something is piping into the writer');
+ assert.equal(dest, writer);
+});
+reader.pipe(writer);
+```
+
+#### Event: 'unpipe'
+
+* `src` {[Writable][] Stream} The source stream that [unpiped][] this readable
+* `err` {Error} The error (if any) that triggered this unpipe event
+
+This is emitted whenever the [`unpipe()`][] method is called on a
+readable stream, removing the given writable from its set of destinations.
+
+```javascript
+var writer = getWritableStreamSomehow();
+var reader = getReadableStreamSomehow();
+reader.on('unpipe', function(dest, err) {
+ console.error('something has stopped piping into the writer');
+ assert.equal(dest, writer);
+});
+reader.pipe(writer);
+reader.unpipe(writer);
+```
+
#### readable.read([size])
* `size` {Number} Optional argument to specify how much data to read.
@@ -600,6 +637,7 @@ reader.pipe(writer);
#### Event: 'unpipe'
* `src` {[Readable][] Stream} The source stream that [unpiped][] this writable
+* `err` {Error} The error (if any) that triggered this unpipe event
This is emitted whenever the [`unpipe()`][] method is called on a
readable stream, removing this writable from its set of destinations.
@@ -607,7 +645,7 @@ readable stream, removing this writable from its set of destinations.
```javascript
var writer = getWritableStreamSomehow();
var reader = getReadableStreamSomehow();
-writer.on('unpipe', function(src) {
+writer.on('unpipe', function(src, err) {
console.error('something has stopped piping into the writer');
assert.equal(src, reader);
});
View
21 lib/_stream_readable.js
@@ -543,7 +543,7 @@ Readable.prototype.pipe = function(dest, pipeOpts) {
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
- unpipe();
+ unpipe(er);
dest.removeListener('error', onerror);
if (EE.listenerCount(dest, 'error') === 0)
dest.emit('error', er);
@@ -572,13 +572,14 @@ Readable.prototype.pipe = function(dest, pipeOpts) {
}
dest.once('finish', onfinish);
- function unpipe() {
+ function unpipe(er) {
debug('unpipe');
- src.unpipe(dest);
+ src.unpipe(dest, er);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
+ src.emit('pipe', dest);
// start the flow if it hasn't been started already.
if (!state.flowing) {
@@ -603,7 +604,13 @@ function pipeOnDrain(src) {
}
-Readable.prototype.unpipe = function(dest) {
+Readable.prototype._emitUnpipe = function(dest, err) {
+ dest.emit('unpipe', this, err);
+ this.emit('unpipe', dest, err);
+};
+
+
+Readable.prototype.unpipe = function(dest, err) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
@@ -624,7 +631,7 @@ Readable.prototype.unpipe = function(dest) {
state.pipesCount = 0;
state.flowing = false;
if (dest)
- dest.emit('unpipe', this);
+ this._emitUnpipe(dest, err);
return this;
}
@@ -639,7 +646,7 @@ Readable.prototype.unpipe = function(dest) {
state.flowing = false;
for (var i = 0; i < len; i++)
- dests[i].emit('unpipe', this);
+ this._emitUnpipe(dests[i], err);
return this;
}
@@ -653,7 +660,7 @@ Readable.prototype.unpipe = function(dest) {
if (state.pipesCount === 1)
state.pipes = state.pipes[0];
- dest.emit('unpipe', this);
+ this._emitUnpipe(dest, err);
return this;
};
View
59 test/simple/test-stream-readable-pipe-event.js
@@ -0,0 +1,59 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var common = require('../common');
+var assert = require('assert');
+
+var stream = require('stream');
+
+var reader = new stream.Readable();
+reader._read = function() {}
+
+var writer = new stream.Writable();
+writer._write = function() {}
+
+reader.on('pipe', common.mustCall(function(dest) {
+ assert.strictEqual(dest, writer);
+}));
+
+writer.on('pipe', common.mustCall(function(src) {
+ assert.strictEqual(src, reader);
+}));
+
+var originalError = new Error('we have an error');
+
+reader.on('unpipe', common.mustCall(function(dest, err) {
+ assert.strictEqual(dest, writer);
+ assert.strictEqual(err, originalError);
+}));
+
+writer.on('unpipe', common.mustCall(function(src, err) {
+ assert.strictEqual(src, reader);
+ assert.strictEqual(err, originalError);
+}));
+
+// listen here to avoid the EE throw on no listeners
+writer.on('error', function(err) {
+ assert.strictEqual(err, originalError);
+});
+
+reader.pipe(writer);
+writer.emit('error', originalError);
Something went wrong with that request. Please try again.