Compare commits

...

35 Commits

Author SHA1 Message Date
Lewis Diamond
e005b45207 set repo to github 2021-02-05 20:13:45 -05:00
Lewis Diamond
2fb7942d9c Update package to use itself in dev, update samples 2020-08-05 19:08:13 -04:00
Lewis Diamond
fc5b96f725 Merge branch 'dev' into master 2020-08-05 10:42:33 -04:00
Lewis Diamond
491ec146a6 Update readme 2020-08-05 10:41:23 -04:00
Lewis Diamond
38bb853181 Set version to 0.5.0, diverge from Mhysa's versioning 2020-08-03 18:56:44 -04:00
Lewis Diamond
87c44de799 Default to an objectMode: true instance but allow creating other instances with other defaults 2020-08-03 18:54:40 -04:00
Lewis Diamond
7f1309f45f update pkg name 2020-08-01 22:09:00 -04:00
Lewis Diamond
4aac05c9c0 Adding some partial documentation. Fixing batching timeout 2020-07-31 23:32:26 -04:00
Lewis Diamond
caaabf4427 Make the package name stromjs because strom is taken 2020-07-31 22:17:57 -04:00
Lewis Diamond
1c02cb5aea No need to create an array to call concat 2020-07-12 18:52:21 -04:00
Lewis Diamond
12cbddf7e0 Update README 2020-07-09 12:51:08 -04:00
Lewis Diamond
2e5a6dbcc8 update samples 2020-07-04 11:06:41 -04:00
Lewis Diamond
e6fb55eb1a ObjectMode is now true by default 2020-07-04 10:58:08 -04:00
Lewis Diamond
74ce415118 Update tests make export a bit nicer 2020-07-04 10:43:52 -04:00
Lewis Diamond
1675b18d5b add prepare script 2020-07-04 00:15:11 -04:00
Lewis Diamond
ca6f36d19a Quick rename 2020-07-04 00:08:31 -04:00
Jerry Kurian
db783805ad
Arrays of pipelines by key (#7)
* Demux handles arrays by key

* Rename construct

* version

* Minor changes to types
2020-05-12 09:44:11 -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
Lewis Diamond
4b806c4d4e Fix a few thing with compose 2019-12-06 16:38:52 -05:00
Lewis Diamond
ff2b652ddf
Merge pull request #3 from Jogogoplay/feature/ObjectModeByConfig
DefaultOptions implemented as module factory
2019-12-02 16:27:01 -05:00
56 changed files with 2342 additions and 2282 deletions

206
README.md
View File

@ -1,14 +1,15 @@
# Mhysa
# Strom
**Dependency-free stream utils for Node.js**
<sub>Released under the [MIT](https://github.com/Wenzil/Mhysa/blob/master/LICENSE) license.</sub>
<sub>Released under the [MIT](LICENSE) license.</sub>
```sh
yarn add mhysa
yarn add stromjs
```
```sh
npm add stromjs
```
<sub>Tested with Node.js versions 8+</sub>
## fromArray(array)
Convert an array into a `Readable` stream of its elements
@ -18,14 +19,14 @@ Convert an array into a `Readable` stream of its elements
| `array` | `T[]` | Array of elements to stream |
```js
Mhysa.fromArray(["a", "b"])
strom.fromArray(["a", "b"])
.pipe(process.stdout);
// ab is printed out
```
## map(mapper, options)
Return a `ReadWrite` stream that maps streamed chunks
Returns a `ReadWrite` stream that maps streamed chunks
| Param | Type | Description |
| --- | --- | --- |
@ -35,15 +36,15 @@ Return a `ReadWrite` stream that maps streamed chunks
| `options.writableObjectMode` | `boolean` | Whether this stream should behave as a writable stream of objects |
```js
Mhysa.fromArray(["a", "b"])
.pipe(Mhysa.map(s => s.toUpperCase()))
strom.fromArray(["a", "b"])
.pipe(strom.map(s => s.toUpperCase()))
.pipe(process.stdout);
// AB is printed out
```
## flatMap(mapper, options)
Return a `ReadWrite` stream that flat maps streamed chunks
Returns a `ReadWrite` stream that flat maps streamed chunks
| Param | Type | Description |
| --- | --- | --- |
@ -53,15 +54,15 @@ Return a `ReadWrite` stream that flat maps streamed chunks
| `options.writableObjectMode` | `boolean` | Whether this stream should behave as a writable stream of objects |
```js
Mhysa.fromArray(["a", "AA"])
.pipe(Mhysa.flatMap(s => new Array(s.length).fill(s)))
strom.fromArray(["a", "AA"])
.pipe(strom.flatMap(s => new Array(s.length).fill(s)))
.pipe(process.stdout);
// aAAAA is printed out
```
## filter(predicate, options)
Return a `ReadWrite` stream that filters out streamed chunks for which the predicate does not hold
Returns a `ReadWrite` stream that filters out streamed chunks for which the predicate does not hold
| Param | Type | Description |
| --- | --- | --- |
@ -70,15 +71,15 @@ Return a `ReadWrite` stream that filters out streamed chunks for which the predi
| `options.objectMode` | `boolean` | `boolean` | Whether this stream should behave as a stream of objects |
```js
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.filter(s => s !== "b"))
strom.fromArray(["a", "b", "c"])
.pipe(strom.filter(s => s !== "b"))
.pipe(process.stdout);
// ac is printed out
```
## reduce(iteratee, initialValue, options)
Return a `ReadWrite` stream that reduces streamed chunks down to a single value and yield that
Returns a `ReadWrite` stream that reduces streamed chunks down to a single value and yield that
value
| Param | Type | Description |
@ -90,16 +91,16 @@ value
| `options.writableObjectMode` | `boolean` | Whether this stream should behave as a writable stream of objects |
```js
Mhysa.fromArray(["a", "b", "cc"])
.pipe(Mhysa.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(Mhysa.stringify())
strom.fromArray(["a", "b", "cc"])
.pipe(strom.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(strom.stringify())
.pipe(process.stdout);
// {"a":1,"b":1","c":2} is printed out
```
## split(separator)
Return a `ReadWrite` stream that splits streamed chunks using the given separator
Returns a `ReadWrite` stream that splits streamed chunks using the given separator
| Param | Type | Description |
| --- | --- | --- |
@ -108,16 +109,16 @@ Return a `ReadWrite` stream that splits streamed chunks using the given separato
| `options.encoding` | `string` | Character encoding to use for decoding chunks. Defaults to utf8
```js
Mhysa.fromArray(["a,b", "c,d"])
.pipe(Mhysa.split(","))
.pipe(Mhysa.join("|"))
strom.fromArray(["a,b", "c,d"])
.pipe(strom.split(","))
.pipe(strom.join("|"))
.pipe(process.stdout);
// a|bc|d is printed out
```
## join(separator)
Return a `ReadWrite` stream that joins streamed chunks using the given separator
Returns a `ReadWrite` stream that joins streamed chunks using the given separator
| Param | Type | Description |
| --- | --- | --- |
@ -126,15 +127,15 @@ Return a `ReadWrite` stream that joins streamed chunks using the given separator
| `options.encoding` | `string` | Character encoding to use for decoding chunks. Defaults to utf8
```js
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.join(","))
strom.fromArray(["a", "b", "c"])
.pipe(strom.join(","))
.pipe(process.stdout);
// a,b,c is printed out
```
## replace(searchValue, replaceValue)
Return a `ReadWrite` stream that replaces occurrences of the given string or regular expression in
Returns a `ReadWrite` stream that replaces occurrences of the given string or regular expression in
the streamed chunks with the specified replacement string
| Param | Type | Description |
@ -145,37 +146,37 @@ the streamed chunks with the specified replacement string
| `options.encoding` | `string` | Character encoding to use for decoding chunks. Defaults to utf8
```js
Mhysa.fromArray(["a1", "b22", "c333"])
.pipe(Mhysa.replace(/b\d+/, "B"))
strom.fromArray(["a1", "b22", "c333"])
.pipe(strom.replace(/b\d+/, "B"))
.pipe(process.stdout);
// a1Bc333 is printed out
```
## parse()
Return a `ReadWrite` stream that parses the streamed chunks as JSON
Returns a `ReadWrite` stream that parses the streamed chunks as JSON
```js
Mhysa.fromArray(['{ "a": "b" }'])
.pipe(Mhysa.parse())
strom.fromArray(['{ "a": "b" }'])
.pipe(strom.parse())
.once("data", object => console.log(object));
// { a: 'b' } is printed out
```
## stringify()
Return a `ReadWrite` stream that stringifies the streamed chunks to JSON
Returns a `ReadWrite` stream that stringifies the streamed chunks to JSON
```js
Mhysa.fromArray([{ a: "b" }])
.pipe(Mhysa.stringify())
strom.fromArray([{ a: "b" }])
.pipe(strom.stringify())
.pipe(process.stdout);
// {"a":"b"} is printed out
```
## collect(options)
Return a `ReadWrite` stream that collects streamed chunks into an array or buffer
Returns a `ReadWrite` stream that collects streamed chunks into an array or buffer
| Param | Type | Description |
| --- | --- | --- |
@ -183,15 +184,15 @@ Return a `ReadWrite` stream that collects streamed chunks into an array or buffe
| `options.objectMode` | `boolean` | Whether this stream should behave as a stream of objects |
```js
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.collect({ objectMode: true }))
strom.fromArray(["a", "b", "c"])
.pipe(strom.collect({ objectMode: true }))
.once("data", object => console.log(object));
// [ 'a', 'b', 'c' ] is printed out
```
## concat(streams)
Return a `Readable` stream of readable streams concatenated together
Returns a `Readable` stream of readable streams concatenated together
| Param | Type | Description |
| --- | --- | --- |
@ -200,7 +201,7 @@ Return a `Readable` stream of readable streams concatenated together
```js
const source1 = new Readable();
const source2 = new Readable();
Mhysa.concat(source1, source2).pipe(process.stdout)
strom.concat(source1, source2).pipe(process.stdout)
source1.push("a1 ");
source2.push("c3 ");
source1.push("b2 ");
@ -212,7 +213,7 @@ source2.push(null);
## merge(streams)
Return a `Readable` stream of readable streams merged together in chunk arrival order
Returns a `Readable` stream of readable streams merged together in chunk arrival order
| Param | Type | Description |
| --- | --- | --- |
@ -221,7 +222,7 @@ Return a `Readable` stream of readable streams merged together in chunk arrival
```js
const source1 = new Readable({ read() {} });
const source2 = new Readable({ read() {} });
Mhysa.merge(source1, source2).pipe(process.stdout);
strom.merge(source1, source2).pipe(process.stdout);
source1.push("a1 ");
setTimeout(() => source2.push("c3 "), 10);
setTimeout(() => source1.push("b2 "), 20);
@ -233,7 +234,7 @@ setTimeout(() => source2.push(null), 50);
## duplex(writable, readable)
Return a `Duplex` stream from a writable stream that is assumed to somehow, when written to,
Returns a `Duplex` stream from a writable stream that is assumed to somehow, when written to,
cause the given readable stream to yield chunks
| Param | Type | Description |
@ -243,15 +244,15 @@ cause the given readable stream to yield chunks
```js
const catProcess = require("child_process").exec("grep -o ab");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.duplex(catProcess.stdin, catProcess.stdout))
strom.fromArray(["a", "b", "c"])
.pipe(strom.duplex(catProcess.stdin, catProcess.stdout))
.pipe(process.stdout);
// ab is printed out
```
## child(childProcess)
Return a `Duplex` stream from a child process' stdin and stdout
Returns a `Duplex` stream from a child process' stdin and stdout
| Param | Type | Description |
| --- | --- | --- |
@ -259,15 +260,15 @@ Return a `Duplex` stream from a child process' stdin and stdout
```js
const catProcess = require("child_process").exec("grep -o ab");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.child(catProcess))
strom.fromArray(["a", "b", "c"])
.pipe(strom.child(catProcess))
.pipe(process.stdout);
// ab is printed out
```
## last(readable)
Return a `Promise` resolving to the last streamed chunk of the given readable stream, after it has
Returns a `Promise` resolving to the last streamed chunk of the given readable stream, after it has
ended
| Param | Type | Description |
@ -276,9 +277,112 @@ ended
```js
let f = async () => {
const source = Mhysa.fromArray(["a", "b", "c"]);
console.log(await Mhysa.last(source));
const source = strom.fromArray(["a", "b", "c"]);
console.log(await strom.last(source));
};
f();
// c is printed out
```
## accumulator(flushStrategy, iteratee, options)
TO BE DOCUMENTED
## batch(batchSize, maxBatchAge, options)
Returns a `Transform` stream which produces all incoming data in batches of size `batchSize`.
| Param | Type | Description |
| --- | --- | --- |
| `batchSize` | `number` | Size of the batches to be produced |
| `maxBatchAge` | `number` | Maximum number of milliseconds a message will be queued for. E.g. a batch will be produced before reaching `batchSize` if the first message queued is `maxBatchAge` ms old or more |
| `options` | `TransformOptions` | Options passed down to the Transform object |
```js
strom.fromArray(["a", "b", "c", "d"])
.pipe(strom.batch(3, 500))
.pipe(process.stdout);
// ["a","b","c"]
// ["d"] //After 500ms
```
## compose(streams, errorCb, options)
Returns a `Transform` stream which consists of all `streams` but behaves as a single stream. The returned stream can be piped into and from transparently.
| Param | Type | Description |
| --- | --- | --- |
| `streams` | `Array` | Streams to be composed |
| `errorCb` | `(err: Error) => void` | Function called when an error occurs in any of the streams |
| `options` | `TransformOptions` | Options passed down to the Transform object |
```js
const composed = strom.compose([
strom.split(),
strom.map(data => data.trim()),
strom.filter(str => !!str),
strom.parse(),
strom.flatMap(data => data),
strom.stringify(),
]);
const data = ["[1,2,3] \n [4,5,6] ", "\n [7,8,9] \n\n"];
strom.fromArray(data).pipe(composed).pipe(process.stdout);
// 123456789
```
## demux(pipelineConstructor, demuxBy, options)
TO BE DOCUMENTED
## parallelMap(mapper, parallel, sleepTime, options)
Returns a `Transform` stream which maps incoming data through the async mapper with the given parallelism.
| Param | Type | Description | Default |
| --- | --- | --- | --- |
| `mapper` | `async (chunk: T, encoding: string) => R` | Mapper function, mapping each (chunk, encoding) to a new chunk (non-async will not be parallelized) | -- |
| `parallel` | `number` | Number of concurrent executions of the mapper allowed | 10 |
| `sleepTime` | `number` | Number of milliseconds to wait before testing if more messages can be processed | 1 |
```js
function sleep(time) {
return time > 0 ? new Promise(resolve => setTimeout(resolve, time)) : null;
}
strom
.fromArray([1, 2, 3, 4, 6, 8])
.pipe(
strom.parallelMap(async d => {
await sleep(10000 - d * 1000);
return `${d}`;
}, 3),
)
.pipe(process.stdout);
// 321864
```
## rate()
```js
const strom = require("stromjs").strom();
function sleep(time) {
return time > 0 ? new Promise(resolve => setTimeout(resolve, time)) : null;
}
const rate = strom.rate(2, 1, { behavior: 1 });
rate.pipe(strom.map(x => console.log(x)));
async function produce() {
rate.write(1);
await sleep(500);
rate.write(2);
await sleep(500);
rate.write(3);
rate.write(4);
rate.write(5);
await sleep(500);
rate.write(6);
}
produce();
```

View File

@ -1,24 +1,26 @@
{
"name": "@jogogo/mhysa",
"version": "0.0.1-beta.4",
"description": "Streams and event emitter utils for Node.js",
"name": "stromjs",
"version": "0.5.1",
"description": "Dependency-free streams utils for Node.js",
"keywords": [
"promise",
"stream",
"event emitter",
"utils"
],
"author": {
"name": "Wenzil"
},
"contributors": [
{
"name": "jerry",
"email": "jerry@jogogo.co"
"name": "Sami Turcotte",
"url": "https://github.com/Wenzil"
},
{
"name": "lewis",
"email": "lewis@jogogo.co"
"name": "Jerry Kurian",
"email": "jerrykurian@protonmail.com",
"url": "https://github.com/jkurian"
},
{
"name": "Lewis Diamond",
"email": "stromjs@lewisdiamond.com",
"url": "https://github.com/lewisdiamond"
}
],
"license": "MIT",
@ -27,29 +29,25 @@
"files": [
"dist"
],
"publishConfig": {
"registry": "https://npm.dev.jogogo.co/"
},
"repository": {
"url": "git@github.com:Jogogoplay/mhysa.git",
"url": "https://github.com/lewisdiamond/stromjs",
"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"
"prepublishOnly": "yarn lint && yarn test && yarn tsc -d",
"prepare": "tsc"
},
"dependencies": {},
"devDependencies": {
"@types/chai": "^4.1.7",
"@types/node": "^12.7.2",
"@types/node": "^12.12.15",
"@types/sinon": "^7.0.13",
"ava": "^1.0.0-rc.2",
"ava": "^2.4.0",
"chai": "^4.2.0",
"mhysa": "./",
"stromjs": "./",
"prettier": "^1.14.3",
"sinon": "^7.4.2",
"ts-node": "^8.3.0",
@ -60,7 +58,8 @@
},
"ava": {
"files": [
"tests/*.spec.ts"
"tests/*.spec.ts",
"tests/utils/*.spec.ts"
],
"sources": [
"src/**/*.ts"

View File

@ -1,8 +1,9 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.map(s => Promise.resolve(s + s)))
.pipe(Mhysa.flatMap(s => Promise.resolve([s, s.toUpperCase()])))
.pipe(Mhysa.filter(s => Promise.resolve(s !== "bb")))
.pipe(Mhysa.join(","))
strom
.fromArray(["a", "b", "c"])
.pipe(strom.map(s => Promise.resolve(s + s)))
.pipe(strom.flatMap(s => Promise.resolve([s, s.toUpperCase()])))
.pipe(strom.filter(s => Promise.resolve(s !== "bb")))
.pipe(strom.join(","))
.pipe(process.stdout);

View File

@ -1,6 +1,7 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
const catProcess = require("child_process").exec("grep -o ab");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.child(catProcess))
strom
.fromArray(["a", "b", "c"])
.pipe(strom.child(catProcess))
.pipe(process.stdout);

View File

@ -1,5 +1,6 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.collect({ objectMode: true }))
strom
.fromArray(["a", "b", "c"])
.pipe(strom.collect({ objectMode: true }))
.on("data", object => console.log(object));

View File

@ -1,9 +1,9 @@
const { Readable } = require("stream");
const Mhysa = require("mhysa");
const strom = require("stromjs");
const source1 = new Readable();
const source2 = new Readable();
Mhysa.concat(source1, source2).pipe(process.stdout);
strom.concat(source1, source2).pipe(process.stdout);
source1.push("a1 ");
source2.push("c3 ");
source1.push("b2 ");

View File

@ -1,6 +1,7 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
const catProcess = require("child_process").exec("grep -o ab");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.duplex(catProcess.stdin, catProcess.stdout))
strom
.fromArray(["a", "b", "c"])
.pipe(strom.duplex(catProcess.stdin, catProcess.stdout))
.pipe(process.stdout);

View File

@ -1,6 +1,7 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.filter(s => s !== "b"))
.pipe(Mhysa.join(","))
strom
.fromArray(["a", "b", "c"])
.pipe(strom.filter(s => s !== "b"))
.pipe(strom.join(","))
.pipe(process.stdout);

