Skip to content

Commit

Permalink
stream: fix multiple Writable.destroy() calls
Browse files Browse the repository at this point in the history
Calling Writable.destroy() multiple times in the same tick
could cause an assertion error.

Fixes: nodejs#38189

PR-URL: nodejs#38221
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Nitzan Uziely <linkgoron@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
  • Loading branch information
ronag committed Apr 29, 2021
1 parent 8d4936d commit 6531b98
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/internal/streams/writable.js
Expand Up @@ -770,7 +770,11 @@ ObjectDefineProperties(Writable.prototype, {
const destroy = destroyImpl.destroy;
Writable.prototype.destroy = function(err, cb) {
const state = this._writableState;
if (!state.destroyed) {

// Invoke pending callbacks.
if (!state.destroyed &&
(state.bufferedIndex < state.buffered.length ||
state[kOnFinished].length)) {
process.nextTick(errorBuffer, state, new ERR_STREAM_DESTROYED('write'));
}
destroy.call(this, err, cb);
Expand Down
54 changes: 54 additions & 0 deletions test/parallel/test-stream-writable-destroy.js
Expand Up @@ -417,3 +417,57 @@ const assert = require('assert');
}));
write.write('asd');
}

{
const ac = new AbortController();
const write = addAbortSignal(ac.signal, new Writable({
write(chunk, enc, cb) { cb(); }
}));

write.on('error', common.mustCall((e) => {
assert.strictEqual(e.name, 'AbortError');
assert.strictEqual(write.destroyed, true);
}));
write.write('asd');
ac.abort();
}

{
const ac = new AbortController();
const write = new Writable({
signal: ac.signal,
write(chunk, enc, cb) { cb(); }
});

write.on('error', common.mustCall((e) => {
assert.strictEqual(e.name, 'AbortError');
assert.strictEqual(write.destroyed, true);
}));
write.write('asd');
ac.abort();
}

{
const signal = AbortSignal.abort();

const write = new Writable({
signal,
write(chunk, enc, cb) { cb(); }
});

write.on('error', common.mustCall((e) => {
assert.strictEqual(e.name, 'AbortError');
assert.strictEqual(write.destroyed, true);
}));
}

{
// Destroy twice
const write = new Writable({
write(chunk, enc, cb) { cb(); }
});

write.end(common.mustCall());
write.destroy();
write.destroy();
}

0 comments on commit 6531b98

Please sign in to comment.