summaryrefslogtreecommitdiff
path: root/deps/npm/node_modules/worker-farm
diff options
context:
space:
mode:
Diffstat (limited to 'deps/npm/node_modules/worker-farm')
-rw-r--r--deps/npm/node_modules/worker-farm/.editorconfig16
-rw-r--r--deps/npm/node_modules/worker-farm/.travis.yml12
-rw-r--r--deps/npm/node_modules/worker-farm/LICENSE.md13
-rw-r--r--deps/npm/node_modules/worker-farm/README.md150
-rw-r--r--deps/npm/node_modules/worker-farm/examples/basic/child.js5
-rw-r--r--deps/npm/node_modules/worker-farm/examples/basic/index.js13
-rw-r--r--deps/npm/node_modules/worker-farm/examples/pi/calc.js22
-rw-r--r--deps/npm/node_modules/worker-farm/examples/pi/index.js41
-rw-r--r--deps/npm/node_modules/worker-farm/index.d.ts55
-rw-r--r--deps/npm/node_modules/worker-farm/lib/child/index.js56
-rw-r--r--deps/npm/node_modules/worker-farm/lib/farm.js348
-rw-r--r--deps/npm/node_modules/worker-farm/lib/fork.js33
-rw-r--r--deps/npm/node_modules/worker-farm/lib/index.js34
-rw-r--r--deps/npm/node_modules/worker-farm/package.json61
-rw-r--r--deps/npm/node_modules/worker-farm/tests/child.js87
-rw-r--r--deps/npm/node_modules/worker-farm/tests/debug.js12
-rw-r--r--deps/npm/node_modules/worker-farm/tests/index.js616
17 files changed, 0 insertions, 1574 deletions
diff --git a/deps/npm/node_modules/worker-farm/.editorconfig b/deps/npm/node_modules/worker-farm/.editorconfig
deleted file mode 100644
index feaebc2315..0000000000
--- a/deps/npm/node_modules/worker-farm/.editorconfig
+++ /dev/null
@@ -1,16 +0,0 @@
-# This file is for unifying the coding style for different editors and IDEs
-# editorconfig.org
-
-root = true
-
-[*]
-end_of_line = lf
-charset = utf-8
-insert_final_newline = true
-trim_trailing_whitespace = true
-indent_style = space
-indent_size = 2
-
-[*.js]
-max_line_length = 80
-View
diff --git a/deps/npm/node_modules/worker-farm/.travis.yml b/deps/npm/node_modules/worker-farm/.travis.yml
deleted file mode 100644
index 7af56429c0..0000000000
--- a/deps/npm/node_modules/worker-farm/.travis.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-language: node_js
-node_js:
- - 6
- - 8
- - 10
- - 12
-branches:
- only:
- - master
-notifications:
- email:
- - rod@vagg.org
diff --git a/deps/npm/node_modules/worker-farm/LICENSE.md b/deps/npm/node_modules/worker-farm/LICENSE.md
deleted file mode 100644
index 274c9b4607..0000000000
--- a/deps/npm/node_modules/worker-farm/LICENSE.md
+++ /dev/null
@@ -1,13 +0,0 @@
-The MIT License (MIT)
-=====================
-
-Copyright (c) 2014 LevelUP contributors
----------------------------------------
-
-*LevelUP contributors listed at <https://github.com/rvagg/node-levelup#contributors>*
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/deps/npm/node_modules/worker-farm/README.md b/deps/npm/node_modules/worker-farm/README.md
deleted file mode 100644
index c52689ed9f..0000000000
--- a/deps/npm/node_modules/worker-farm/README.md
+++ /dev/null
@@ -1,150 +0,0 @@
-# Worker Farm [![Build Status](https://secure.travis-ci.org/rvagg/node-worker-farm.svg)](http://travis-ci.org/rvagg/node-worker-farm)
-
-[![NPM](https://nodei.co/npm/worker-farm.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/worker-farm/) [![NPM](https://nodei.co/npm-dl/worker-farm.png?months=6&height=3)](https://nodei.co/npm/worker-farm/)
-
-
-Distribute processing tasks to child processes with an über-simple API and baked-in durability & custom concurrency options. *Available in npm as <strong>worker-farm</strong>*.
-
-## Example
-
-Given a file, *child.js*:
-
-```js
-module.exports = function (inp, callback) {
- callback(null, inp + ' BAR (' + process.pid + ')')
-}
-```
-
-And a main file:
-
-```js
-var workerFarm = require('worker-farm')
- , workers = workerFarm(require.resolve('./child'))
- , ret = 0
-
-for (var i = 0; i < 10; i++) {
- workers('#' + i + ' FOO', function (err, outp) {
- console.log(outp)
- if (++ret == 10)
- workerFarm.end(workers)
- })
-}
-```
-
-We'll get an output something like the following:
-
-```
-#1 FOO BAR (8546)
-#0 FOO BAR (8545)
-#8 FOO BAR (8545)
-#9 FOO BAR (8546)
-#2 FOO BAR (8548)
-#4 FOO BAR (8551)
-#3 FOO BAR (8549)
-#6 FOO BAR (8555)
-#5 FOO BAR (8553)
-#7 FOO BAR (8557)
-```
-
-This example is contained in the *[examples/basic](https://github.com/rvagg/node-worker-farm/tree/master/examples/basic/)* directory.
-
-### Example #1: Estimating π using child workers
-
-You will also find a more complex example in *[examples/pi](https://github.com/rvagg/node-worker-farm/tree/master/examples/pi/)* that estimates the value of **π** by using a Monte Carlo *area-under-the-curve* method and compares the speed of doing it all in-process vs using child workers to complete separate portions.
-
-Running `node examples/pi` will give you something like:
-
-```
-Doing it the slow (single-process) way...
-π ≈ 3.1416269360000006 (0.0000342824102075312 away from actual!)
-took 8341 milliseconds
-Doing it the fast (multi-process) way...
-π ≈ 3.1416233600000036 (0.00003070641021052367 away from actual!)
-took 1985 milliseconds
-```
-
-## Durability
-
-An important feature of Worker Farm is **call durability**. If a child process dies for any reason during the execution of call(s), those calls will be re-queued and taken care of by other child processes. In this way, when you ask for something to be done, unless there is something *seriously* wrong with what you're doing, you should get a result on your callback function.
-
-## My use-case
-
-There are other libraries for managing worker processes available but my use-case was fairly specific: I need to make heavy use of the [node-java](https://github.com/nearinfinity/node-java) library to interact with JVM code. Unfortunately, because the JVM garbage collector is so difficult to interact with, it's prone to killing your Node process when the GC kicks under heavy load. For safety I needed a durable way to make calls so that (1) it wouldn't kill my main process and (2) any calls that weren't successful would be resubmitted for processing.
-
-Worker Farm allows me to spin up multiple JVMs to be controlled by Node, and have a single, uncomplicated API that acts the same way as an in-process API and the calls will be taken care of by a child process even if an error kills a child process while it is working as the call will simply be passed to a new child process.
-
-**But**, don't think that Worker Farm is specific to that use-case, it's designed to be very generic and simple to adapt to anything requiring the use of child Node processes.
-
-## API
-
-Worker Farm exports a main function and an `end()` method. The main function sets up a "farm" of coordinated child-process workers and it can be used to instantiate multiple farms, all operating independently.
-
-### workerFarm([options, ]pathToModule[, exportedMethods])
-
-In its most basic form, you call `workerFarm()` with the path to a module file to be invoked by the child process. You should use an **absolute path** to the module file, the best way to obtain the path is with `require.resolve('./path/to/module')`, this function can be used in exactly the same way as `require('./path/to/module')` but it returns an absolute path.
-
-#### `exportedMethods`
-
-If your module exports a single function on `module.exports` then you should omit the final parameter. However, if you are exporting multiple functions on `module.exports` then you should list them in an Array of Strings:
-
-```js
-var workers = workerFarm(require.resolve('./mod'), [ 'doSomething', 'doSomethingElse' ])
-workers.doSomething(function () {})
-workers.doSomethingElse(function () {})
-```
-
-Listing the available methods will instruct Worker Farm what API to provide you with on the returned object. If you don't list a `exportedMethods` Array then you'll get a single callable function to use; but if you list the available methods then you'll get an object with callable functions by those names.
-
-**It is assumed that each function you call on your child module will take a `callback` function as the last argument.**
-
-#### `options`
-
-If you don't provide an `options` object then the following defaults will be used:
-
-```js
-{
- workerOptions : {}
- , maxCallsPerWorker : Infinity
- , maxConcurrentWorkers : require('os').cpus().length
- , maxConcurrentCallsPerWorker : 10
- , maxConcurrentCalls : Infinity
- , maxCallTime : Infinity
- , maxRetries : Infinity
- , autoStart : false
- , onChild : function() {}
-}
-```
-
- * **<code>workerOptions</code>** allows you to customize all the parameters passed to child nodes. This object supports [all possible options of `child_process.fork`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options). The default options passed are the parent `execArgv`, `cwd` and `env`. Any (or all) of them can be overridden, and others can be added as well.
-
- * **<code>maxCallsPerWorker</code>** allows you to control the lifespan of your child processes. A positive number will indicate that you only want each child to accept that many calls before it is terminated. This may be useful if you need to control memory leaks or similar in child processes.
-
- * **<code>maxConcurrentWorkers</code>** will set the number of child processes to maintain concurrently. By default it is set to the number of CPUs available on the current system, but it can be any reasonable number, including `1`.
-
- * **<code>maxConcurrentCallsPerWorker</code>** allows you to control the *concurrency* of individual child processes. Calls are placed into a queue and farmed out to child processes according to the number of calls they are allowed to handle concurrently. It is arbitrarily set to 10 by default so that calls are shared relatively evenly across workers, however if your calls predictably take a similar amount of time then you could set it to `Infinity` and Worker Farm won't queue any calls but spread them evenly across child processes and let them go at it. If your calls aren't I/O bound then it won't matter what value you use here as the individual workers won't be able to execute more than a single call at a time.
-
- * **<code>maxConcurrentCalls</code>** allows you to control the maximum number of calls in the queue&mdash;either actively being processed or waiting for a worker to be processed. `Infinity` indicates no limit but if you have conditions that may endlessly queue jobs and you need to set a limit then provide a `>0` value and any calls that push the limit will return on their callback with a `MaxConcurrentCallsError` error (check `err.type == 'MaxConcurrentCallsError'`).
-
- * **<code>maxCallTime</code>** *(use with caution, understand what this does before you use it!)* when `!== Infinity`, will cap a time, in milliseconds, that *any single call* can take to execute in a worker. If this time limit is exceeded by just a single call then the worker running that call will be killed and any calls running on that worker will have their callbacks returned with a `TimeoutError` (check `err.type == 'TimeoutError'`). If you are running with `maxConcurrentCallsPerWorker` value greater than `1` then **all calls currently executing** will fail and will be automatically resubmitted uless you've changed the `maxRetries` option. Use this if you have jobs that may potentially end in infinite loops that you can't programatically end with your child code. Preferably run this with a `maxConcurrentCallsPerWorker` so you don't interrupt other calls when you have a timeout. This timeout operates on a per-call basis but will interrupt a whole worker.
-
- * **<code>maxRetries</code>** allows you to control the max number of call requeues after worker termination (unexpected or timeout). By default this option is set to `Infinity` which means that each call of each terminated worker will always be auto requeued. When the number of retries exceeds `maxRetries` value, the job callback will be executed with a `ProcessTerminatedError`. Note that if you are running with finite `maxCallTime` and `maxConcurrentCallsPerWorkers` greater than `1` then any `TimeoutError` will increase the retries counter *for each* concurrent call of the terminated worker.
-
- * **<code>autoStart</code>** when set to `true` will start the workers as early as possible. Use this when your workers have to do expensive initialization. That way they'll be ready when the first request comes through.
-
- * **<code>onChild</code>** when new child process starts this callback will be called with subprocess object as an argument. Use this when you need to add some custom communication with child processes.
-
-### workerFarm.end(farm)
-
-Child processes stay alive waiting for jobs indefinitely and your farm manager will stay alive managing its workers, so if you need it to stop then you have to do so explicitly. If you send your farm API to `workerFarm.end()` then it'll cleanly end your worker processes. Note though that it's a *soft* ending so it'll wait for child processes to finish what they are working on before asking them to die.
-
-Any calls that are queued and not yet being handled by a child process will be discarded. `end()` only waits for those currently in progress.
-
-Once you end a farm, it won't handle any more calls, so don't even try!
-
-## Related
-
-* [farm-cli](https://github.com/Kikobeats/farm-cli) – Launch a farm of workers from CLI.
-
-## License
-
-Worker Farm is Copyright (c) 2014 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.
diff --git a/deps/npm/node_modules/worker-farm/examples/basic/child.js b/deps/npm/node_modules/worker-farm/examples/basic/child.js
deleted file mode 100644
index 0f0900b5e2..0000000000
--- a/deps/npm/node_modules/worker-farm/examples/basic/child.js
+++ /dev/null
@@ -1,5 +0,0 @@
-'use strict'
-
-module.exports = function (inp, callback) {
- callback(null, inp + ' BAR (' + process.pid + ')')
-}
diff --git a/deps/npm/node_modules/worker-farm/examples/basic/index.js b/deps/npm/node_modules/worker-farm/examples/basic/index.js
deleted file mode 100644
index 452e7b1630..0000000000
--- a/deps/npm/node_modules/worker-farm/examples/basic/index.js
+++ /dev/null
@@ -1,13 +0,0 @@
-'use strict'
-
-let workerFarm = require('../../')
- , workers = workerFarm(require.resolve('./child'))
- , ret = 0
-
-for (let i = 0; i < 10; i++) {
- workers('#' + i + ' FOO', function (err, outp) {
- console.log(outp)
- if (++ret == 10)
- workerFarm.end(workers)
- })
-}
diff --git a/deps/npm/node_modules/worker-farm/examples/pi/calc.js b/deps/npm/node_modules/worker-farm/examples/pi/calc.js
deleted file mode 100644
index df9e5bae13..0000000000
--- a/deps/npm/node_modules/worker-farm/examples/pi/calc.js
+++ /dev/null
@@ -1,22 +0,0 @@
-'use strict'
-
-/* A simple π estimation function using a Monte Carlo method
- * For 0 to `points`, take 2 random numbers < 1, square and add them to
- * find the area under that point in a 1x1 square. If that area is <= 1
- * then it's *within* a quarter-circle, otherwise it's outside.
- * Take the number of points <= 1 and multiply it by 4 and you have an
- * estimate!
- * Do this across multiple processes and average the results to
- * increase accuracy.
- */
-
-module.exports = function (points, callback) {
- let inside = 0
- , i = points
-
- while (i--)
- if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) <= 1)
- inside++
-
- callback(null, (inside / points) * 4)
-}
diff --git a/deps/npm/node_modules/worker-farm/examples/pi/index.js b/deps/npm/node_modules/worker-farm/examples/pi/index.js
deleted file mode 100644
index b7b26839ed..0000000000
--- a/deps/npm/node_modules/worker-farm/examples/pi/index.js
+++ /dev/null
@@ -1,41 +0,0 @@
-'use strict'
-
-const CHILDREN = 500
- , POINTS_PER_CHILD = 1000000
- , FARM_OPTIONS = {
- maxConcurrentWorkers : require('os').cpus().length
- , maxCallsPerWorker : Infinity
- , maxConcurrentCallsPerWorker : 1
- }
-
-let workerFarm = require('../../')
- , calcDirect = require('./calc')
- , calcWorker = workerFarm(FARM_OPTIONS, require.resolve('./calc'))
-
- , ret
- , start
-
- , tally = function (finish, err, avg) {
- ret.push(avg)
- if (ret.length == CHILDREN) {
- let pi = ret.reduce(function (a, b) { return a + b }) / ret.length
- , end = +new Date()
- console.log('π ≈', pi, '\t(' + Math.abs(pi - Math.PI), 'away from actual!)')
- console.log('took', end - start, 'milliseconds')
- if (finish)
- finish()
- }
- }
-
- , calc = function (method, callback) {
- ret = []
- start = +new Date()
- for (let i = 0; i < CHILDREN; i++)
- method(POINTS_PER_CHILD, tally.bind(null, callback))
- }
-
-console.log('Doing it the slow (single-process) way...')
-calc(calcDirect, function () {
- console.log('Doing it the fast (multi-process) way...')
- calc(calcWorker, process.exit)
-})
diff --git a/deps/npm/node_modules/worker-farm/index.d.ts b/deps/npm/node_modules/worker-farm/index.d.ts
deleted file mode 100644
index 310e91503f..0000000000
--- a/deps/npm/node_modules/worker-farm/index.d.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { ForkOptions } from "child_process";
-
-export = Farm;
-
-declare function Farm(name: string): Farm.Workers;
-declare function Farm(name: string, exportedMethods: string[]): Farm.Workers;
-declare function Farm(options: Farm.FarmOptions, name: string): Farm.Workers;
-declare function Farm(
- options: Farm.FarmOptions,
- name: string,
- exportedMethods: string[],
-): Farm.Workers;
-
-type WorkerCallback0 = () => void;
-type WorkerCallback1 = (arg1: any) => void;
-type WorkerCallback2 = (arg1: any, arg2: any) => void;
-type WorkerCallback3 = (arg1: any, arg2: any, arg3: any) => void;
-type WorkerCallback4 = (arg1: any, arg2: any, arg3: any, arg4: any) => void;
-
-declare namespace Farm {
- export function end(workers: Workers, callback?: Function): void;
-
- export interface Workers {
- [x: string]: Workers,
- (callback: WorkerCallback): void;
- (arg1: any, callback: WorkerCallback): void;
- (arg1: any, arg2: any, callback: WorkerCallback): void;
- (arg1: any, arg2: any, arg3: any, callback: WorkerCallback): void;
- (
- arg1: any,
- arg2: any,
- arg3: any,
- arg4: any,
- callback: WorkerCallback,
- ): void;
- }
-
- export interface FarmOptions {
- maxCallsPerWorker?: number;
- maxConcurrentWorkers?: number;
- maxConcurrentCallsPerWorker?: number;
- maxConcurrentCalls?: number;
- maxCallTime?: number;
- maxRetries?: number;
- autoStart?: boolean;
- workerOptions?: ForkOptions;
- }
-
- export type WorkerCallback =
- | WorkerCallback0
- | WorkerCallback1
- | WorkerCallback2
- | WorkerCallback3
- | WorkerCallback4;
-}
diff --git a/deps/npm/node_modules/worker-farm/lib/child/index.js b/deps/npm/node_modules/worker-farm/lib/child/index.js
deleted file mode 100644
index 78f6337139..0000000000
--- a/deps/npm/node_modules/worker-farm/lib/child/index.js
+++ /dev/null
@@ -1,56 +0,0 @@
-'use strict'
-
-let $module
-
-/*
- let contextProto = this.context;
- while (contextProto = Object.getPrototypeOf(contextProto)) {
- completionGroups.push(Object.getOwnPropertyNames(contextProto));
- }
-*/
-
-
-function handle (data) {
- let idx = data.idx
- , child = data.child
- , method = data.method
- , args = data.args
- , callback = function () {
- let _args = Array.prototype.slice.call(arguments)
- if (_args[0] instanceof Error) {
- let e = _args[0]
- _args[0] = {
- '$error' : '$error'
- , 'type' : e.constructor.name
- , 'message' : e.message
- , 'stack' : e.stack
- }
- Object.keys(e).forEach(function(key) {
- _args[0][key] = e[key]
- })
- }
- process.send({ owner: 'farm', idx: idx, child: child, args: _args })
- }
- , exec
-
- if (method == null && typeof $module == 'function')
- exec = $module
- else if (typeof $module[method] == 'function')
- exec = $module[method]
-
- if (!exec)
- return console.error('NO SUCH METHOD:', method)
-
- exec.apply(null, args.concat([ callback ]))
-}
-
-
-process.on('message', function (data) {
- if (data.owner !== 'farm') {
- return;
- }
-
- if (!$module) return $module = require(data.module)
- if (data.event == 'die') return process.exit(0)
- handle(data)
-})
diff --git a/deps/npm/node_modules/worker-farm/lib/farm.js b/deps/npm/node_modules/worker-farm/lib/farm.js
deleted file mode 100644
index 60720dc561..0000000000
--- a/deps/npm/node_modules/worker-farm/lib/farm.js
+++ /dev/null
@@ -1,348 +0,0 @@
-'use strict'
-
-const DEFAULT_OPTIONS = {
- workerOptions : {}
- , maxCallsPerWorker : Infinity
- , maxConcurrentWorkers : (require('os').cpus() || { length: 1 }).length
- , maxConcurrentCallsPerWorker : 10
- , maxConcurrentCalls : Infinity
- , maxCallTime : Infinity // exceed this and the whole worker is terminated
- , maxRetries : Infinity
- , forcedKillTime : 100
- , autoStart : false
- , onChild : function() {}
- }
-
-const fork = require('./fork')
- , TimeoutError = require('errno').create('TimeoutError')
- , ProcessTerminatedError = require('errno').create('ProcessTerminatedError')
- , MaxConcurrentCallsError = require('errno').create('MaxConcurrentCallsError')
-
-
-function Farm (options, path) {
- this.options = Object.assign({}, DEFAULT_OPTIONS, options)
- this.path = path
- this.activeCalls = 0
-}
-
-
-// make a handle to pass back in the form of an external API
-Farm.prototype.mkhandle = function (method) {
- return function () {
- let args = Array.prototype.slice.call(arguments)
- if (this.activeCalls + this.callQueue.length >= this.options.maxConcurrentCalls) {
- let err = new MaxConcurrentCallsError('Too many concurrent calls (active: ' + this.activeCalls + ', queued: ' + this.callQueue.length + ')')
- if (typeof args[args.length - 1] == 'function')
- return process.nextTick(args[args.length - 1].bind(null, err))
- throw err
- }
- this.addCall({
- method : method
- , callback : args.pop()
- , args : args
- , retries : 0
- })
- }.bind(this)
-}
-
-
-// a constructor of sorts
-Farm.prototype.setup = function (methods) {
- let iface
- if (!methods) { // single-function export
- iface = this.mkhandle()
- } else { // multiple functions on the export
- iface = {}
- methods.forEach(function (m) {
- iface[m] = this.mkhandle(m)
- }.bind(this))
- }
-
- this.searchStart = -1
- this.childId = -1
- this.children = {}
- this.activeChildren = 0
- this.callQueue = []
-
- if (this.options.autoStart) {
- while (this.activeChildren < this.options.maxConcurrentWorkers)
- this.startChild()
- }
-
- return iface
-}
-
-
-// when a child exits, check if there are any outstanding jobs and requeue them
-Farm.prototype.onExit = function (childId) {
- // delay this to give any sends a chance to finish
- setTimeout(function () {
- let doQueue = false
- if (this.children[childId] && this.children[childId].activeCalls) {
- this.children[childId].calls.forEach(function (call, i) {
- if (!call) return
- else if (call.retries >= this.options.maxRetries) {
- this.receive({
- idx : i
- , child : childId
- , args : [ new ProcessTerminatedError('cancel after ' + call.retries + ' retries!') ]
- })
- } else {
- call.retries++
- this.callQueue.unshift(call)
- doQueue = true
- }
- }.bind(this))
- }
- this.stopChild(childId)
- doQueue && this.processQueue()
- }.bind(this), 10)
-}
-
-
-// start a new worker
-Farm.prototype.startChild = function () {
- this.childId++
-
- let forked = fork(this.path, this.options.workerOptions)
- , id = this.childId
- , c = {
- send : forked.send
- , child : forked.child
- , calls : []
- , activeCalls : 0
- , exitCode : null
- }
-
- this.options.onChild(forked.child);
-
- forked.child.on('message', function(data) {
- if (data.owner !== 'farm') {
- return;
- }
- this.receive(data);
- }.bind(this))
- forked.child.once('exit', function (code) {
- c.exitCode = code
- this.onExit(id)
- }.bind(this))
-
- this.activeChildren++
- this.children[id] = c
-}
-
-
-// stop a worker, identified by id
-Farm.prototype.stopChild = function (childId) {
- let child = this.children[childId]
- if (child) {
- child.send({owner: 'farm', event: 'die'})
- setTimeout(function () {
- if (child.exitCode === null)
- child.child.kill('SIGKILL')
- }, this.options.forcedKillTime).unref()
- ;delete this.children[childId]
- this.activeChildren--
- }
-}
-
-
-// called from a child process, the data contains information needed to
-// look up the child and the original call so we can invoke the callback
-Farm.prototype.receive = function (data) {
- let idx = data.idx
- , childId = data.child
- , args = data.args
- , child = this.children[childId]
- , call
-
- if (!child) {
- return console.error(
- 'Worker Farm: Received message for unknown child. '
- + 'This is likely as a result of premature child death, '
- + 'the operation will have been re-queued.'
- )
- }
-
- call = child.calls[idx]
- if (!call) {
- return console.error(
- 'Worker Farm: Received message for unknown index for existing child. '
- + 'This should not happen!'
- )
- }
-
- if (this.options.maxCallTime !== Infinity)
- clearTimeout(call.timer)
-
- if (args[0] && args[0].$error == '$error') {
- let e = args[0]
- switch (e.type) {
- case 'TypeError': args[0] = new TypeError(e.message); break
- case 'RangeError': args[0] = new RangeError(e.message); break
- case 'EvalError': args[0] = new EvalError(e.message); break
- case 'ReferenceError': args[0] = new ReferenceError(e.message); break
- case 'SyntaxError': args[0] = new SyntaxError(e.message); break
- case 'URIError': args[0] = new URIError(e.message); break
- default: args[0] = new Error(e.message)
- }
- args[0].type = e.type
- args[0].stack = e.stack
-
- // Copy any custom properties to pass it on.
- Object.keys(e).forEach(function(key) {
- args[0][key] = e[key];
- });
- }
-
- process.nextTick(function () {
- call.callback.apply(null, args)
- })
-
- ;delete child.calls[idx]
- child.activeCalls--
- this.activeCalls--
-
- if (child.calls.length >= this.options.maxCallsPerWorker
- && !Object.keys(child.calls).length) {
- // this child has finished its run, kill it
- this.stopChild(childId)
- }
-
- // allow any outstanding calls to be processed
- this.processQueue()
-}
-
-
-Farm.prototype.childTimeout = function (childId) {
- let child = this.children[childId]
- , i
-
- if (!child)
- return
-
- for (i in child.calls) {
- this.receive({
- idx : i
- , child : childId
- , args : [ new TimeoutError('worker call timed out!') ]
- })
- }
- this.stopChild(childId)
-}
-
-
-// send a call to a worker, identified by id
-Farm.prototype.send = function (childId, call) {
- let child = this.children[childId]
- , idx = child.calls.length
-
- child.calls.push(call)
- child.activeCalls++
- this.activeCalls++
-
- child.send({
- owner : 'farm'
- , idx : idx
- , child : childId
- , method : call.method
- , args : call.args
- })
-
- if (this.options.maxCallTime !== Infinity) {
- call.timer =
- setTimeout(this.childTimeout.bind(this, childId), this.options.maxCallTime)
- }
-}
-
-
-// a list of active worker ids, in order, but the starting offset is
-// shifted each time this method is called, so we work our way through
-// all workers when handing out jobs
-Farm.prototype.childKeys = function () {
- let cka = Object.keys(this.children)
- , cks
-
- if (this.searchStart >= cka.length - 1)
- this.searchStart = 0
- else
- this.searchStart++
-
- cks = cka.splice(0, this.searchStart)
-
- return cka.concat(cks)
-}
-
-
-// Calls are added to a queue, this processes the queue and is called
-// whenever there might be a chance to send more calls to the workers.
-// The various options all impact on when we're able to send calls,
-// they may need to be kept in a queue until a worker is ready.
-Farm.prototype.processQueue = function () {
- let cka, i = 0, childId
-
- if (!this.callQueue.length)
- return this.ending && this.end()
-
- if (this.activeChildren < this.options.maxConcurrentWorkers)
- this.startChild()
-
- for (cka = this.childKeys(); i < cka.length; i++) {
- childId = +cka[i]
- if (this.children[childId].activeCalls < this.options.maxConcurrentCallsPerWorker
- && this.children[childId].calls.length < this.options.maxCallsPerWorker) {
-
- this.send(childId, this.callQueue.shift())
- if (!this.callQueue.length)
- return this.ending && this.end()
- } /*else {
- console.log(
- , this.children[childId].activeCalls < this.options.maxConcurrentCallsPerWorker
- , this.children[childId].calls.length < this.options.maxCallsPerWorker
- , this.children[childId].calls.length , this.options.maxCallsPerWorker)
- }*/
- }
-
- if (this.ending)
- this.end()
-}
-
-
-// add a new call to the call queue, then trigger a process of the queue
-Farm.prototype.addCall = function (call) {
- if (this.ending)
- return this.end() // don't add anything new to the queue
- this.callQueue.push(call)
- this.processQueue()
-}
-
-
-// kills child workers when they're all done
-Farm.prototype.end = function (callback) {
- let complete = true
- if (this.ending === false)
- return
- if (callback)
- this.ending = callback
- else if (this.ending == null)
- this.ending = true
- Object.keys(this.children).forEach(function (child) {
- if (!this.children[child])
- return
- if (!this.children[child].activeCalls)
- this.stopChild(child)
- else
- complete = false
- }.bind(this))
-
- if (complete && typeof this.ending == 'function') {
- process.nextTick(function () {
- this.ending()
- this.ending = false
- }.bind(this))
- }
-}
-
-
-module.exports = Farm
-module.exports.TimeoutError = TimeoutError
diff --git a/deps/npm/node_modules/worker-farm/lib/fork.js b/deps/npm/node_modules/worker-farm/lib/fork.js
deleted file mode 100644
index 5a035d9749..0000000000
--- a/deps/npm/node_modules/worker-farm/lib/fork.js
+++ /dev/null
@@ -1,33 +0,0 @@
-'use strict'
-
-const childProcess = require('child_process')
- , childModule = require.resolve('./child/index')
-
-
-function fork (forkModule, workerOptions) {
- // suppress --debug / --inspect flags while preserving others (like --harmony)
- let filteredArgs = process.execArgv.filter(function (v) {
- return !(/^--(debug|inspect)/).test(v)
- })
- , options = Object.assign({
- execArgv : filteredArgs
- , env : process.env
- , cwd : process.cwd()
- }, workerOptions)
- , child = childProcess.fork(childModule, process.argv, options)
-
- child.on('error', function() {
- // this *should* be picked up by onExit and the operation requeued
- })
-
- child.send({ owner: 'farm', module: forkModule })
-
- // return a send() function for this child
- return {
- send : child.send.bind(child)
- , child : child
- }
-}
-
-
-module.exports = fork
diff --git a/deps/npm/node_modules/worker-farm/lib/index.js b/deps/npm/node_modules/worker-farm/lib/index.js
deleted file mode 100644
index 8c14222735..0000000000
--- a/deps/npm/node_modules/worker-farm/lib/index.js
+++ /dev/null
@@ -1,34 +0,0 @@
-'use strict'
-
-const Farm = require('./farm')
-
-let farms = [] // keep record of farms so we can end() them if required
-
-
-function farm (options, path, methods) {
- if (typeof options == 'string') {
- methods = path
- path = options
- options = {}
- }
-
- let f = new Farm(options, path)
- , api = f.setup(methods)
-
- farms.push({ farm: f, api: api })
-
- // return the public API
- return api
-}
-
-
-function end (api, callback) {
- for (let i = 0; i < farms.length; i++)
- if (farms[i] && farms[i].api === api)
- return farms[i].farm.end(callback)
- process.nextTick(callback.bind(null, new Error('Worker farm not found!')))
-}
-
-
-module.exports = farm
-module.exports.end = end
diff --git a/deps/npm/node_modules/worker-farm/package.json b/deps/npm/node_modules/worker-farm/package.json
deleted file mode 100644
index 3d6181ae95..0000000000
--- a/deps/npm/node_modules/worker-farm/package.json
+++ /dev/null
@@ -1,61 +0,0 @@
-{
- "_from": "worker-farm@1.7.0",
- "_id": "worker-farm@1.7.0",
- "_inBundle": false,
- "_integrity": "sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw==",
- "_location": "/worker-farm",
- "_phantomChildren": {},
- "_requested": {
- "type": "version",
- "registry": true,
- "raw": "worker-farm@1.7.0",
- "name": "worker-farm",
- "escapedName": "worker-farm",
- "rawSpec": "1.7.0",
- "saveSpec": null,
- "fetchSpec": "1.7.0"
- },
- "_requiredBy": [
- "#USER",
- "/",
- "/libcipm"
- ],
- "_resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.7.0.tgz",
- "_shasum": "26a94c5391bbca926152002f69b84a4bf772e5a8",
- "_spec": "worker-farm@1.7.0",
- "_where": "/Users/isaacs/dev/npm/cli",
- "authors": [
- "Rod Vagg @rvagg <rod@vagg.org> (https://github.com/rvagg)"
- ],
- "bugs": {
- "url": "https://github.com/rvagg/node-worker-farm/issues"
- },
- "bundleDependencies": false,
- "dependencies": {
- "errno": "~0.1.7"
- },
- "deprecated": false,
- "description": "Distribute processing tasks to child processes with an über-simple API and baked-in durability & custom concurrency options.",
- "devDependencies": {
- "tape": "~4.10.1"
- },
- "homepage": "https://github.com/rvagg/node-worker-farm",
- "keywords": [
- "worker",
- "child",
- "processing",
- "farm"
- ],
- "license": "MIT",
- "main": "./lib/index.js",
- "name": "worker-farm",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/rvagg/node-worker-farm.git"
- },
- "scripts": {
- "test": "node ./tests/"
- },
- "types": "./index.d.ts",
- "version": "1.7.0"
-}
diff --git a/deps/npm/node_modules/worker-farm/tests/child.js b/deps/npm/node_modules/worker-farm/tests/child.js
deleted file mode 100644
index 71cb728f77..0000000000
--- a/deps/npm/node_modules/worker-farm/tests/child.js
+++ /dev/null
@@ -1,87 +0,0 @@
-'use strict'
-
-const fs = require('fs')
-const started = Date.now()
-
-
-module.exports = function (timeout, callback) {
- callback = callback.bind(null, null, process.pid, Math.random(), timeout)
- if (timeout)
- return setTimeout(callback, timeout)
- callback()
-}
-
-
-module.exports.args = function (callback) {
- callback(null, {
- argv : process.argv
- , cwd : process.cwd()
- , execArgv : process.execArgv
- })
-}
-
-
-module.exports.run0 = function (callback) {
- module.exports(0, callback)
-}
-
-
-module.exports.killable = function (id, callback) {
- if (Math.random() < 0.5)
- return process.exit(-1)
- callback(null, id, process.pid)
-}
-
-
-module.exports.err = function (type, message, data, callback) {
- if (typeof data == 'function') {
- callback = data
- data = null
- } else {
- let err = new Error(message)
- Object.keys(data).forEach(function(key) {
- err[key] = data[key]
- })
- callback(err)
- return
- }
-
- if (type == 'TypeError')
- return callback(new TypeError(message))
- callback(new Error(message))
-}
-
-
-module.exports.block = function () {
- while (true);
-}
-
-
-// use provided file path to save retries count among terminated workers
-module.exports.stubborn = function (path, callback) {
- function isOutdated(path) {
- return ((new Date).getTime() - fs.statSync(path).mtime.getTime()) > 2000
- }
-
- // file may not be properly deleted, check if modified no earler than two seconds ago
- if (!fs.existsSync(path) || isOutdated(path)) {
- fs.writeFileSync(path, '1')
- process.exit(-1)
- }
-
- let retry = parseInt(fs.readFileSync(path, 'utf8'))
- if (Number.isNaN(retry))
- return callback(new Error('file contents is not a number'))
-
- if (retry > 4) {
- callback(null, 12)
- } else {
- fs.writeFileSync(path, String(retry + 1))
- process.exit(-1)
- }
-}
-
-
-module.exports.uptime = function (callback) {
- callback(null, Date.now() - started)
-}
diff --git a/deps/npm/node_modules/worker-farm/tests/debug.js b/deps/npm/node_modules/worker-farm/tests/debug.js
deleted file mode 100644
index 4d2b803216..0000000000
--- a/deps/npm/node_modules/worker-farm/tests/debug.js
+++ /dev/null
@@ -1,12 +0,0 @@
-'use strict'
-
-const workerFarm = require('../')
- , workers = workerFarm(require.resolve('./child'), ['args'])
-
-
-workers.args(function(err, result) {
- console.log(result);
- workerFarm.end(workers)
- console.log('FINISHED')
- process.exit(0)
-})
diff --git a/deps/npm/node_modules/worker-farm/tests/index.js b/deps/npm/node_modules/worker-farm/tests/index.js
deleted file mode 100644
index e6be7bb7aa..0000000000
--- a/deps/npm/node_modules/worker-farm/tests/index.js
+++ /dev/null
@@ -1,616 +0,0 @@
-'use strict'
-
-const tape = require('tape')
- , child_process = require('child_process')
- , workerFarm = require('../')
- , childPath = require.resolve('./child')
- , fs = require('fs')
- , os = require('os')
-
-function uniq (ar) {
- let a = [], i, j
- o: for (i = 0; i < ar.length; ++i) {
- for (j = 0; j < a.length; ++j) if (a[j] == ar[i]) continue o
- a[a.length] = ar[i]
- }
- return a
-}
-
-
-// a child where module.exports = function ...
-tape('simple, exports=function test', function (t) {
- t.plan(4)
-
- let child = workerFarm(childPath)
- child(0, function (err, pid, rnd) {
- t.ok(pid > process.pid, 'pid makes sense')
- t.ok(pid < process.pid + 750, 'pid makes sense')
- t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-// a child where we have module.exports.fn = function ...
-tape('simple, exports.fn test', function (t) {
- t.plan(4)
-
- let child = workerFarm(childPath, [ 'run0' ])
- child.run0(function (err, pid, rnd) {
- t.ok(pid > process.pid, 'pid makes sense')
- t.ok(pid < process.pid + 750, 'pid makes sense')
- t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-tape('on child', function (t) {
- t.plan(2)
-
- let child = workerFarm({ onChild: function(subprocess) { childPid = subprocess.pid } }, childPath)
- , childPid = null;
-
- child(0, function(err, pid) {
- t.equal(childPid, pid)
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-// use the returned pids to check that we're using a single child process
-// when maxConcurrentWorkers = 1
-tape('single worker', function (t) {
- t.plan(2)
-
- let child = workerFarm({ maxConcurrentWorkers: 1 }, childPath)
- , pids = []
- , i = 10
-
- while (i--) {
- child(0, function (err, pid) {
- pids.push(pid)
- if (pids.length == 10) {
- t.equal(1, uniq(pids).length, 'only a single process (by pid)')
- } else if (pids.length > 10)
- t.fail('too many callbacks!')
- })
- }
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-// use the returned pids to check that we're using two child processes
-// when maxConcurrentWorkers = 2
-tape('two workers', function (t) {
- t.plan(2)
-
- let child = workerFarm({ maxConcurrentWorkers: 2 }, childPath)
- , pids = []
- , i = 10
-
- while (i--) {
- child(0, function (err, pid) {
- pids.push(pid)
- if (pids.length == 10) {
- t.equal(2, uniq(pids).length, 'only two child processes (by pid)')
- } else if (pids.length > 10)
- t.fail('too many callbacks!')
- })
- }
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-// use the returned pids to check that we're using a child process per
-// call when maxConcurrentWorkers = 10
-tape('many workers', function (t) {
- t.plan(2)
-
- let child = workerFarm({ maxConcurrentWorkers: 10 }, childPath)
- , pids = []
- , i = 10
-
- while (i--) {
- child(1, function (err, pid) {
- pids.push(pid)
- if (pids.length == 10) {
- t.equal(10, uniq(pids).length, 'pids are all the same (by pid)')
- } else if (pids.length > 10)
- t.fail('too many callbacks!')
- })
- }
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-tape('auto start workers', function (t) {
- let child = workerFarm({ maxConcurrentWorkers: 3, autoStart: true }, childPath, ['uptime'])
- , pids = []
- , count = 5
- , i = count
- , delay = 250
-
- t.plan(count + 1)
-
- setTimeout(function() {
- while (i--)
- child.uptime(function (err, uptime) {
- t.ok(uptime > 10, 'child has been up before the request (' + uptime + 'ms)')
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- }, delay)
-})
-
-
-// use the returned pids to check that we're using a child process per
-// call when we set maxCallsPerWorker = 1 even when we have maxConcurrentWorkers = 1
-tape('single call per worker', function (t) {
- t.plan(2)
-
- let child = workerFarm({
- maxConcurrentWorkers: 1
- , maxConcurrentCallsPerWorker: Infinity
- , maxCallsPerWorker: 1
- , autoStart: true
- }, childPath)
- , pids = []
- , count = 25
- , i = count
-
- while (i--) {
- child(0, function (err, pid) {
- pids.push(pid)
- if (pids.length == count) {
- t.equal(count, uniq(pids).length, 'one process for each call (by pid)')
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- } else if (pids.length > count)
- t.fail('too many callbacks!')
- })
- }
-})
-
-
-// use the returned pids to check that we're using a child process per
-// two-calls when we set maxCallsPerWorker = 2 even when we have maxConcurrentWorkers = 1
-tape('two calls per worker', function (t) {
- t.plan(2)
-
- let child = workerFarm({
- maxConcurrentWorkers: 1
- , maxConcurrentCallsPerWorker: Infinity
- , maxCallsPerWorker: 2
- , autoStart: true
- }, childPath)
- , pids = []
- , count = 20
- , i = count
-
- while (i--) {
- child(0, function (err, pid) {
- pids.push(pid)
- if (pids.length == count) {
- t.equal(count / 2, uniq(pids).length, 'one process for each call (by pid)')
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- } else if (pids.length > count)
- t.fail('too many callbacks!')
- })
- }
-})
-
-
-// use timing to confirm that one worker will process calls sequentially
-tape('many concurrent calls', function (t) {
- t.plan(2)
-
- let child = workerFarm({
- maxConcurrentWorkers: 1
- , maxConcurrentCallsPerWorker: Infinity
- , maxCallsPerWorker: Infinity
- , autoStart: true
- }, childPath)
- , defer = 200
- , count = 200
- , i = count
- , cbc = 0
-
- setTimeout(function () {
- let start = Date.now()
-
- while (i--) {
- child(defer, function () {
- if (++cbc == count) {
- let time = Date.now() - start
- // upper-limit not tied to `count` at all
- t.ok(time > defer && time < (defer * 2.5), 'processed tasks concurrently (' + time + 'ms)')
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- } else if (cbc > count)
- t.fail('too many callbacks!')
- })
- }
- }, 250)
-})
-
-
-// use timing to confirm that one child processes calls sequentially with
-// maxConcurrentCallsPerWorker = 1
-tape('single concurrent call', function (t) {
- t.plan(2)
-
- let child = workerFarm({
- maxConcurrentWorkers: 1
- , maxConcurrentCallsPerWorker: 1
- , maxCallsPerWorker: Infinity
- , autoStart: true
- }, childPath)
- , defer = 20
- , count = 100
- , i = count
- , cbc = 0
-
- setTimeout(function () {
- let start = Date.now()
-
- while (i--) {
- child(defer, function () {
- if (++cbc == count) {
- let time = Date.now() - start
- // upper-limit tied closely to `count`, 1.3 is generous but accounts for all the timers
- // coming back at the same time and the IPC overhead
- t.ok(time > (defer * count) && time < (defer * count * 1.3), 'processed tasks sequentially (' + time + ')')
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- } else if (cbc > count)
- t.fail('too many callbacks!')
- })
- }
- }, 250)
-})
-
-
-// use timing to confirm that one child processes *only* 5 calls concurrently
-tape('multiple concurrent calls', function (t) {
- t.plan(2)
-
- let callsPerWorker = 5
- , child = workerFarm({
- maxConcurrentWorkers: 1
- , maxConcurrentCallsPerWorker: callsPerWorker
- , maxCallsPerWorker: Infinity
- , autoStart: true
- }, childPath)
- , defer = 100
- , count = 100
- , i = count
- , cbc = 0
-
- setTimeout(function () {
- let start = Date.now()
-
- while (i--) {
- child(defer, function () {
- if (++cbc == count) {
- let time = Date.now() - start
- let min = defer * 1.5
- // (defer * (count / callsPerWorker + 2)) - if precise it'd be count/callsPerWorker
- // but accounting for IPC and other overhead, we need to give it a bit of extra time,
- // hence the +2
- let max = defer * (count / callsPerWorker + 2)
- t.ok(time > min && time < max, 'processed tasks concurrently (' + time + ' > ' + min + ' && ' + time + ' < ' + max + ')')
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- } else if (cbc > count)
- t.fail('too many callbacks!')
- })
- }
- }, 250)
-})
-
-
-// call a method that will die with a probability of 0.5 but expect that
-// we'll get results for each of our calls anyway
-tape('durability', function (t) {
- t.plan(3)
-
- let child = workerFarm({ maxConcurrentWorkers: 2 }, childPath, [ 'killable' ])
- , ids = []
- , pids = []
- , count = 20
- , i = count
-
- while (i--) {
- child.killable(i, function (err, id, pid) {
- ids.push(id)
- pids.push(pid)
- if (ids.length == count) {
- t.ok(uniq(pids).length > 2, 'processed by many (' + uniq(pids).length + ') workers, but got there in the end!')
- t.ok(uniq(ids).length == count, 'received a single result for each unique call')
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- } else if (ids.length > count)
- t.fail('too many callbacks!')
- })
- }
-})
-
-
-// a callback provided to .end() can and will be called (uses "simple, exports=function test" to create a child)
-tape('simple, end callback', function (t) {
- t.plan(4)
-
- let child = workerFarm(childPath)
- child(0, function (err, pid, rnd) {
- t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
- t.ok(pid < process.pid + 750, 'pid makes sense ' + pid + ' vs ' + process.pid)
- t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
- })
-
- workerFarm.end(child, function() {
- t.pass('an .end() callback was successfully called')
- })
-})
-
-
-tape('call timeout test', function (t) {
- t.plan(3 + 3 + 4 + 4 + 4 + 3 + 1)
-
- let child = workerFarm({ maxCallTime: 250, maxConcurrentWorkers: 1 }, childPath)
-
- // should come back ok
- child(50, function (err, pid, rnd) {
- t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
- t.ok(pid < process.pid + 750, 'pid makes sense ' + pid + ' vs ' + process.pid)
- t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
- })
-
- // should come back ok
- child(50, function (err, pid, rnd) {
- t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
- t.ok(pid < process.pid + 750, 'pid makes sense ' + pid + ' vs ' + process.pid)
- t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
- })
-
- // should die
- child(500, function (err, pid, rnd) {
- t.ok(err, 'got an error')
- t.equal(err.type, 'TimeoutError', 'correct error type')
- t.ok(pid === undefined, 'no pid')
- t.ok(rnd === undefined, 'no rnd')
- })
-
- // should die
- child(1000, function (err, pid, rnd) {
- t.ok(err, 'got an error')
- t.equal(err.type, 'TimeoutError', 'correct error type')
- t.ok(pid === undefined, 'no pid')
- t.ok(rnd === undefined, 'no rnd')
- })
-
- // should die even though it is only a 100ms task, it'll get caught up
- // in a dying worker
- setTimeout(function () {
- child(100, function (err, pid, rnd) {
- t.ok(err, 'got an error')
- t.equal(err.type, 'TimeoutError', 'correct error type')
- t.ok(pid === undefined, 'no pid')
- t.ok(rnd === undefined, 'no rnd')
- })
- }, 200)
-
- // should be ok, new worker
- setTimeout(function () {
- child(50, function (err, pid, rnd) {
- t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
- t.ok(pid < process.pid + 750, 'pid makes sense ' + pid + ' vs ' + process.pid)
- t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
- })
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- }, 400)
-})
-
-
-tape('test error passing', function (t) {
- t.plan(10)
-
- let child = workerFarm(childPath, [ 'err' ])
- child.err('Error', 'this is an Error', function (err) {
- t.ok(err instanceof Error, 'is an Error object')
- t.equal('Error', err.type, 'correct type')
- t.equal('this is an Error', err.message, 'correct message')
- })
- child.err('TypeError', 'this is a TypeError', function (err) {
- t.ok(err instanceof Error, 'is a TypeError object')
- t.equal('TypeError', err.type, 'correct type')
- t.equal('this is a TypeError', err.message, 'correct message')
- })
- child.err('Error', 'this is an Error with custom props', {foo: 'bar', 'baz': 1}, function (err) {
- t.ok(err instanceof Error, 'is an Error object')
- t.equal(err.foo, 'bar', 'passes data')
- t.equal(err.baz, 1, 'passes data')
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-tape('test maxConcurrentCalls', function (t) {
- t.plan(10)
-
- let child = workerFarm({ maxConcurrentCalls: 5 }, childPath)
-
- child(50, function (err) { t.notOk(err, 'no error') })
- child(50, function (err) { t.notOk(err, 'no error') })
- child(50, function (err) { t.notOk(err, 'no error') })
- child(50, function (err) { t.notOk(err, 'no error') })
- child(50, function (err) { t.notOk(err, 'no error') })
- child(50, function (err) {
- t.ok(err)
- t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
- })
- child(50, function (err) {
- t.ok(err)
- t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-tape('test maxConcurrentCalls + queue', function (t) {
- t.plan(13)
-
- let child = workerFarm({ maxConcurrentCalls: 4, maxConcurrentWorkers: 2, maxConcurrentCallsPerWorker: 1 }, childPath)
-
- child(20, function (err) { console.log('ended short1'); t.notOk(err, 'no error, short call 1') })
- child(20, function (err) { console.log('ended short2'); t.notOk(err, 'no error, short call 2') })
- child(300, function (err) { t.notOk(err, 'no error, long call 1') })
- child(300, function (err) { t.notOk(err, 'no error, long call 2') })
- child(20, function (err) {
- t.ok(err, 'short call 3 should error')
- t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
- })
- child(20, function (err) {
- t.ok(err, 'short call 4 should error')
- t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
- })
-
- // cross fingers and hope the two short jobs have ended
- setTimeout(function () {
- child(20, function (err) { t.notOk(err, 'no error, delayed short call 1') })
- child(20, function (err) { t.notOk(err, 'no error, delayed short call 2') })
- child(20, function (err) {
- t.ok(err, 'delayed short call 3 should error')
- t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
- }, 250)
-})
-
-
-// this test should not keep the process running! if the test process
-// doesn't die then the problem is here
-tape('test timeout kill', function (t) {
- t.plan(3)
-
- let child = workerFarm({ maxCallTime: 250, maxConcurrentWorkers: 1 }, childPath, [ 'block' ])
- child.block(function (err) {
- t.ok(err, 'got an error')
- t.equal(err.type, 'TimeoutError', 'correct error type')
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-tape('test max retries after process terminate', function (t) {
- t.plan(7)
-
- // temporary file is used to store the number of retries among terminating workers
- let filepath1 = '.retries1'
- let child1 = workerFarm({ maxConcurrentWorkers: 1, maxRetries: 5}, childPath, [ 'stubborn' ])
- child1.stubborn(filepath1, function (err, result) {
- t.notOk(err, 'no error')
- t.equal(result, 12, 'correct result')
- })
-
- workerFarm.end(child1, function () {
- fs.unlinkSync(filepath1)
- t.ok(true, 'workerFarm ended')
- })
-
- let filepath2 = '.retries2'
- let child2 = workerFarm({ maxConcurrentWorkers: 1, maxRetries: 3}, childPath, [ 'stubborn' ])
- child2.stubborn(filepath2, function (err, result) {
- t.ok(err, 'got an error')
- t.equal(err.type, 'ProcessTerminatedError', 'correct error type')
- t.equal(err.message, 'cancel after 3 retries!', 'correct message and number of retries')
- })
-
- workerFarm.end(child2, function () {
- fs.unlinkSync(filepath2)
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-tape('custom arguments can be passed to "fork"', function (t) {
- t.plan(3)
-
- // allocate a real, valid path, in any OS
- let cwd = fs.realpathSync(os.tmpdir())
- , workerOptions = {
- cwd : cwd
- , execArgv : ['--expose-gc']
- }
- , child = workerFarm({ maxConcurrentWorkers: 1, maxRetries: 5, workerOptions: workerOptions}, childPath, ['args'])
-
- child.args(function (err, result) {
- t.equal(result.execArgv[0], '--expose-gc', 'flags passed (overridden default)')
- t.equal(result.cwd, cwd, 'correct cwd folder')
- })
-
- workerFarm.end(child, function () {
- t.ok(true, 'workerFarm ended')
- })
-})
-
-
-tape('ensure --debug/--inspect not propagated to children', function (t) {
- t.plan(3)
-
- let script = __dirname + '/debug.js'
- , debugArg = process.version.replace(/^v(\d+)\..*$/, '$1') >= 8 ? '--inspect' : '--debug=8881'
- , child = child_process.spawn(process.execPath, [ debugArg, script ])
- , stdout = ''
-
- child.stdout.on('data', function (data) {
- stdout += data.toString()
- })
-
- child.on('close', function (code) {
- t.equal(code, 0, 'exited without error (' + code + ')')
- t.ok(stdout.indexOf('FINISHED') > -1, 'process finished')
- t.ok(stdout.indexOf('--debug') === -1, 'child does not receive debug flag')
- })
-})