View File

@ -1,6 +1,7 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a", "AA"])
.pipe(Mhysa.flatMap(s => new Array(s.length).fill(s)))
.pipe(Mhysa.join(","))
strom
.fromArray(["a", "AA"])
.pipe(strom.flatMap(s => new Array(s.length).fill(s)))
.pipe(strom.join(","))
.pipe(process.stdout);

View File

@ -1,5 +1,6 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.join(","))
strom
.fromArray(["a", "b", "c"])
.pipe(strom.join(","))
.pipe(process.stdout);

View File

@ -1,7 +1,7 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
let f = async () => {
const source = Mhysa.fromArray(["a", "b", "c"]);
console.log(await Mhysa.last(source));
const source = strom.fromArray(["a", "b", "c"]);
console.log(await strom.last(source));
};
f();

View File

@ -1,6 +1,7 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a", "b"])
.pipe(Mhysa.map(s => s.toUpperCase()))
.pipe(Mhysa.join(","))
strom
.fromArray(["a", "b"])
.pipe(strom.map(s => s.toUpperCase()))
.pipe(strom.join(","))
.pipe(process.stdout);

View File

@ -1,9 +1,9 @@
const { Readable } = require("stream");
const Mhysa = require("mhysa");
const strom = require("stromjs");
const source1 = new Readable({ read() {} });
const source2 = new Readable({ read() {} });
Mhysa.merge(source1, source2).pipe(process.stdout);
strom.merge(source1, source2).pipe(process.stdout);
source1.push("a1 ");
setTimeout(() => source2.push("c3 "), 10);
setTimeout(() => source1.push("b2 "), 20);

