Skip to content

Commit

Permalink
stream: add isDisturbed helper
Browse files Browse the repository at this point in the history
Adds a helper util used to determine whether a stream has been
disturbed (read or cancelled).

Refs: nodejs#39627
  • Loading branch information
ronag committed Aug 2, 2021
1 parent 6ca23d7 commit 3bd9a53
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/internal/streams/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const {
} = primordials;

const kDestroyed = Symbol('kDestroyed');
const kIsDisturbed = Symbol('kIsDisturbed');

function isReadableNodeStream(obj) {
return !!(
Expand Down Expand Up @@ -195,8 +196,20 @@ function willEmitClose(stream) {
);
}

function isDisturbed(stream) {
const state = stream && stream._readableState;
return stream && (
stream.readableDidRead ||
isDestroyed(stream) ||
stream[kIsDisturbed] ||
(state && state.endEmitted)
);
}

module.exports = {
kDestroyed,
isDisturbed,
kIsDisturbed,
isClosed,
isDestroyed,
isFinished,
Expand Down
9 changes: 9 additions & 0 deletions lib/internal/webstreams/readablestream.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ const {
queueMicrotask,
} = require('internal/process/task_queues');

const {
kIsDisturbed,
} = require('internal/stream/utils');

const {
ArrayBufferViewGetBuffer,
ArrayBufferViewGetByteLength,
Expand Down Expand Up @@ -200,6 +204,7 @@ class ReadableStream {
promise: undefined,
}
};

// The spec requires handling of the strategy first
// here. Specifically, if getting the size and
// highWaterMark from the strategy fail, that has
Expand Down Expand Up @@ -232,6 +237,10 @@ class ReadableStream {
return makeTransferable(this);
}

get [kIsDisturbed]() {
return this[kState].disturbed;
}

/**
* @readonly
* @type {boolean}
Expand Down
1 change: 1 addition & 0 deletions lib/stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const internalBuffer = require('internal/buffer');
const promises = require('stream/promises');

const Stream = module.exports = require('internal/streams/legacy').Stream;
Stream.isDisturbed = require('internal/streams/utils').isDisturbed;
Stream.Readable = require('internal/streams/readable');
Stream.Writable = require('internal/streams/writable');
Stream.Duplex = require('internal/streams/duplex');
Expand Down

0 comments on commit 3bd9a53

Please sign in to comment.