20 Commits

Author SHA1 Message Date
Jerry Kurian
3c75ef88b4 Minor changes to types 2020-05-11 21:13:03 -04:00
Jerry Kurian
7113400cb1 version 2020-05-11 10:33:17 -04:00
Jerry Kurian
a42560edfc Rename construct 2020-05-08 16:21:20 -04:00
Jerry Kurian
58a95a91d0 Demux handles arrays by key 2020-05-08 15:58:31 -04:00
Jerry Kurian
71b03678ba Add chunk to constructor (#5)
* Add chunk to constructor

* Add test

* Bump version
2020-04-27 12:25:36 -04:00
Lewis Diamond
f661f9be6b Export DemuxOptions is necessary for publishing 2020-03-02 10:17:41 -05:00
Lewis Diamond
ed73bd2887 Adding collected 2020-03-02 10:09:46 -05:00
Lewis Diamond
2841f4e182 Merge pull request #4 from Jogogoplay/feature/demux-pipe
Allow demux to be piped ie muxed
2020-02-28 17:23:59 -05:00
Jerry Kurian
12efbec698 Update tests 2020-01-28 09:48:29 -05:00
Jerry Kurian
ce2bb55b24 Emit correct event 2020-01-27 16:10:00 -05:00
Jerry Kurian
2bbc5c9e0f types 2020-01-27 13:11:51 -05:00
Jerry Kurian
8856cb8d3b Update demux 2020-01-27 13:07:37 -05:00
Jerry Kurian
2b1308a605 use fromArray 2020-01-27 09:29:59 -05:00
Jerry Kurian
11ed6f81e7 remove console log 2020-01-26 10:43:33 -05:00
Jerry Kurian
cf719b25cf Fix broken test 2020-01-26 10:37:59 -05:00
Jerry Kurian
9c09957775 Add test for remux 2020-01-26 10:26:54 -05:00
Jerry Kurian
bff4e0d6ed Add remux options 2020-01-26 09:55:35 -05:00
Jerry Kurian
bd178ce2f0 Revert to old 2020-01-25 12:36:38 -05:00
Jerry Kurian
1227ce7095 Allow demux to be piped (mux) 2020-01-25 12:33:09 -05:00
Lewis Diamond
179d526c6c 2.0.0-alpha.1 2019-12-06 17:14:39 -05:00
13 changed files with 577 additions and 281 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "@jogogo/mhysa",
"version": "0.1.0-alpha.1",
"version": "2.0.0-alpha.4",
"description": "Streams and event emitter utils for Node.js",
"keywords": [
"promise",
@@ -35,9 +35,7 @@
"type": "git"
},
"scripts": {
"test": "NODE_PATH=src node node_modules/.bin/ava tests/*.spec.ts -e",
"test:debug": "NODE_PATH=src node inspect node_modules/ava/profile.js",
"test:all": "NODE_PATH=src node node_modules/.bin/ava",
"test": "ava",
"lint": "tslint -p tsconfig.json",
"validate:tslint": "tslint-config-prettier-check ./tslint.json",
"prepublishOnly": "yarn lint && yarn test && yarn tsc -d"
@@ -45,7 +43,7 @@
"dependencies": {},
"devDependencies": {
"@types/chai": "^4.1.7",
"@types/node": "^12.7.2",
"@types/node": "^12.12.15",
"@types/sinon": "^7.0.13",
"ava": "^2.4.0",
"chai": "^4.2.0",
@@ -60,7 +58,8 @@
},
"ava": {
"files": [
"tests/*.spec.ts"
"tests/*.spec.ts",
"tests/utils/*.spec.ts"
],
"sources": [
"src/**/*.ts"

View File

@@ -12,7 +12,9 @@ export function batch(
clearTimeout(timer);
}
timer = null;
if (buffer.length > 0) {
self.push(buffer);
}
buffer = [];
};
return new Transform({

View File

@@ -1,4 +1,5 @@
import { pipeline, TransformOptions, Transform } from "stream";
import { AllStreams, isReadable } from "../helpers";
import { PassThrough, pipeline, TransformOptions, Transform } from "stream";
export function compose(
streams: Array<
@@ -21,18 +22,6 @@ enum EventSubscription {
Self,
}
type AllStreams =
| NodeJS.ReadableStream
| NodeJS.ReadWriteStream
| NodeJS.WritableStream;
function isReadable(stream: AllStreams): stream is NodeJS.WritableStream {
return (
(stream as NodeJS.ReadableStream).pipe !== undefined &&
(stream as any).readable === true
);
}
export class Compose extends Transform {
private first: AllStreams;
private last: AllStreams;
@@ -45,11 +34,11 @@ export class Compose extends Transform {
options?: TransformOptions,
) {
super(options);
this.first = streams[0];
this.first = new PassThrough(options);
this.last = streams[streams.length - 1];
this.streams = streams;
pipeline(
streams,
[this.first, ...streams],
errorCallback ||
((error: any) => {
if (error) {

View File

@@ -1,99 +1,131 @@
import { WritableOptions, Writable } from "stream";
import { DuplexOptions, Duplex, Transform } from "stream";
enum EventSubscription {
Last = 0,
First,
All,
Self,
Unhandled,
}
const eventsTarget = {
close: EventSubscription.Self,
data: EventSubscription.All,
drain: EventSubscription.Self,
end: EventSubscription.Self,
error: EventSubscription.Self,
finish: EventSubscription.Self,
pause: EventSubscription.Self,
pipe: EventSubscription.Self,
readable: EventSubscription.Self,
resume: EventSubscription.Self,
unpipe: EventSubscription.Self,
};
import { isReadable } from "../helpers";
type DemuxStreams = NodeJS.WritableStream | NodeJS.ReadWriteStream;
export function demux(
construct: (destKey?: string) => DemuxStreams,
demuxBy: string | ((chunk: any) => string),
options?: WritableOptions,
): Writable {
return new Demux(construct, demuxBy, options);
export interface DemuxOptions extends DuplexOptions {
remultiplex?: boolean;
}
// @TODO handle pipe event ie) Multiplex
class Demux extends Writable {
export function demux(
pipelineConstructor: (
destKey?: string,
chunk?: any,
) => DemuxStreams | DemuxStreams[],
demuxBy: string | ((chunk: any) => string),
options?: DemuxOptions,
): Duplex {
return new Demux(pipelineConstructor, demuxBy, options);
}
class Demux extends Duplex {
private streamsByKey: {
[key: string]: DemuxStreams;
[key: string]: DemuxStreams[];
};
private demuxer: (chunk: any) => string;
private construct: (destKey?: string) => DemuxStreams;
private pipelineConstructor: (
destKey?: string,
chunk?: any,
) => DemuxStreams[];
private remultiplex: boolean;
private transform: Transform;
constructor(
construct: (destKey?: string) => DemuxStreams,
pipelineConstructor: (
destKey?: string,
chunk?: any,
) => DemuxStreams | DemuxStreams[],
demuxBy: string | ((chunk: any) => string),
options: WritableOptions = {},
options: DemuxOptions = {},
) {
super(options);
this.demuxer =
typeof demuxBy === "string" ? chunk => chunk[demuxBy] : demuxBy;
this.construct = construct;
this.pipelineConstructor = (destKey: string, chunk?: any) => {
const pipeline = pipelineConstructor(destKey, chunk);
return Array.isArray(pipeline) ? pipeline : [pipeline];
};
this.remultiplex =
options.remultiplex === undefined ? true : options.remultiplex;
this.streamsByKey = {};
this.transform = new Transform({
...options,
transform: (d, _, cb) => {
this.push(d);
cb(null);
},
});
this.on("unpipe", () => this._flush());
}
// tslint:disable-next-line
public _read(size: number) {}
public async _write(chunk: any, encoding: any, cb: any) {
const destKey = this.demuxer(chunk);
if (this.streamsByKey[destKey] === undefined) {
this.streamsByKey[destKey] = await this.construct(destKey);
const newPipelines = this.pipelineConstructor(destKey, chunk);
this.streamsByKey[destKey] = newPipelines;
newPipelines.forEach(newPipeline => {
if (this.remultiplex && isReadable(newPipeline)) {
(newPipeline as NodeJS.ReadWriteStream).pipe(
this.transform,
);
} else if (this.remultiplex) {
console.error(
`Pipeline construct for ${destKey} does not implement readable interface`,
);
}
if (!this.streamsByKey[destKey].write(chunk, encoding)) {
this.streamsByKey[destKey].once("drain", () => {
cb();
});
} else {
}
const pipelines = this.streamsByKey[destKey];
const pendingDrains: Array<Promise<any>> = [];
pipelines.forEach(pipeline => {
if (!pipeline.write(chunk, encoding)) {
pendingDrains.push(
new Promise(resolve => {
pipeline.once("drain", () => {
resolve();
});
}),
);
}
});
await Promise.all(pendingDrains);
cb();
}
public _flush() {
const pipelines: DemuxStreams[] = [].concat.apply(
[],
Object.values(this.streamsByKey),
);
const flushPromises: Array<Promise<void>> = [];
pipelines.forEach(pipeline => {
flushPromises.push(
new Promise(resolve => {
pipeline.once("end", () => {
resolve();
});
}),
);
});
pipelines.forEach(pipeline => pipeline.end());
Promise.all(flushPromises).then(() => {
this.push(null);
this.emit("end");
});
}
public on(event: string, cb: any) {
switch (eventsTarget[event]) {
case EventSubscription.Self:
super.on(event, cb);
break;
case EventSubscription.All:
Object.keys(this.streamsByKey).forEach(key =>
this.streamsByKey[key].on(event, cb),
public _destroy(error: any, cb: (error?: any) => void) {
const pipelines: DemuxStreams[] = [].concat.apply(
[],
Object.values(this.streamsByKey),
);
break;
default:
super.on(event, cb);
}
return this;
}
public once(event: string, cb: any) {
switch (eventsTarget[event]) {
case EventSubscription.Self:
super.once(event, cb);
break;
case EventSubscription.All:
Object.keys(this.streamsByKey).forEach(key =>
this.streamsByKey[key].once(event, cb),
);
break;
default:
super.once(event, cb);
}
return this;
pipelines.forEach(p => (p as any).destroy());
cb(error);
}
}

View File

@@ -1,3 +1,17 @@
export async function sleep(time: number): Promise<{} | null> {
return time > 0 ? new Promise(resolve => setTimeout(resolve, time)) : null;
}
export type AllStreams =
| NodeJS.ReadableStream
| NodeJS.ReadWriteStream
| NodeJS.WritableStream;
export function isReadable(
stream: AllStreams,
): stream is NodeJS.WritableStream {
return (
(stream as NodeJS.ReadableStream).pipe !== undefined &&
(stream as any).readable === true
);
}

View File

@@ -1,2 +1,6 @@
import mhysa from "./functions";
import * as _utils from "./utils";
export default mhysa;
// @TODO fix this with proper import export
export const utils = { ..._utils };

12
src/utils/collected.ts Normal file
View File

@@ -0,0 +1,12 @@
import { Transform } from "stream";
export function collected(stream: Transform): any {
return new Promise((resolve, reject) => {
stream.once("data", d => {
resolve(d);
});
stream.once("error", e => {
reject(e);
});
});
}

1
src/utils/index.ts Normal file
View File

@@ -0,0 +1 @@
export { collected } from "./collected";

View File

@@ -2,7 +2,7 @@ import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { batch } = mhysa({ objectMode: true });
const { batch, map, fromArray } = mhysa({ objectMode: true });
test.cb("batch() batches chunks together", t => {
t.plan(3);
@@ -57,3 +57,28 @@ test.cb("batch() yields a batch after the timeout", t => {
source.push(null);
}, 600 * 2);
});
test.cb(
"batch() yields all input data even when the last element(s) dont make a full batch",
t => {
const data = [1, 2, 3, 4, 5, 6, 7];
fromArray([...data])
.pipe(batch(3))
.pipe(
map(d => {
t.deepEqual(
d,
[data.shift(), data.shift(), data.shift()].filter(
x => !!x,
),
);
}),
)
.on("error", t.fail)
.on("finish", () => {
t.is(data.length, 0);
t.end();
});
},
);

View File

@@ -4,7 +4,7 @@ import { sleep } from "../src/helpers";
import { Readable, Writable } from "stream";
import mhysa from "../src";
import { performance } from "perf_hooks";
const { compose, map } = mhysa({ objectMode: true });
const { compose, map, fromArray } = mhysa({ objectMode: true });
test.cb("compose() chains two streams together in the correct order", t => {
t.plan(3);
@@ -98,7 +98,7 @@ test.cb("piping compose() maintains correct order", t => {
});
test("compose() writable length should be less than highWaterMark when handing writes", async t => {
t.plan(7);
t.plan(2);
return new Promise(async (resolve, reject) => {
interface Chunk {
key: string;
@@ -114,9 +114,13 @@ test("compose() writable length should be less than highWaterMark when handing w
return chunk;
});
const composed = compose([first, second], undefined, {
const composed = compose(
[first, second],
undefined,
{
highWaterMark: 2,
});
},
);
composed.on("error", err => {
reject();
});
@@ -140,19 +144,12 @@ test("compose() writable length should be less than highWaterMark when handing w
{ key: "e", mapped: [] },
];
for (const item of input) {
const res = composed.write(item);
expect(composed._writableState.length).to.be.at.most(2);
t.pass();
if (!res) {
await sleep(10);
}
}
fromArray(input).pipe(composed);
});
});
test("compose() should emit drain event ~rate * highWaterMark ms for every write that causes backpressure", async t => {
t.plan(7);
t.plan(2);
const _rate = 100;
const highWaterMark = 2;
return new Promise(async (resolve, reject) => {
@@ -171,9 +168,13 @@ test("compose() should emit drain event ~rate * highWaterMark ms for every write
return chunk;
});
const composed = compose([first, second], undefined, {
const composed = compose(
[first, second],
undefined,
{
highWaterMark,
});
},
);
composed.on("error", err => {
reject();
});
@@ -181,19 +182,14 @@ test("compose() should emit drain event ~rate * highWaterMark ms for every write
composed.on("drain", () => {
t.pass();
expect(composed._writableState.length).to.be.equal(0);
expect(performance.now() - start).to.be.closeTo(
_rate * highWaterMark,
40,
);
});
composed.on("data", (chunk: Chunk) => {
pendingReads--;
if (pendingReads === 0) {
resolve();
}
t.deepEqual(chunk.mapped, [1, 2]);
});
composed.on("finish", () => resolve());
const input = [
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
@@ -201,19 +197,7 @@ test("compose() should emit drain event ~rate * highWaterMark ms for every write
{ key: "d", mapped: [] },
{ key: "e", mapped: [] },
];
let start = performance.now();
let pendingReads = input.length;
start = performance.now();
for (const item of input) {
const res = composed.write(item);
expect(composed._writableState.length).to.be.at.most(highWaterMark);
t.pass();
if (!res) {
await sleep(_rate * highWaterMark * 2);
start = performance.now();
}
}
fromArray(input).pipe(composed);
});
});
@@ -237,9 +221,13 @@ test.cb(
return chunk;
});
const composed = compose([first, second], undefined, {
const composed = compose(
[first, second],
undefined,
{
highWaterMark: 5,
});
},
);
composed.on("error", err => {
t.end(err);
@@ -247,10 +235,6 @@ test.cb(
composed.on("drain", () => {
expect(composed._writableState.length).to.be.equal(0);
expect(performance.now() - start).to.be.closeTo(
_rate * input.length,
50,
);
t.pass();
});
@@ -271,7 +255,6 @@ test.cb(
input.forEach(item => {
composed.write(item);
});
const start = performance.now();
},
);
@@ -301,9 +284,13 @@ test.cb(
{ highWaterMark: 1 },
);
const composed = compose([first, second], undefined, {
const composed = compose(
[first, second],
undefined,
{
highWaterMark: 5,
});
},
);
composed.on("error", err => {
t.end(err);
});
@@ -368,9 +355,13 @@ test.cb(
{ highWaterMark: 2 },
);
const composed = compose([first, second], undefined, {
const composed = compose(
[first, second],
undefined,
{
highWaterMark: 5,
});
},
);
composed.on("error", err => {
t.end(err);
});
@@ -423,9 +414,13 @@ test.cb(
return chunk;
});
const composed = compose([first, second], undefined, {
const composed = compose(
[first, second],
undefined,
{
highWaterMark: 6,
});
},
);
composed.on("error", err => {
t.end(err);
@@ -475,9 +470,12 @@ test.cb("compose() should be 'destroyable'", t => {
return chunk;
});
const composed = compose([first, second], (err: any) => {
const composed = compose(
[first, second],
(err: any) => {
t.pass();
});
},
);
const fakeSource = new Readable({
objectMode: true,
@@ -533,9 +531,13 @@ test.cb("compose() `finish` and `end` propagates", t => {
return chunk;
});
const composed = compose([first, second], undefined, {
const composed = compose(
[first, second],
undefined,
{
highWaterMark: 3,
});
},
);
const fakeSource = new Readable({
objectMode: true,

View File

@@ -1,11 +1,11 @@
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
import { Writable } from "stream";
import { Writable, Readable } from "stream";
const sinon = require("sinon");
const { sleep } = require("../src/helpers");
import { performance } from "perf_hooks";
const { demux, map } = mhysa();
const { demux, map, fromArray } = mhysa({ objectMode: true });
interface Test {
key: string;
@@ -31,7 +31,7 @@ test.cb("demux() constructor should be called once per key", t => {
return dest;
});
const demuxed = demux(construct, "key", { objectMode: true });
const demuxed = demux(construct, "key", {});
demuxed.on("finish", () => {
expect(construct.withArgs("a").callCount).to.equal(1);
@@ -41,8 +41,35 @@ test.cb("demux() constructor should be called once per key", t => {
t.end();
});
input.forEach(event => demuxed.write(event));
demuxed.end();
fromArray(input).pipe(demuxed);
});
test.cb("demux() item written passed in constructor", t => {
t.plan(4);
const input = [
{ key: "a", visited: [] },
{ key: "b", visited: [] },
{ key: "c", visited: [] },
];
const construct = sinon.spy((destKey: string, item: any) => {
expect(item).to.deep.equal({ key: destKey, visited: [] });
t.pass();
const dest = map((chunk: Test) => {
chunk.visited.push(1);
return chunk;
});
return dest;
});
const demuxed = demux(construct, "key", {});
demuxed.on("finish", () => {
t.pass();
t.end();
});
fromArray(input).pipe(demuxed);
});
test.cb("demux() should send input through correct pipeline", t => {
@@ -66,7 +93,7 @@ test.cb("demux() should send input through correct pipeline", t => {
return dest;
};
const demuxed = demux(construct, "key", { objectMode: true });
const demuxed = demux(construct, "key", {});
demuxed.on("finish", () => {
pipelineSpies["a"].getCalls().forEach(call => {
@@ -84,8 +111,7 @@ test.cb("demux() should send input through correct pipeline", t => {
t.end();
});
input.forEach(event => demuxed.write(event));
demuxed.end();
fromArray(input).pipe(demuxed);
});
test.cb("demux() constructor should be called once per key using keyBy", t => {
@@ -108,7 +134,7 @@ test.cb("demux() constructor should be called once per key using keyBy", t => {
return dest;
});
const demuxed = demux(construct, item => item.key, { objectMode: true });
const demuxed = demux(construct, item => item.key, {});
demuxed.on("finish", () => {
expect(construct.withArgs("a").callCount).to.equal(1);
@@ -118,8 +144,7 @@ test.cb("demux() constructor should be called once per key using keyBy", t => {
t.end();
});
input.forEach(event => demuxed.write(event));
demuxed.end();
fromArray(input).pipe(demuxed);
});
test.cb("demux() should send input through correct pipeline using keyBy", t => {
@@ -143,7 +168,7 @@ test.cb("demux() should send input through correct pipeline using keyBy", t => {
return dest;
};
const demuxed = demux(construct, item => item.key, { objectMode: true });
const demuxed = demux(construct, item => item.key, {});
demuxed.on("finish", () => {
pipelineSpies["a"].getCalls().forEach(call => {
@@ -161,11 +186,10 @@ test.cb("demux() should send input through correct pipeline using keyBy", t => {
t.end();
});
input.forEach(event => demuxed.write(event));
demuxed.end();
fromArray(input).pipe(demuxed);
});
test("demux() write should return false after if it has >= highWaterMark items buffered and drain should be emitted", t => {
test("demux() write should return false and emit drain if more than highWaterMark items are buffered", t => {
return new Promise(async (resolve, reject) => {
t.plan(7);
interface Chunk {
@@ -189,7 +213,7 @@ test("demux() write should return false after if it has >= highWaterMark items b
await sleep(slowProcessorSpeed);
return { ...chunk, mapped: [1] };
},
{ highWaterMark: 1, objectMode: true },
{ highWaterMark: 1 },
);
first.on("data", chunk => {
@@ -205,7 +229,6 @@ test("demux() write should return false after if it has >= highWaterMark items b
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark,
});
@@ -229,7 +252,7 @@ test("demux() write should return false after if it has >= highWaterMark items b
});
});
test("demux() should emit one drain event after slowProcessorSpeed * highWaterMark ms", t => {
test("demux() should emit one drain event after slowProcessorSpeed * highWaterMark ms when first stream is bottleneck", t => {
return new Promise(async (resolve, reject) => {
t.plan(7);
interface Chunk {
@@ -255,7 +278,7 @@ test("demux() should emit one drain event after slowProcessorSpeed * highWaterMa
chunk.mapped.push(1);
return chunk;
},
{ highWaterMark: 1, objectMode: true },
{ highWaterMark: 1 },
);
first.on("data", () => {
@@ -268,7 +291,6 @@ test("demux() should emit one drain event after slowProcessorSpeed * highWaterMa
return first;
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark,
});
_demux.on("error", err => {
@@ -296,7 +318,7 @@ test("demux() should emit one drain event after slowProcessorSpeed * highWaterMa
test("demux() should emit one drain event when writing 6 items with highWaterMark of 5", t => {
return new Promise(async (resolve, reject) => {
t.plan(7);
t.plan(1);
interface Chunk {
key: string;
mapped: number[];
@@ -318,12 +340,11 @@ test("demux() should emit one drain event when writing 6 items with highWaterMar
chunk.mapped.push(2);
return chunk;
},
{ highWaterMark: 1, objectMode: true },
{ highWaterMark: 1 },
);
first.on("data", () => {
pendingReads--;
t.pass();
if (pendingReads === 0) {
resolve();
}
@@ -331,7 +352,6 @@ test("demux() should emit one drain event when writing 6 items with highWaterMar
return first;
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark: 5,
});
@@ -355,9 +375,10 @@ test("demux() should emit one drain event when writing 6 items with highWaterMar
});
});
test.cb.only(
"demux() should emit drain event when third stream is bottleneck",
test.cb(
"demux() should emit drain event when second stream is bottleneck after (highWaterMark - 2) * slowProcessorSpeed ms",
t => {
// ie) first two items are pushed directly into first and second streams (highWaterMark - 2 remain in demux)
t.plan(8);
const slowProcessorSpeed = 100;
const highWaterMark = 5;
@@ -383,7 +404,7 @@ test.cb.only(
chunk.mapped.push(1);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
const second = map(
@@ -392,25 +413,23 @@ test.cb.only(
chunk.mapped.push(2);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
first.pipe(second).pipe(sink);
return first;
};
const _demux = demux(construct, () => "a", {
objectMode: true,
highWaterMark,
});
_demux.on("error", err => {
t.end(err);
});
// This event should be received after at least 5 * slowProcessorSpeed (two are read immediately by first and second, 5 remaining in demux before drain event)
_demux.on("drain", () => {
expect(_demux._writableState.length).to.be.equal(0);
expect(performance.now() - start).to.be.greaterThan(
slowProcessorSpeed * (input.length - 2),
slowProcessorSpeed * 3,
);
t.pass();
});
@@ -427,15 +446,14 @@ test.cb.only(
let pendingReads = input.length;
const start = performance.now();
input.forEach(item => {
_demux.write(item);
});
fromArray(input).pipe(_demux);
},
);
test.cb(
"demux() should emit drain event when second stream is bottleneck",
"demux() should emit drain event when third stream is bottleneck",
t => {
// @TODO investigate why drain is emitted after slowProcessorSpeed
t.plan(8);
const slowProcessorSpeed = 100;
const highWaterMark = 5;
@@ -446,7 +464,7 @@ test.cb(
const sink = new Writable({
objectMode: true,
write(chunk, encoding, cb) {
expect(chunk.mapped).to.deep.equal([1, 2]);
expect(chunk.mapped).to.deep.equal([1, 2, 3]);
t.pass();
pendingReads--;
if (pendingReads === 0) {
@@ -461,14 +479,14 @@ test.cb(
chunk.mapped.push(1);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
const second = map(
(chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
const third = map(
@@ -477,7 +495,7 @@ test.cb(
chunk.mapped.push(3);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
first
@@ -487,18 +505,16 @@ test.cb(
return first;
};
const _demux = demux(construct, () => "a", {
objectMode: true,
highWaterMark,
});
_demux.on("error", err => {
t.end(err);
});
// This event should be received after at least 3 * slowProcessorSpeed (two are read immediately by first and second, 3 remaining in demux before drain event)
_demux.on("drain", () => {
expect(_demux._writableState.length).to.be.equal(0);
expect(performance.now() - start).to.be.greaterThan(
slowProcessorSpeed * (input.length - 4),
slowProcessorSpeed,
);
t.pass();
});
@@ -515,9 +531,7 @@ test.cb(
let pendingReads = input.length;
const start = performance.now();
input.forEach(item => {
_demux.write(item);
});
fromArray(input).pipe(_demux);
},
);
@@ -536,10 +550,21 @@ test("demux() should be blocked by slowest pipeline", t => {
chunk.mapped.push(1);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
first.on("data", chunk => {
return first;
};
const _demux = demux(construct, "key", {
highWaterMark: 1,
});
_demux.on("error", err => {
reject(err);
});
_demux.on("data", async chunk => {
pendingReads--;
if (chunk.key === "b") {
expect(performance.now() - start).to.be.greaterThan(
@@ -550,22 +575,12 @@ test("demux() should be blocked by slowest pipeline", t => {
resolve();
}
});
return first;
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark: 1,
});
_demux.on("error", err => {
reject(err);
});
const input = [
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "c", mapped: [] },
{ key: "c", mapped: [] },
{ key: "c", mapped: [] },
{ key: "b", mapped: [] },
];
@@ -584,74 +599,266 @@ test("demux() should be blocked by slowest pipeline", t => {
});
});
test("demux() should emit drain event when second stream in pipeline is bottleneck", t => {
t.plan(5);
const highWaterMark = 3;
return new Promise(async (resolve, reject) => {
test.cb("Demux should remux to sink", t => {
t.plan(6);
let i = 0;
const input = [
{ key: "a", visited: [] },
{ key: "b", visited: [] },
{ key: "a", visited: [] },
{ key: "c", visited: [] },
{ key: "a", visited: [] },
{ key: "b", visited: [] },
];
const result = [
{ key: "a", visited: ["a"] },
{ key: "b", visited: ["b"] },
{ key: "a", visited: ["a"] },
{ key: "c", visited: ["c"] },
{ key: "a", visited: ["a"] },
{ key: "b", visited: ["b"] },
];
const construct = (destKey: string) => {
const dest = map((chunk: any) => {
chunk.visited.push(destKey);
return chunk;
});
return dest;
};
const sink = map(d => {
t.deepEqual(d, result[i]);
i++;
if (i === input.length) {
t.end();
}
});
const demuxed = demux(construct, "key", {});
fromArray(input)
.pipe(demuxed)
.pipe(sink);
});
test.cb("Demux should send data events", t => {
t.plan(6);
let i = 0;
const input = [
{ key: "a", visited: [] },
{ key: "b", visited: [] },
{ key: "a", visited: [] },
{ key: "c", visited: [] },
{ key: "a", visited: [] },
{ key: "b", visited: [] },
];
const result = [
{ key: "a", visited: ["a"] },
{ key: "b", visited: ["b"] },
{ key: "a", visited: ["a"] },
{ key: "c", visited: ["c"] },
{ key: "a", visited: ["a"] },
{ key: "b", visited: ["b"] },
];
const construct = (destKey: string) => {
const dest = map((chunk: any) => {
chunk.visited.push(destKey);
return chunk;
});
return dest;
};
const demuxed = demux(construct, "key", {});
fromArray(input).pipe(demuxed);
demuxed.on("data", d => {
t.deepEqual(d, result[i]);
i++;
if (i === input.length) {
t.end();
}
});
});
test.cb("demux() `finish` and `end` propagates", t => {
interface Chunk {
key: string;
mapped: number[];
}
const sink = new Writable({
objectMode: true,
write(chunk, encoding, cb) {
expect(chunk.mapped).to.deep.equal([1, 2]);
t.pass();
cb();
if (pendingReads === 0) {
resolve();
}
},
});
t.plan(9);
const construct = (destKey: string) => {
const first = map(
(chunk: Chunk) => {
expect(first._readableState.length).to.be.at.most(2);
chunk.mapped.push(1);
const dest = map((chunk: any) => {
chunk.mapped.push(destKey);
return chunk;
},
{ objectMode: true, highWaterMark: 2 },
);
const second = map(
async (chunk: Chunk) => {
await sleep(100);
chunk.mapped.push(2);
expect(second._writableState.length).to.be.equal(1);
pendingReads--;
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
);
first.pipe(second).pipe(sink);
return first;
});
return dest;
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark,
});
_demux.on("error", err => {
reject();
highWaterMark: 3,
});
_demux.on("drain", () => {
expect(_demux._writableState.length).to.be.equal(0);
const fakeSource = new Readable({
objectMode: true,
read() {
return;
},
});
const sink = map((d: any) => {
const curr = input.shift();
t.is(curr.key, d.key);
t.deepEqual(d.mapped, [d.key]);
});
fakeSource.pipe(_demux).pipe(sink);
fakeSource.on("end", () => {
t.pass();
});
_demux.on("finish", () => {
t.pass();
});
_demux.on("unpipe", () => {
t.pass();
});
_demux.on("end", () => {
t.pass();
t.end();
});
sink.on("finish", () => {
t.pass();
});
const input = [
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
];
let pendingReads = input.length;
input.forEach(item => {
_demux.write(item);
});
});
fakeSource.push(input[0]);
fakeSource.push(input[1]);
fakeSource.push(null);
});
test.cb("demux() `unpipe` propagates", t => {
interface Chunk {
key: string;
mapped: number[];
}
t.plan(7);
const construct = (destKey: string) => {
const dest = map((chunk: any) => {
chunk.mapped.push(destKey);
return chunk;
});
return dest;
};
const _demux = demux(construct, "key", {
highWaterMark: 3,
});
const fakeSource = new Readable({
objectMode: true,
read() {
return;
},
});
const sink = map((d: any) => {
const curr = input.shift();
t.is(curr.key, d.key);
t.deepEqual(d.mapped, [d.key]);
});
fakeSource.pipe(_demux).pipe(sink);
_demux.on("unpipe", () => {
t.pass();
});
sink.on("unpipe", () => {
t.pass();
});
sink.on("finish", () => {
t.pass();
t.end();
});
const input = [
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
];
fakeSource.push(input[0]);
fakeSource.push(input[1]);
fakeSource.push(null);
});
test.cb("demux() should be 'destroyable'", t => {
t.plan(2);
const _sleep = 100;
interface Chunk {
key: string;
mapped: string[];
}
const construct = (destKey: string) => {
const first = map(async (chunk: Chunk) => {
await sleep(_sleep);
chunk.mapped.push(destKey);
return chunk;
});
return first;
};
const _demux = demux(construct, "key");
const fakeSource = new Readable({
objectMode: true,
read() {
return;
},
});
const fakeSink = new Writable({
objectMode: true,
write(data, enc, cb) {
const cur = input.shift();
t.is(cur.key, data.key);
t.deepEqual(cur.mapped, ["a"]);
if (cur.key === "a") {
_demux.destroy();
}
cb();
},
});
_demux.on("close", t.end);
fakeSource.pipe(_demux).pipe(fakeSink);
const input = [
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
{ key: "c", mapped: [] },
{ key: "d", mapped: [] },
{ key: "e", mapped: [] },
];
fakeSource.push(input[0]);
fakeSource.push(input[1]);
fakeSource.push(input[2]);
fakeSource.push(input[3]);
fakeSource.push(input[4]);
});

View File

@@ -0,0 +1,9 @@
import test from "ava";
import { collected } from "../../src/utils";
import mhysa from "../../src";
const { fromArray, collect } = mhysa({ objectMode: true });
test("collected returns a promise for the first data point", async t => {
const data = collected(fromArray([1, 2, 3, 4]).pipe(collect()));
t.deepEqual(await data, [1, 2, 3, 4]);
});

View File

@@ -409,10 +409,10 @@
resolved "https://registry.yarnpkg.com/@types/node/-/node-12.7.2.tgz#c4e63af5e8823ce9cc3f0b34f7b998c2171f0c44"
integrity sha512-dyYO+f6ihZEtNPDcWNR1fkoTDf3zAK3lAABDze3mz6POyIercH0lEUawUFXlG8xaQZmm1yEBON/4TsYv/laDYg==
"@types/node@^12.7.2":
version "12.12.14"
resolved "https://npm.dev.jogogo.co/@types%2fnode/-/node-12.12.14.tgz#1c1d6e3c75dba466e0326948d56e8bd72a1903d2"
integrity sha512-u/SJDyXwuihpwjXy7hOOghagLEV1KdAST6syfnOk6QZAMzZuWZqXy5aYYZbh8Jdpd4escVFP0MvftHNDb9pruA==
"@types/node@^12.12.15":
version "12.12.15"
resolved "https://npm.dev.jogogo.co/@types%2fnode/-/node-12.12.15.tgz#8dfb6ce22fedd469128137640a3aa8f17415422f"
integrity sha512-Pv+vWicyFd07Hw/SmNnTUguqrHgDfMtjabvD9sQyxeqbpCEg8CmViLBaVPHtNsoBgZECrRf5/pgV6FJIBrGSjw==
"@types/sinon@^7.0.13":
version "7.5.1"
@@ -1935,7 +1935,7 @@ merge2@^1.2.3, merge2@^1.3.0:
integrity sha512-2j4DAdlBOkiSZIsaXk4mTE3sRS02yBHAtfy127xRV3bQUFqXkjHCHLW6Scv7DwNRbIWNHH8zpnz9zMaKXIdvYw==
mhysa@./:
version "0.0.1-beta.4"
version "2.0.0-alpha.1"
micromatch@^4.0.2:
version "4.0.2"