15
samples/parallelMap.js Normal file
View File

@ -0,0 +1,15 @@
const strom = require("stromjs");
function sleep(time) {
return time > 0 ? new Promise(resolve => setTimeout(resolve, time)) : null;
}
strom
.fromArray([1, 2, 3, 4, 6, 8])
.pipe(
strom.parallelMap(async d => {
await sleep(10000 - d * 1000);
return `${d}`;
}, 3),
)
.pipe(process.stdout);

View File

@ -1,5 +1,6 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(['{ "a": "b" }'])
.pipe(Mhysa.parse())
strom
.fromArray(['{ "a": "b" }'])
.pipe(strom.parse())
.on("data", object => console.log(object));

21
samples/rate.js Normal file
View File

@ -0,0 +1,21 @@
const strom = require("stromjs");
function sleep(time) {
return time > 0 ? new Promise(resolve => setTimeout(resolve, time)) : null;
}
const rate = strom.rate(2, 1, { behavior: 1 });
rate.pipe(strom.map(x => console.log(x)));
async function produce() {
rate.write(1);
await sleep(500);
rate.write(2);
await sleep(500);
rate.write(3);
rate.write(4);
rate.write(5);
await sleep(500);
rate.write(6);
}
produce();

View File

@ -1,6 +1,7 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a", "b", "cc"])
.pipe(Mhysa.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(Mhysa.stringify())
strom
.fromArray(["a", "b", "cc"])
.pipe(strom.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(strom.stringify())
.pipe(process.stdout);

View File

@ -1,5 +1,6 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a1", "b22", "c333"])
.pipe(Mhysa.replace(/b\d+/, "B"))
strom
.fromArray(["a1", "b22", "c333"])
.pipe(strom.replace(/b\d+/, "B"))
.pipe(process.stdout);

View File

@ -1,6 +1,7 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray(["a,b", "c,d"])
.pipe(Mhysa.split(","))
.pipe(Mhysa.join("|"))
strom
.fromArray(["a,b", "c,d"])
.pipe(strom.split(","))
.pipe(strom.join("|"))
.pipe(process.stdout);

View File

@ -1,5 +1,6 @@
const Mhysa = require("mhysa");
const strom = require("stromjs");
Mhysa.fromArray([{ a: "b" }])
.pipe(Mhysa.stringify())
strom
.fromArray([{ a: "b" }])
.pipe(strom.stringify())
.pipe(process.stdout);

View File

@ -2,7 +2,7 @@ import { Transform, TransformOptions } from "stream";
export function batch(
batchSize: number = 1000,
maxBatchAge: number = 500,
maxBatchAge: number = 0,
options: TransformOptions = {},
): Transform {
let buffer: any[] = [];
@ -12,7 +12,9 @@ export function batch(
clearTimeout(timer);
}
timer = null;
self.push(buffer);
if (buffer.length > 0) {
self.push(buffer);
}
buffer = [];
};
return new Transform({
@ -21,7 +23,7 @@ export function batch(
buffer.push(chunk);
if (buffer.length === batchSize) {
sendChunk(this);
} else {
} else if (maxBatchAge) {
if (timer === null) {
timer = setInterval(() => {
sendChunk(this);

View File

@ -1,16 +1,18 @@
import { pipeline, Duplex, DuplexOptions } from "stream";
import { AllStreams, isReadable } from "../helpers";
import { PassThrough, pipeline, TransformOptions, Transform } from "stream";
export function compose(
streams: Array<
NodeJS.ReadableStream | NodeJS.ReadWriteStream | NodeJS.WritableStream
>,
options?: DuplexOptions,
errorCallback?: (err: any) => void,
options?: TransformOptions,
): Compose {
if (streams.length < 2) {
throw new Error("At least two streams are required to compose");
}
return new Compose(streams, options);
return new Compose(streams, errorCallback, options);
}
enum EventSubscription {
@ -20,46 +22,60 @@ enum EventSubscription {
Self,
}
const eventsTarget = {
close: EventSubscription.Last,
data: EventSubscription.Last,
drain: EventSubscription.Self,
end: EventSubscription.Last,
error: EventSubscription.Self,
finish: EventSubscription.Last,
pause: EventSubscription.Last,
pipe: EventSubscription.First,
readable: EventSubscription.Last,
resume: EventSubscription.Last,
unpipe: EventSubscription.First,
};
type AllStreams =
| NodeJS.ReadableStream
| NodeJS.ReadWriteStream
| NodeJS.WritableStream;
export class Compose extends Duplex {
export class Compose extends Transform {
private first: AllStreams;
private last: AllStreams;
private streams: AllStreams[];
private inputStream: ReadableStream;
constructor(streams: AllStreams[], options?: DuplexOptions) {
constructor(
streams: AllStreams[],
errorCallback?: (err: any) => void,
options?: TransformOptions,
) {
super(options);
this.first = streams[0];
this.first = new PassThrough(options);
this.last = streams[streams.length - 1];
this.streams = streams;
pipeline(streams, (err: any) => {
this.emit("error", err);
pipeline(
[this.first, ...streams],
errorCallback ||
((error: any) => {
if (error) {
this.emit("error", error);
}
}),
);
if (isReadable(this.last)) {
(this.last as NodeJS.ReadWriteStream).pipe(
new Transform({
...options,
transform: (d: any, encoding, cb) => {
this.push(d);
cb();
},
}),
);
}
}
public _transform(chunk: any, encoding: string, cb: any) {
(this.first as NodeJS.WritableStream).write(chunk, encoding, cb);
}
public _flush(cb: any) {
if (isReadable(this.first)) {
(this.first as any).push(null);
}
this.last.once("end", () => {
cb();
});
}
public pipe<T extends NodeJS.WritableStream>(dest: T) {
return (this.last as NodeJS.ReadableStream).pipe(dest);
}
public _write(chunk: any, encoding: string, cb: any) {
(this.first as NodeJS.WritableStream).write(chunk, encoding, cb);
public _destroy(error: any, cb: (error?: any) => void) {
this.streams.forEach(s => (s as any).destroy());
cb(error);
}
public bubble(...events: string[]) {
@ -69,38 +85,4 @@ export class Compose extends Duplex {
});
});
}
public on(event: string, cb: any) {
switch (eventsTarget[event]) {
case EventSubscription.First:
this.first.on(event, cb);
break;
case EventSubscription.Last:
this.last.on(event, cb);
break;
case EventSubscription.All:
this.streams.forEach(s => s.on(event, cb));
break;
default:
super.on(event, cb);
}
return this;
}
public once(event: string, cb: any) {
switch (eventsTarget[event]) {
case EventSubscription.First:
this.first.once(event, cb);
break;
case EventSubscription.Last:
this.last.once(event, cb);
break;
case EventSubscription.All:
this.streams.forEach(s => s.once(event, cb));
break;
default:
super.once(event, cb);
}
return this;
}
}

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);
}
if (!this.streamsByKey[destKey].write(chunk, encoding)) {
this.streamsByKey[destKey].once("drain", () => {
cb();
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`,
);
}
});
} else {
cb();
}
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 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),
);
break;
default:
super.on(event, cb);
}
return this;
public _flush() {
const pipelines: DemuxStreams[] = Array.prototype.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 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;
public _destroy(error: any, cb: (error?: any) => void) {
const pipelines: DemuxStreams[] = [].concat.apply(
[],
Object.values(this.streamsByKey),
);
pipelines.forEach(p => (p as any).destroy());
cb(error);
}
}

View File

@ -28,7 +28,7 @@ import { unbatch } from "./unbatch";
import { compose } from "./compose";
import { demux } from "./demux";
export default function mhysa(defaultOptions?: TransformOptions) {
export function strom(defaultOptions: TransformOptions = { objectMode: true }) {
function withDefaultOptions<T extends any[], R>(
n: number,
fn: (...args: T) => R,
@ -121,6 +121,10 @@ export default function mhysa(defaultOptions?: TransformOptions) {
/**
* Return a ReadWrite stream that parses the streamed chunks as JSON. Each streamed chunk
* must be a fully defined JSON string in utf8.
* @param format: @type SerializationFormats defaults SerializationFormats.utf8
* @param emitError: @type boolean Whether or not to emit an error when
* failing to parse. An error will automatically close the stream.
* Defaults to true.
*/
parse,
@ -245,9 +249,10 @@ export default function mhysa(defaultOptions?: TransformOptions) {
/**
* Composes multiple streams together. Writing occurs on first stream, piping occurs from last stream.
* @param streams Array of streams to compose. Minimum of two.
* @param errorCallback a function that handles any error coming out of the pipeline
* @param options Transform stream options
*/
compose: withDefaultOptions(1, compose),
compose: withDefaultOptions(2, compose),
/**
* Composes multiple streams together. Writing occurs on first stream, piping occurs from last stream.
@ -258,5 +263,10 @@ export default function mhysa(defaultOptions?: TransformOptions) {
* @param options Writable stream options
*/
demux: withDefaultOptions(2, demux),
/**
* Create a new strom instance overriding the defaults
*/
instance: strom,
};
}

View File

@ -4,6 +4,7 @@ import { SerializationFormats } from "./baseDefinitions";
export function parse(
format: SerializationFormats = SerializationFormats.utf8,
emitError: boolean = true,
): Transform {
const decoder = new StringDecoder(format);
return new Transform({
@ -13,9 +14,13 @@ export function parse(
try {
const asString = decoder.write(chunk);
// Using await causes parsing errors to be emitted
callback(undefined, await JSON.parse(asString));
callback(null, await JSON.parse(asString));
} catch (err) {
callback(err);
if (emitError) {
callback(err);
} else {
callback();
}
}
},
});

View File

@ -2,20 +2,41 @@ import { Transform, TransformOptions } from "stream";
import { performance } from "perf_hooks";
import { sleep } from "../helpers";
export enum Behavior {
BUFFER = 0,
DROP = 1,
}
export interface RateOptions {
window?: number;
behavior?: Behavior;
}
export function rate(
targetRate: number = 50,
period: number = 1,
options?: TransformOptions,
options?: TransformOptions & RateOptions,
): Transform {
const deltaMS = ((1 / targetRate) * 1000) / period; // Skip a full period
let total = 0;
const start = performance.now();
const window = options?.window || Infinity;
const behavior = options?.behavior || Behavior.BUFFER;
let start = performance.now();
return new Transform({
...options,
async transform(data, encoding, callback) {
const currentRate = (total / (performance.now() - start)) * 1000;
const now = performance.now();
if (now - start >= window) {
start = now - window;
}
const currentRate = (total / (now - start)) * 1000;
if (targetRate && currentRate > targetRate) {
await sleep(deltaMS);
if (behavior === Behavior.DROP) {
callback(undefined);
return;
} else {
await sleep(deltaMS);
}
}
total += 1;
callback(undefined, data);

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,29 @@
import mhysa from "./functions";
export default mhysa;
import { strom } from "./functions";
export * from "./utils";
export const {
fromArray,
map,
flatMap,
filter,
reduce,
split,
join,
replace,
parse,
stringify,
collect,
concat,
merge,
duplex,
child,
last,
batch,
unbatch,
rate,
parallelMap,
accumulator,
accumulatorBy,
compose,
demux,
instance,
} = strom();

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

@ -1,10 +1,9 @@
import test from "ava";
import { expect } from "chai";
import { Readable } from "stream";
import mhysa from "../src";
import { accumulator, accumulatorBy } from "../src";
import { FlushStrategy } from "../src/functions/accumulator";
import { performance } from "perf_hooks";
const { accumulator, accumulatorBy } = mhysa({ objectMode: true });
test.cb("accumulator() rolling", t => {
t.plan(3);
@ -14,8 +13,14 @@ test.cb("accumulator() rolling", t => {
key: string;
}
const source = new Readable({ objectMode: true });
const firstFlush = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const secondFlush = [{ ts: 2, key: "d" }, { ts: 3, key: "e" }];
const firstFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const secondFlush = [
{ ts: 2, key: "d" },
{ ts: 3, key: "e" },
];
const thirdFlush = [{ ts: 4, key: "f" }];
const flushes = [firstFlush, secondFlush, thirdFlush];
@ -88,7 +93,10 @@ test.cb(
"nonExistingKey",
{ objectMode: true },
);
const input = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const input = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
source
.pipe(accumulatorStream)
@ -182,7 +190,10 @@ test.cb("accumulator() sliding", t => {
{ ts: 4, key: "d" },
];
const firstFlush = [{ ts: 0, key: "a" }];
const secondFlush = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const secondFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const thirdFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
@ -232,7 +243,10 @@ test.cb("accumulator() sliding with key", t => {
{ ts: 6, key: "g" },
];
const firstFlush = [{ ts: 0, key: "a" }];
const secondFlush = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const secondFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const thirdFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
@ -243,8 +257,14 @@ test.cb("accumulator() sliding with key", t => {
{ ts: 2, key: "c" },
{ ts: 3, key: "d" },
];
const fifthFlush = [{ ts: 3, key: "d" }, { ts: 5, key: "f" }];
const sixthFlush = [{ ts: 5, key: "f" }, { ts: 6, key: "g" }];
const fifthFlush = [
{ ts: 3, key: "d" },
{ ts: 5, key: "f" },
];
const sixthFlush = [
{ ts: 5, key: "f" },
{ ts: 6, key: "g" },
];
const flushes = [
firstFlush,
@ -286,7 +306,10 @@ test.cb(
"nonExistingKey",
{ objectMode: true },
);
const input = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const input = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
source
.pipe(accumulatorStream)
@ -334,10 +357,22 @@ test.cb(
{ ts: 6, key: "g" },
];
const firstFlush = [{ ts: 0, key: "a" }];
const secondFlush = [{ ts: 0, key: "a" }, { ts: 2, key: "c" }];
const thirdFlush = [{ ts: 2, key: "c" }, { ts: 3, key: "d" }];
const fourthFlush = [{ ts: 3, key: "d" }, { ts: 5, key: "f" }];
const fifthFlush = [{ ts: 5, key: "f" }, { ts: 6, key: "g" }];
const secondFlush = [
{ ts: 0, key: "a" },
{ ts: 2, key: "c" },
];
const thirdFlush = [
{ ts: 2, key: "c" },
{ ts: 3, key: "d" },
];
const fourthFlush = [
{ ts: 3, key: "d" },
{ ts: 5, key: "f" },
];
const fifthFlush = [
{ ts: 5, key: "f" },
{ ts: 6, key: "g" },
];
const flushes = [
firstFlush,
@ -469,7 +504,10 @@ test.cb("accumulatorBy() sliding", t => {
{ ts: 6, key: "g" },
];
const firstFlush = [{ ts: 0, key: "a" }];
const secondFlush = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const secondFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const thirdFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
@ -480,8 +518,14 @@ test.cb("accumulatorBy() sliding", t => {
{ ts: 2, key: "c" },
{ ts: 3, key: "d" },
];
const fifthFlush = [{ ts: 3, key: "d" }, { ts: 5, key: "f" }];
const sixthFlush = [{ ts: 5, key: "f" }, { ts: 6, key: "g" }];
const fifthFlush = [
{ ts: 3, key: "d" },
{ ts: 5, key: "f" },
];
const sixthFlush = [
{ ts: 5, key: "f" },
{ ts: 6, key: "g" },
];
const flushes = [
firstFlush,

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { batch } = mhysa({ objectMode: true });
import { batch, map, fromArray } from "../src";
test.cb("batch() batches chunks together", t => {
t.plan(3);
@ -39,7 +38,7 @@ test.cb("batch() yields a batch after the timeout", t => {
const expectedElements = [["a", "b"], ["c"], ["d"]];
let i = 0;
source
.pipe(batch(3))
.pipe(batch(3, 500))
.on("data", (element: string[]) => {
t.deepEqual(element, expectedElements[i]);
i++;
@ -57,3 +56,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

@ -2,8 +2,7 @@ import * as cp from "child_process";
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { child } = mhysa();
import { child } from "../src";
test.cb(
"child() allows easily writing to child process stdin and reading from its stdout",

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { collect } = mhysa();
import { collect } from "../src";
test.cb(
"collect() collects streamed elements into an array (object, flowing mode)",
@ -59,7 +58,7 @@ test.cb(
const source = new Readable({ objectMode: false });
source
.pipe(collect())
.pipe(collect({ objectMode: false }))
.on("data", collected => {
expect(collected).to.deep.equal(Buffer.from("abc"));
t.pass();

View File

@ -1,9 +1,9 @@
const test = require("ava");
const { expect } = require("chai");
const { sleep } = require("../src/helpers");
import mhysa from "../src";
import * as test from "ava";
import { expect } from "chai";
import { sleep } from "../src/helpers";
import { Readable, Writable } from "stream";
import { compose, map, fromArray } from "../src";
import { performance } from "perf_hooks";
const { compose, map } = mhysa({ objectMode: true });
test.cb("compose() chains two streams together in the correct order", t => {
t.plan(3);
@ -22,10 +22,7 @@ test.cb("compose() chains two streams together in the correct order", t => {
return chunk;
});
const composed = compose(
[first, second],
{ objectMode: true },
);
const composed = compose([first, second]);
composed.on("data", data => {
expect(data).to.deep.equal(result[i]);
@ -35,12 +32,6 @@ test.cb("compose() chains two streams together in the correct order", t => {
t.end();
}
});
composed.on("error", err => {
t.end(err);
});
composed.on("end", () => {
t.end();
});
const input = [
{ key: "a", visited: [] },
@ -72,10 +63,7 @@ test.cb("piping compose() maintains correct order", t => {
return chunk;
});
const composed = compose(
[first, second],
{ objectMode: true },
);
const composed = compose([first, second]);
const third = map((chunk: Chunk) => {
chunk.visited.push(3);
return chunk;
@ -109,34 +97,25 @@ 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;
mapped: number[];
}
const first = map(
async (chunk: Chunk) => {
chunk.mapped.push(1);
return chunk;
},
{
objectMode: true,
},
);
const first = map(async (chunk: Chunk) => {
chunk.mapped.push(1);
return chunk;
});
const second = map(
async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
},
{ objectMode: true },
);
const second = map(async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
});
const composed = compose(
[first, second],
{ objectMode: true, highWaterMark: 2 },
);
const composed = compose([first, second], undefined, {
highWaterMark: 2,
});
composed.on("error", err => {
reject();
});
@ -160,19 +139,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) => {
@ -180,29 +152,20 @@ test("compose() should emit drain event ~rate * highWaterMark ms for every write
key: string;
mapped: number[];
}
const first = map(
async (chunk: Chunk) => {
await sleep(_rate);
chunk.mapped.push(1);
return chunk;
},
{
objectMode: true,
},
);
const first = map(async (chunk: Chunk) => {
await sleep(_rate);
chunk.mapped.push(1);
return chunk;
});
const second = map(
async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
},
{ objectMode: true },
);
const second = map(async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
});
const composed = compose(
[first, second],
{ objectMode: true, highWaterMark },
);
const composed = compose([first, second], undefined, {
highWaterMark,
});
composed.on("error", err => {
reject();
});
@ -210,19 +173,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: [] },
@ -230,19 +188,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);
});
});
@ -255,29 +201,20 @@ test.cb(
key: string;
mapped: number[];
}
const first = map(
async (chunk: Chunk) => {
await sleep(_rate);
chunk.mapped.push(1);
return chunk;
},
{
objectMode: true,
},
);
const first = map(async (chunk: Chunk) => {
await sleep(_rate);
chunk.mapped.push(1);
return chunk;
});
const second = map(
async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
},
{ objectMode: true },
);
const second = map(async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
});
const composed = compose(
[first, second],
{ objectMode: true, highWaterMark: 5 },
);
const composed = compose([first, second], undefined, {
highWaterMark: 5,
});
composed.on("error", err => {
t.end(err);
@ -285,10 +222,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();
});
@ -309,7 +242,6 @@ test.cb(
input.forEach(item => {
composed.write(item);
});
const start = performance.now();
},
);
@ -322,15 +254,10 @@ test.cb(
key: string;
mapped: number[];
}
const first = map(
(chunk: Chunk) => {
chunk.mapped.push(1);
return chunk;
},
{
objectMode: true,
},
);
const first = map((chunk: Chunk) => {
chunk.mapped.push(1);
return chunk;
});
const second = map(
async (chunk: Chunk) => {
@ -341,13 +268,12 @@ test.cb(
chunk.mapped.push(2);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
const composed = compose(
[first, second],
{ objectMode: true, highWaterMark: 5 },
);
const composed = compose([first, second], undefined, {
highWaterMark: 5,
});
composed.on("error", err => {
t.end(err);
});
@ -398,7 +324,6 @@ test.cb(
return chunk;
},
{
objectMode: true,
highWaterMark: 2,
},
);
@ -410,13 +335,12 @@ test.cb(
chunk.mapped.push("second");
return chunk;
},
{ objectMode: true, highWaterMark: 2 },
{ highWaterMark: 2 },
);
const composed = compose(
[first, second],
{ objectMode: true, highWaterMark: 5 },
);
const composed = compose([first, second], undefined, {
highWaterMark: 5,
});
composed.on("error", err => {
t.end(err);
});
@ -458,29 +382,20 @@ test.cb(
key: string;
mapped: number[];
}
const first = map(
async (chunk: Chunk) => {
await sleep(_rate);
chunk.mapped.push(1);
return chunk;
},
{
objectMode: true,
},
);
const first = map(async (chunk: Chunk) => {
await sleep(_rate);
chunk.mapped.push(1);
return chunk;
});
const second = map(
async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
},
{ objectMode: true },
);
const second = map(async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
});
const composed = compose(
[first, second],
{ objectMode: true, highWaterMark: 6 },
);
const composed = compose([first, second], undefined, {
highWaterMark: 6,
});
composed.on("error", err => {
t.end(err);
@ -510,3 +425,124 @@ test.cb(
});
},
);
test.cb("compose() should be 'destroyable'", t => {
t.plan(3);
const _sleep = 100;
interface Chunk {
key: string;
mapped: number[];
}
const first = map(async (chunk: Chunk) => {
await sleep(_sleep);
chunk.mapped.push(1);
return chunk;
});
const second = map(async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
});
const composed = compose([first, second], (err: any) => {
t.pass();
});
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, [1, 2]);
if (cur.key === "a") {
composed.destroy();
}
cb();
},
});
composed.on("close", t.end);
fakeSource.pipe(composed).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]);
});
test.cb("compose() `finish` and `end` propagates", t => {
interface Chunk {
key: string;
mapped: number[];
}
t.plan(8);
const first = map(async (chunk: Chunk) => {
chunk.mapped.push(1);
return chunk;
});
const second = map(async (chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
});
const composed = compose([first, second], undefined, {
highWaterMark: 3,
});
const fakeSource = new Readable({
objectMode: true,
read() {
return;
},
});
const sink = map((d: Chunk) => {
const curr = input.shift();
t.is(curr.key, d.key);
t.deepEqual(d.mapped, [1, 2]);
});
fakeSource.pipe(composed).pipe(sink);
fakeSource.on("end", () => {
t.pass();
});
composed.on("finish", () => {
t.pass();
});
composed.on("end", () => {
t.pass();
t.end();
});
sink.on("finish", () => {
t.pass();
});
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(null);
});

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { concat, collect } = mhysa();
import { concat, collect } from "../src";
test.cb(
"concat() concatenates multiple readable streams (object, flowing mode)",
@ -172,7 +171,7 @@ test.cb(
test.cb("concat() concatenates empty list of readable streams", t => {
t.plan(0);
concat()
.pipe(collect())
.pipe(collect({ objectMode: false }))
.on("data", _ => {
t.fail();
})

View File

@ -1,21 +1,30 @@
import { Readable } from "stream";
import test from "ava";
import mhysa from "../src";
import { batch as _batch, instance as strom } from "../src";
const withDefaultOptions = mhysa({ objectMode: true });
const withoutOptions = mhysa();
const withDefaultOptions = strom({ objectMode: false });
test("Mhysa instances can have default options", t => {
test("strom instances can have default options", t => {
let batch = withDefaultOptions.batch();
t.true(batch._readableState.objectMode);
t.true(batch._writableState.objectMode);
t.false(batch._readableState.objectMode);
t.false(batch._writableState.objectMode);
batch = withDefaultOptions.batch(3);
t.true(batch._readableState.objectMode);
t.true(batch._writableState.objectMode);
t.false(batch._readableState.objectMode);
t.false(batch._writableState.objectMode);
batch = withDefaultOptions.batch(3, 1);
t.false(batch._readableState.objectMode);
t.false(batch._writableState.objectMode);
batch = withDefaultOptions.batch(3, 1, { objectMode: true });
t.true(batch._readableState.objectMode);
t.true(batch._writableState.objectMode);
batch = withDefaultOptions.batch(3, 1, { objectMode: false });
batch = _batch(3);
t.true(batch._readableState.objectMode);
t.true(batch._writableState.objectMode);
batch = _batch(3, 1);
t.true(batch._readableState.objectMode);
t.true(batch._writableState.objectMode);
batch = _batch(3, 1, { objectMode: false });
t.false(batch._readableState.objectMode);
t.false(batch._writableState.objectMode);
});

View File

@ -1,11 +1,10 @@
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
import { Writable } from "stream";
const sinon = require("sinon");
const { sleep } = require("../src/helpers");
import { demux, map, fromArray } from "../src";
import { Writable, Readable } from "stream";
import * as sinon from "sinon";
import { sleep } from "../src/helpers";
import { performance } from "perf_hooks";
const { demux, map } = mhysa();
interface Test {
key: string;
@ -31,7 +30,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 +40,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 +92,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 +110,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 +133,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 +143,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 +167,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 +185,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 +212,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 +228,6 @@ test("demux() write should return false after if it has >= highWaterMark items b
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark,
});
@ -229,7 +251,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 +277,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 +290,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 +317,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 +339,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 +351,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 +374,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 +403,7 @@ test.cb.only(
chunk.mapped.push(1);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
const second = map(
@ -392,25 +412,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 +445,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 +463,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 +478,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 +494,7 @@ test.cb(
chunk.mapped.push(3);
return chunk;
},
{ objectMode: true, highWaterMark: 1 },
{ highWaterMark: 1 },
);
first
@ -487,18 +504,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 +530,7 @@ test.cb(
let pendingReads = input.length;
const start = performance.now();
input.forEach(item => {
_demux.write(item);
});
fromArray(input).pipe(_demux);
},
);
@ -536,36 +549,37 @@ 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 => {
pendingReads--;
if (chunk.key === "b") {
expect(performance.now() - start).to.be.greaterThan(
slowProcessorSpeed * totalItems,
);
t.pass();
expect(pendingReads).to.equal(0);
resolve();
}
});
return first;
};
const _demux = demux(construct, "key", {
objectMode: true,
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(
slowProcessorSpeed * totalItems,
);
t.pass();
expect(pendingReads).to.equal(0);
resolve();
}
});
const input = [
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "c", mapped: [] },
{ key: "c", mapped: [] },
{ key: "c", mapped: [] },
{ key: "b", mapped: [] },
];
@ -584,74 +598,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) => {
interface Chunk {
key: string;
mapped: number[];
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 sink = new Writable({
objectMode: true,
write(chunk, encoding, cb) {
expect(chunk.mapped).to.deep.equal([1, 2]);
t.pass();
cb();
if (pendingReads === 0) {
resolve();
}
},
});
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;
});
const construct = (destKey: string) => {
const first = map(
(chunk: Chunk) => {
expect(first._readableState.length).to.be.at.most(2);
chunk.mapped.push(1);
return chunk;
},
{ objectMode: true, highWaterMark: 2 },
);
return dest;
};
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 },
);
const demuxed = demux(construct, "key", {});
first.pipe(second).pipe(sink);
return first;
};
fromArray(input).pipe(demuxed);
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark,
});
_demux.on("error", err => {
reject();
});
_demux.on("drain", () => {
expect(_demux._writableState.length).to.be.equal(0);
t.pass();
});
const input = [
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
];
let pendingReads = input.length;
input.forEach(item => {
_demux.write(item);
});
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[];
}
t.plan(9);
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);
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: "b", mapped: [] },
];
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

@ -2,8 +2,7 @@ import * as cp from "child_process";
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { duplex } = mhysa();
import { duplex } from "../src";
test.cb(
"duplex() combines a writable and readable stream into a ReadWrite stream",

View File

@ -1,8 +1,7 @@
import test from "ava";
import { expect } from "chai";
import { Readable } from "stream";
import mhysa from "../src";
const { filter } = mhysa();
import { filter } from "../src";
test.cb("filter() filters elements synchronously", t => {
t.plan(2);

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { flatMap } = mhysa({ objectMode: true });
import { flatMap } from "../src";
test.cb("flatMap() maps elements synchronously", t => {
t.plan(6);

View File

@ -1,7 +1,6 @@
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { fromArray } = mhysa();
import { fromArray } from "../src";
test.cb("fromArray() streams array elements in flowing mode", t => {
t.plan(3);

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { join } = mhysa();
import { join } from "../src";
test.cb("join() joins chunks using the specified separator", t => {
t.plan(9);

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { last } = mhysa();
import { last } from "../src";
test("last() resolves to the last chunk streamed by the given readable stream", async t => {
const source = new Readable({ objectMode: true });

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { map } = mhysa();
import { map } from "../src";
test.cb("map() maps elements synchronously", t => {
t.plan(3);

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { merge } = mhysa();
import { merge } from "../src";
test.cb(
"merge() merges multiple readable streams in chunk arrival order",

View File

@ -2,9 +2,8 @@ import { Readable } from "stream";
import { performance } from "perf_hooks";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
import { parallelMap } from "../src";
import { sleep } from "../src/helpers";
const { parallelMap } = mhysa({ objectMode: true });
test.cb("parallelMap() parallel mapping", t => {
t.plan(6);

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import { Readable, finished } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { parse } = mhysa();
import { parse } from "../src";
test.cb("parse() parses the streamed elements as JSON", t => {
t.plan(3);
@ -26,13 +25,17 @@ test.cb("parse() parses the streamed elements as JSON", t => {
});
test.cb("parse() emits errors on invalid JSON", t => {
t.plan(2);
t.plan(1);
const source = new Readable({ objectMode: true });
source
.pipe(parse())
.resume()
.on("error", () => t.pass())
.on("end", t.end);
.on("error", (d: any) => {
t.pass();
t.end();
})
.on("end", t.fail);
source.push("{}");
source.push({});

View File

@ -1,12 +1,11 @@
import { Readable } from "stream";
import { performance } from "perf_hooks";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { rate } = mhysa({ objectMode: true });
import { rate } from "../src";
import { sleep } from "../src/helpers";
test.cb("rate() sends data at a rate of 150", t => {
t.plan(5);
t.plan(15);
const targetRate = 150;
const source = new Readable({ objectMode: true });
const expectedElements = ["a", "b", "c", "d", "e"];
@ -15,10 +14,10 @@ test.cb("rate() sends data at a rate of 150", t => {
source
.pipe(rate(targetRate))
.on("data", (element: string[]) => {
.on("data", (element: string) => {
const currentRate = (i / (performance.now() - start)) * 1000;
expect(element).to.deep.equal(expectedElements[i]);
expect(currentRate).lessThan(targetRate);
t.is(element, expectedElements[i]);
t.true(currentRate <= targetRate);
t.pass();
i++;
})
@ -34,7 +33,7 @@ test.cb("rate() sends data at a rate of 150", t => {
});
test.cb("rate() sends data at a rate of 50", t => {
t.plan(5);
t.plan(15);
const targetRate = 50;
const source = new Readable({ objectMode: true });
const expectedElements = ["a", "b", "c", "d", "e"];
@ -43,10 +42,10 @@ test.cb("rate() sends data at a rate of 50", t => {
source
.pipe(rate(targetRate))
.on("data", (element: string[]) => {
.on("data", (element: string) => {
const currentRate = (i / (performance.now() - start)) * 1000;
expect(element).to.deep.equal(expectedElements[i]);
expect(currentRate).lessThan(targetRate);
t.is(element, expectedElements[i]);
t.true(currentRate <= targetRate);
t.pass();
i++;
})
@ -62,7 +61,7 @@ test.cb("rate() sends data at a rate of 50", t => {
});
test.cb("rate() sends data at a rate of 1", t => {
t.plan(5);
t.plan(15);
const targetRate = 1;
const source = new Readable({ objectMode: true });
const expectedElements = ["a", "b", "c", "d", "e"];
@ -71,10 +70,10 @@ test.cb("rate() sends data at a rate of 1", t => {
source
.pipe(rate(targetRate))
.on("data", (element: string[]) => {
.on("data", (element: string) => {
const currentRate = (i / (performance.now() - start)) * 1000;
expect(element).to.deep.equal(expectedElements[i]);
expect(currentRate).lessThan(targetRate);
t.is(element, expectedElements[i]);
t.true(currentRate <= targetRate);
t.pass();
i++;
})
@ -88,3 +87,41 @@ test.cb("rate() sends data at a rate of 1", t => {
source.push("e");
source.push(null);
});
test("rate() sends data at a rate of 1 and drops extra messages", async t => {
t.plan(9);
const targetRate = 1;
const source = new Readable({
objectMode: true,
read: () => {
return;
},
});
const expectedElements = ["a", "b", "e"];
const start = performance.now();
let i = 0;
let plan = 0;
source
.pipe(rate(targetRate, 1, { behavior: 1 }))
.on("data", (element: string) => {
const currentRate = (i / (performance.now() - start)) * 1000;
t.is(element, expectedElements[i]);
t.true(currentRate <= targetRate);
plan++;
t.pass();
i++;
})
.on("error", t.fail)
.on("end", t.fail);
source.push("a");
await sleep(1000);
source.push("b");
source.push("c");
source.push("d");
await sleep(1000);
source.push("e");
await sleep(1000);
source.push(null);
});

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { reduce } = mhysa({ objectMode: true });
import { reduce } from "../src";
test.cb("reduce() reduces elements synchronously", t => {
t.plan(1);

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { replace } = mhysa();
import { replace } from "../src";
test.cb(
"replace() replaces occurrences of the given string in the streamed elements with the specified " +

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { split } = mhysa();
import { split } from "../src";
test.cb("split() splits chunks using the default separator (\\n)", t => {
t.plan(5);

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { stringify } = mhysa();
import { stringify } from "../src";
test.cb("stringify() stringifies the streamed elements as JSON", t => {
t.plan(4);

View File

@ -1,8 +1,7 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import mhysa from "../src";
const { unbatch, batch } = mhysa({ objectMode: true });
import { unbatch, batch } from "../src";
test.cb("unbatch() unbatches", t => {
t.plan(3);

View File

@ -0,0 +1,8 @@
import test from "ava";
import { collected } from "../../src/utils";
import { fromArray, collect } from "../../src";
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]);
});

2722
yarn.lock

File diff suppressed because it is too large Load Diff