Skip to content

Commit

Permalink
fix(hash-stream-node): throw error if non-file readableStream is flow…
Browse files Browse the repository at this point in the history
…ing (#3341)
  • Loading branch information
trivikr committed Feb 22, 2022
1 parent 0ad6f73 commit 76df645
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
24 changes: 16 additions & 8 deletions packages/hash-stream-node/src/readableStreamHasher.spec.ts
Expand Up @@ -53,11 +53,7 @@ describe(readableStreamHasher.name, () => {
});

it("creates a copy in case of fileStream", () => {
(fsCreateReadStream as jest.Mock).mockReturnValue(
new Readable({
read: (size) => {},
})
);
(fsCreateReadStream as jest.Mock).mockReturnValue(new Readable({ read: (size) => {} }));
(isFileStream as unknown as jest.Mock).mockReturnValue(true);

const fsReadStream = createReadStream(__filename);
Expand All @@ -68,9 +64,7 @@ describe(readableStreamHasher.name, () => {
});

it("computes hash for a readable stream", async () => {
const readableStream = new Readable({
read: (size) => {},
});
const readableStream = new Readable({ read: (size) => {} });
const hashPromise = readableStreamHasher(mockHashCtor, readableStream);

// @ts-ignore Property '_readableState' does not exist on type 'Readable'.
Expand All @@ -92,6 +86,20 @@ describe(readableStreamHasher.name, () => {
expect(mockHashCalculatorEnd).toHaveBeenCalledTimes(1);
});

it("throws if readable stream is not a file stream and has started reading", async () => {
const readableStream = new Readable({ read: (size) => {} });
// Simulate readableFlowing to true.
readableStream.resume();

const expectedError = new Error("Unable to calculate hash for flowing readable stream");
try {
readableStreamHasher(mockHashCtor, readableStream);
fail(`expected ${expectedError}`);
} catch (error) {
expect(error).toStrictEqual(expectedError);
}
});

it("throws error if readable stream throws error", async () => {
const readableStream = new Readable({
read: (size) => {},
Expand Down
6 changes: 5 additions & 1 deletion packages/hash-stream-node/src/readableStreamHasher.ts
Expand Up @@ -6,7 +6,11 @@ import { HashCalculator } from "./HashCalculator";
import { isFileStream } from "./isFileStream";

export const readableStreamHasher: StreamHasher<Readable> = (hashCtor: HashConstructor, readableStream: Readable) => {
// ToDo: throw if readableStream is already flowing and it's copy can't be created.
// Throw if readableStream is already flowing and it's not a file stream.
if (!isFileStream(readableStream) && readableStream.readableFlowing !== null) {
throw new Error("Unable to calculate hash for flowing readable stream");
}

const streamToPipe = isFileStream(readableStream) ? fsCreateReadStream(readableStream) : readableStream;

const hash = new hashCtor();
Expand Down

0 comments on commit 76df645

Please sign in to comment.