You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
954 lines
35 KiB
954 lines
35 KiB
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>JSDoc: Source: workers/workerpool.js</title>
|
|
|
|
<script src="scripts/prettify/prettify.js"> </script>
|
|
<script src="scripts/prettify/lang-css.js"> </script>
|
|
<!--[if lt IE 9]>
|
|
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
|
|
<![endif]-->
|
|
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
|
|
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<div id="main">
|
|
|
|
<h1 class="page-title">Source: workers/workerpool.js</h1>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<section>
|
|
<article>
|
|
<pre class="prettyprint source linenums"><code>/*!
|
|
* workerpool.js - worker processes for bcoin
|
|
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
|
|
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
|
|
* https://github.com/bcoin-org/bcoin
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
var assert = require('assert');
|
|
var EventEmitter = require('events').EventEmitter;
|
|
var os = require('os');
|
|
var cp = require('child_process');
|
|
var util = require('../utils/util');
|
|
var co = require('../utils/co');
|
|
var global = util.global;
|
|
var Network = require('../protocol/network');
|
|
var jobs = require('./jobs');
|
|
var Parser = require('./parser');
|
|
var Framer = require('./framer');
|
|
var packets = require('./packets');
|
|
|
|
/**
|
|
* A worker pool.
|
|
* @alias module:workers.WorkerPool
|
|
* @constructor
|
|
* @param {Object} options
|
|
* @param {Number} [options.size=num-cores] - Max pool size.
|
|
* @param {Number} [options.timeout=10000] - Execution timeout.
|
|
* @property {Number} size
|
|
* @property {Number} timeout
|
|
* @property {Object} children
|
|
* @property {Number} nonce
|
|
*/
|
|
|
|
function WorkerPool(options) {
|
|
if (!(this instanceof WorkerPool))
|
|
return new WorkerPool(options);
|
|
|
|
EventEmitter.call(this);
|
|
|
|
this.size = WorkerPool.CORES;
|
|
this.timeout = 60000;
|
|
this.children = [];
|
|
this.nonce = 0;
|
|
this.enabled = true;
|
|
|
|
this.set(options);
|
|
|
|
this.on('error', util.nop);
|
|
}
|
|
|
|
util.inherits(WorkerPool, EventEmitter);
|
|
|
|
/**
|
|
* Whether workers are supported.
|
|
* @const {Boolean}
|
|
*/
|
|
|
|
WorkerPool.support = true;
|
|
|
|
if (util.isBrowser) {
|
|
WorkerPool.support = typeof global.Worker === 'function'
|
|
|| typeof global.postMessage === 'function';
|
|
}
|
|
|
|
/**
|
|
* Number of CPUs/cores available.
|
|
* @const {Number}
|
|
*/
|
|
|
|
WorkerPool.CORES = getCores();
|
|
|
|
/**
|
|
* Global list of workers.
|
|
* @type {Array}
|
|
*/
|
|
|
|
WorkerPool.children = [];
|
|
|
|
/**
|
|
* Destroy all workers.
|
|
* Used for cleaning up workers on exit.
|
|
* @private
|
|
*/
|
|
|
|
WorkerPool.cleanup = function cleanup() {
|
|
while (WorkerPool.children.length > 0)
|
|
WorkerPool.children.pop().destroy();
|
|
};
|
|
|
|
/**
|
|
* Whether exit events have been bound globally.
|
|
* @private
|
|
* @type {Boolean}
|
|
*/
|
|
|
|
WorkerPool.bound = false;
|
|
|
|
/**
|
|
* Bind to process events in
|
|
* order to cleanup listeners.
|
|
* @private
|
|
*/
|
|
|
|
WorkerPool.bindExit = function bindExit() {
|
|
if (util.isBrowser)
|
|
return;
|
|
|
|
if (WorkerPool.bound)
|
|
return;
|
|
|
|
WorkerPool.bound = true;
|
|
|
|
function onSignal() {
|
|
WorkerPool.cleanup();
|
|
process.exit(0);
|
|
}
|
|
|
|
function onError(err) {
|
|
WorkerPool.cleanup();
|
|
if (err && err.stack)
|
|
util.error(err.stack + '');
|
|
process.exit(1);
|
|
}
|
|
|
|
process.once('exit', function() {
|
|
WorkerPool.cleanup();
|
|
});
|
|
|
|
if (process.listeners('SIGINT').length === 0)
|
|
process.once('SIGINT', onSignal);
|
|
|
|
if (process.listeners('SIGTERM').length === 0)
|
|
process.once('SIGTERM', onSignal);
|
|
|
|
if (process.listeners('uncaughtException').length === 0)
|
|
process.once('uncaughtException', onError);
|
|
|
|
process.on('newListener', function(name) {
|
|
switch (name) {
|
|
case 'SIGINT':
|
|
case 'SIGTERM':
|
|
process.removeListener(name, onSignal);
|
|
break;
|
|
case 'uncaughtException':
|
|
process.removeListener(name, onError);
|
|
break;
|
|
}
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Set worker pool options.
|
|
* @param {Object} options
|
|
*/
|
|
|
|
WorkerPool.prototype.set = function set(options) {
|
|
if (!options)
|
|
return;
|
|
|
|
if (options.enabled != null) {
|
|
assert(typeof options.enabled === 'boolean');
|
|
this.enabled = options.enabled;
|
|
}
|
|
|
|
if (options.size != null) {
|
|
assert(util.isNumber(options.size));
|
|
assert(options.size > 0);
|
|
this.size = options.size;
|
|
}
|
|
|
|
if (options.timeout != null) {
|
|
assert(util.isNumber(options.timeout));
|
|
assert(options.timeout > 0);
|
|
this.timeout = options.timeout;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Spawn a new worker.
|
|
* @param {Number} id - Worker ID.
|
|
* @returns {Worker}
|
|
*/
|
|
|
|
WorkerPool.prototype.spawn = function spawn(id) {
|
|
var self = this;
|
|
var child;
|
|
|
|
child = new Worker(id);
|
|
|
|
child.on('error', function(err) {
|
|
self.emit('error', err, child);
|
|
});
|
|
|
|
child.on('exit', function(code) {
|
|
self.emit('exit', code, child);
|
|
if (self.children[child.id] === child)
|
|
self.children[child.id] = null;
|
|
});
|
|
|
|
child.on('event', function(items) {
|
|
self.emit('event', items, child);
|
|
self.emit.apply(self, items);
|
|
});
|
|
|
|
this.emit('spawn', child);
|
|
|
|
return child;
|
|
};
|
|
|
|
/**
|
|
* Allocate a new worker, will not go above `size` option
|
|
* and will automatically load balance the workers.
|
|
* @returns {Worker}
|
|
*/
|
|
|
|
WorkerPool.prototype.alloc = function alloc() {
|
|
var id = this.nonce++ % this.size;
|
|
if (!this.children[id])
|
|
this.children[id] = this.spawn(id);
|
|
return this.children[id];
|
|
};
|
|
|
|
/**
|
|
* Emit an event on the worker side (all workers).
|
|
* @param {String} event
|
|
* @param {...Object} arg
|
|
* @returns {Boolean}
|
|
*/
|
|
|
|
WorkerPool.prototype.sendEvent = function sendEvent() {
|
|
var result = true;
|
|
var i, child;
|
|
|
|
for (i = 0; i < this.children.length; i++) {
|
|
child = this.children[i];
|
|
|
|
if (!child)
|
|
continue;
|
|
|
|
if (!child.sendEvent.apply(child, arguments))
|
|
result = false;
|
|
}
|
|
|
|
return result;
|
|
};
|
|
|
|
/**
|
|
* Destroy all workers.
|
|
*/
|
|
|
|
WorkerPool.prototype.destroy = function destroy() {
|
|
var i, child;
|
|
|
|
for (i = 0; i < this.children.length; i++) {
|
|
child = this.children[i];
|
|
|
|
if (!child)
|
|
continue;
|
|
|
|
child.destroy();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Call a method for a worker to execute.
|
|
* @param {Packet} packet
|
|
* @param {Number} timeout
|
|
* @returns {Promise}
|
|
*/
|
|
|
|
WorkerPool.prototype.execute = function execute(packet, timeout) {
|
|
var result, child;
|
|
|
|
if (!this.enabled || !WorkerPool.support) {
|
|
return new Promise(function(resolve, reject) {
|
|
util.nextTick(function() {
|
|
try {
|
|
result = jobs._execute(packet);
|
|
} catch (e) {
|
|
reject(e);
|
|
return;
|
|
}
|
|
resolve(result);
|
|
});
|
|
});
|
|
}
|
|
|
|
if (!timeout)
|
|
timeout = this.timeout;
|
|
|
|
child = this.alloc();
|
|
|
|
return child.execute(packet, timeout);
|
|
};
|
|
|
|
/**
|
|
* Execute the tx verification job (default timeout).
|
|
* @method
|
|
* @param {TX} tx
|
|
* @param {CoinView} view
|
|
* @param {VerifyFlags} flags
|
|
* @returns {Promise} - Returns Boolean.
|
|
*/
|
|
|
|
WorkerPool.prototype.verify = co(function* verify(tx, view, flags) {
|
|
var packet = new packets.VerifyPacket(tx, view, flags);
|
|
var result = yield this.execute(packet, -1);
|
|
return result.value;
|
|
});
|
|
|
|
/**
|
|
* Execute the tx signing job (default timeout).
|
|
* @method
|
|
* @param {MTX} tx
|
|
* @param {KeyRing[]} ring
|
|
* @param {SighashType} type
|
|
* @returns {Promise}
|
|
*/
|
|
|
|
WorkerPool.prototype.sign = co(function* sign(tx, ring, type) {
|
|
var rings = ring;
|
|
var packet, result;
|
|
|
|
if (!Array.isArray(rings))
|
|
rings = [rings];
|
|
|
|
packet = new packets.SignPacket(tx, rings, type);
|
|
result = yield this.execute(packet, -1);
|
|
|
|
result.inject(tx);
|
|
|
|
return result.total;
|
|
});
|
|
|
|
/**
|
|
* Execute the tx input verification job (default timeout).
|
|
* @method
|
|
* @param {TX} tx
|
|
* @param {Number} index
|
|
* @param {Coin|Output} coin
|
|
* @param {VerifyFlags} flags
|
|
* @returns {Promise} - Returns Boolean.
|
|
*/
|
|
|
|
WorkerPool.prototype.verifyInput = co(function* verifyInput(tx, index, coin, flags) {
|
|
var packet = new packets.VerifyInputPacket(tx, index, coin, flags);
|
|
var result = yield this.execute(packet, -1);
|
|
return result.value;
|
|
});
|
|
|
|
/**
|
|
* Execute the tx input signing job (default timeout).
|
|
* @method
|
|
* @param {MTX} tx
|
|
* @param {Number} index
|
|
* @param {Coin|Output} coin
|
|
* @param {KeyRing} ring
|
|
* @param {SighashType} type
|
|
* @returns {Promise}
|
|
*/
|
|
|
|
WorkerPool.prototype.signInput = co(function* signInput(tx, index, coin, ring, type) {
|
|
var packet = new packets.SignInputPacket(tx, index, coin, ring, type);
|
|
var result = yield this.execute(packet, -1);
|
|
result.inject(tx);
|
|
return result.value;
|
|
});
|
|
|
|
/**
|
|
* Execute the ec verify job (no timeout).
|
|
* @method
|
|
* @param {Buffer} msg
|
|
* @param {Buffer} sig - DER formatted.
|
|
* @param {Buffer} key
|
|
* @returns {Promise}
|
|
*/
|
|
|
|
WorkerPool.prototype.ecVerify = co(function* ecVerify(msg, sig, key) {
|
|
var packet = new packets.ECVerifyPacket(msg, sig, key);
|
|
var result = yield this.execute(packet, -1);
|
|
return result.value;
|
|
});
|
|
|
|
/**
|
|
* Execute the ec signing job (no timeout).
|
|
* @method
|
|
* @param {Buffer} msg
|
|
* @param {Buffer} key
|
|
* @returns {Promise}
|
|
*/
|
|
|
|
WorkerPool.prototype.ecSign = co(function* ecSign(msg, key) {
|
|
var packet = new packets.SignPacket(msg, key);
|
|
var result = yield this.execute(packet, -1);
|
|
return result.sig;
|
|
});
|
|
|
|
/**
|
|
* Execute the mining job (no timeout).
|
|
* @method
|
|
* @param {Buffer} data
|
|
* @param {Buffer} target
|
|
* @param {Number} min
|
|
* @param {Number} max
|
|
* @returns {Promise} - Returns {Number}.
|
|
*/
|
|
|
|
WorkerPool.prototype.mine = co(function* mine(data, target, min, max) {
|
|
var packet = new packets.MinePacket(data, target, min, max);
|
|
var result = yield this.execute(packet, -1);
|
|
return result.nonce;
|
|
});
|
|
|
|
/**
|
|
* Execute scrypt job (no timeout).
|
|
* @method
|
|
* @param {Buffer} passwd
|
|
* @param {Buffer} salt
|
|
* @param {Number} N
|
|
* @param {Number} r
|
|
* @param {Number} p
|
|
* @param {Number} len
|
|
* @returns {Promise}
|
|
*/
|
|
|
|
WorkerPool.prototype.scrypt = co(function* scrypt(passwd, salt, N, r, p, len) {
|
|
var packet = new packets.ScryptPacket(passwd, salt, N, r, p, len);
|
|
var result = yield this.execute(packet, -1);
|
|
return result.key;
|
|
});
|
|
|
|
/**
|
|
* Represents a worker.
|
|
* @alias module:workers.Worker
|
|
* @constructor
|
|
* @param {Number?} id
|
|
*/
|
|
|
|
function Worker(id) {
|
|
if (!(this instanceof Worker))
|
|
return new Worker(id);
|
|
|
|
EventEmitter.call(this);
|
|
|
|
this.framer = new Framer();
|
|
this.parser = new Parser();
|
|
|
|
this.id = id != null ? id : -1;
|
|
this.child = null;
|
|
this.pending = {};
|
|
|
|
this.env = {
|
|
BCOIN_WORKER_NETWORK: Network.type,
|
|
BCOIN_WORKER_ISTTY: process.stdout
|
|
? (process.stdout.isTTY ? '1' : '0')
|
|
: '0'
|
|
};
|
|
|
|
this._init();
|
|
}
|
|
|
|
util.inherits(Worker, EventEmitter);
|
|
|
|
/**
|
|
* Initialize worker. Bind to events.
|
|
* @private
|
|
*/
|
|
|
|
Worker.prototype._init = function _init() {
|
|
var self = this;
|
|
|
|
this.on('data', function(data) {
|
|
self.parser.feed(data);
|
|
});
|
|
|
|
this.parser.on('error', function(err) {
|
|
self.emit('error', err);
|
|
});
|
|
|
|
this.parser.on('packet', function(packet) {
|
|
self.emit('packet', packet);
|
|
});
|
|
|
|
if (util.isBrowser) {
|
|
// Web workers
|
|
this._initWebWorkers();
|
|
} else {
|
|
// Child process + pipes
|
|
this._initChildProcess();
|
|
}
|
|
|
|
this._bind();
|
|
this._listen();
|
|
};
|
|
|
|
/**
|
|
* Initialize worker (web workers).
|
|
* @private
|
|
*/
|
|
|
|
Worker.prototype._initWebWorkers = function _initWebWorkers() {
|
|
var self = this;
|
|
|
|
this.child = new global.Worker('/bcoin-worker.js');
|
|
|
|
this.child.onerror = function onerror(err) {
|
|
self.emit('error', err);
|
|
self.emit('exit', -1, null);
|
|
};
|
|
|
|
this.child.onmessage = function onmessage(event) {
|
|
var data;
|
|
if (typeof event.data !== 'string') {
|
|
data = event.data.buf;
|
|
data.__proto__ = Buffer.prototype;
|
|
} else {
|
|
data = new Buffer(event.data, 'hex');
|
|
}
|
|
self.emit('data', data);
|
|
};
|
|
|
|
this.child.postMessage(JSON.stringify(this.env));
|
|
};
|
|
|
|
/**
|
|
* Initialize worker (node.js).
|
|
* @private
|
|
*/
|
|
|
|
Worker.prototype._initChildProcess = function _initChildProcess() {
|
|
var self = this;
|
|
var file = process.argv[0];
|
|
var argv = [__dirname + '/worker.js'];
|
|
var env = util.merge({}, process.env, this.env);
|
|
var options = { stdio: 'pipe', env: env };
|
|
|
|
this.child = cp.spawn(file, argv, options);
|
|
|
|
this.child.on('error', function(err) {
|
|
self.emit('error', err);
|
|
});
|
|
|
|
this.child.on('exit', function(code, signal) {
|
|
self.emit('exit', code == null ? -1 : code, signal);
|
|
});
|
|
|
|
this.child.on('close', function() {
|
|
self.emit('exit', -1, null);
|
|
});
|
|
|
|
this.child.stdin.on('error', function(err) {
|
|
self.emit('error', err);
|
|
});
|
|
|
|
this.child.stdout.on('error', function(err) {
|
|
self.emit('error', err);
|
|
});
|
|
|
|
this.child.stderr.on('error', function(err) {
|
|
self.emit('error', err);
|
|
});
|
|
|
|
this.child.stdout.on('data', function(data) {
|
|
self.emit('data', data);
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Bind to exit listener.
|
|
* @private
|
|
*/
|
|
|
|
Worker.prototype._bind = function _bind() {
|
|
var self = this;
|
|
|
|
this.on('exit', function(code) {
|
|
var i = WorkerPool.children.indexOf(self);
|
|
if (i !== -1)
|
|
WorkerPool.children.splice(i, 1);
|
|
});
|
|
|
|
WorkerPool.children.push(this);
|
|
|
|
WorkerPool.bindExit();
|
|
};
|
|
|
|
/**
|
|
* Listen for packets.
|
|
* @private
|
|
*/
|
|
|
|
Worker.prototype._listen = function _listen() {
|
|
var self = this;
|
|
|
|
this.on('exit', function() {
|
|
self.killJobs();
|
|
});
|
|
|
|
this.on('error', function(err) {
|
|
self.killJobs();
|
|
});
|
|
|
|
this.on('packet', function(packet) {
|
|
try {
|
|
self.handlePacket(packet);
|
|
} catch (e) {
|
|
self.emit('error', e);
|
|
}
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Handle packet.
|
|
* @private
|
|
* @param {Packet} packet
|
|
*/
|
|
|
|
Worker.prototype.handlePacket = function handlePacket(packet) {
|
|
switch (packet.cmd) {
|
|
case packets.types.EVENT:
|
|
this.emit.apply(this, packet.items);
|
|
this.emit('event', packet.items);
|
|
break;
|
|
case packets.types.LOG:
|
|
util.log('Worker %d:', this.id);
|
|
util.log(packet.text);
|
|
break;
|
|
case packets.types.ERROR:
|
|
this.emit('error', packet.error);
|
|
break;
|
|
case packets.types.ERRORRESULT:
|
|
this.rejectJob(packet.id, packet.error);
|
|
break;
|
|
default:
|
|
this.resolveJob(packet.id, packet);
|
|
break;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Send data to worker.
|
|
* @param {Buffer} data
|
|
* @returns {Boolean}
|
|
*/
|
|
|
|
Worker.prototype.write = function write(data) {
|
|
if (util.isBrowser) {
|
|
if (this.child.postMessage.length === 2) {
|
|
data.__proto__ = Uint8Array.prototype;
|
|
this.child.postMessage({ buf: data }, [data]);
|
|
} else {
|
|
this.child.postMessage(data.toString('hex'));
|
|
}
|
|
return true;
|
|
}
|
|
return this.child.stdin.write(data);
|
|
};
|
|
|
|
/**
|
|
* Frame and send a packet.
|
|
* @param {Packet} packet
|
|
* @returns {Boolean}
|
|
*/
|
|
|
|
Worker.prototype.send = function send(packet) {
|
|
return this.write(this.framer.packet(packet));
|
|
};
|
|
|
|
/**
|
|
* Emit an event on the worker side.
|
|
* @param {String} event
|
|
* @param {...Object} arg
|
|
* @returns {Boolean}
|
|
*/
|
|
|
|
Worker.prototype.sendEvent = function sendEvent() {
|
|
var items = new Array(arguments.length);
|
|
var i;
|
|
|
|
for (i = 0; i < items.length; i++)
|
|
items[i] = arguments[i];
|
|
|
|
return this.send(new packets.EventPacket(items));
|
|
};
|
|
|
|
/**
|
|
* Destroy the worker.
|
|
*/
|
|
|
|
Worker.prototype.destroy = function destroy() {
|
|
if (util.isBrowser) {
|
|
this.child.terminate();
|
|
this.emit('exit', -1, 'SIGTERM');
|
|
return;
|
|
}
|
|
return this.child.kill('SIGTERM');
|
|
};
|
|
|
|
/**
|
|
* Call a method for a worker to execute.
|
|
* @param {Packet} packet
|
|
* @param {Number} timeout
|
|
* @returns {Promise}
|
|
*/
|
|
|
|
Worker.prototype.execute = function execute(packet, timeout) {
|
|
var self = this;
|
|
return new Promise(function(resolve, reject) {
|
|
self._execute(packet, timeout, resolve, reject);
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Call a method for a worker to execute.
|
|
* @private
|
|
* @param {Packet} packet
|
|
* @param {Number} timeout
|
|
* @param {Function} resolve
|
|
* @param {Function} reject
|
|
* the worker method specifies.
|
|
*/
|
|
|
|
Worker.prototype._execute = function _execute(packet, timeout, resolve, reject) {
|
|
var job = new PendingJob(this, packet.id, resolve, reject);
|
|
|
|
assert(!this.pending[packet.id], 'ID overflow.');
|
|
|
|
this.pending[packet.id] = job;
|
|
|
|
job.start(timeout);
|
|
|
|
this.send(packet);
|
|
};
|
|
|
|
/**
|
|
* Resolve a job.
|
|
* @param {Number} id
|
|
* @param {Packet} result
|
|
*/
|
|
|
|
Worker.prototype.resolveJob = function resolveJob(id, result) {
|
|
var job = this.pending[id];
|
|
|
|
if (!job)
|
|
throw new Error('Job ' + id + ' is not in progress.');
|
|
|
|
job.resolve(result);
|
|
};
|
|
|
|
/**
|
|
* Reject a job.
|
|
* @param {Number} id
|
|
* @param {Error} err
|
|
*/
|
|
|
|
Worker.prototype.rejectJob = function rejectJob(id, err) {
|
|
var job = this.pending[id];
|
|
|
|
if (!job)
|
|
throw new Error('Job ' + id + ' is not in progress.');
|
|
|
|
job.reject(err);
|
|
};
|
|
|
|
/**
|
|
* Kill all jobs associated with worker.
|
|
*/
|
|
|
|
Worker.prototype.killJobs = function killJobs() {
|
|
var keys = Object.keys(this.pending);
|
|
var i, key, job;
|
|
|
|
for (i = 0; i < keys.length; i++) {
|
|
key = keys[i];
|
|
job = this.pending[key];
|
|
job.destroy();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Pending Job
|
|
* @constructor
|
|
* @ignore
|
|
* @param {Worker} worker
|
|
* @param {Number} id
|
|
* @param {Function} resolve
|
|
* @param {Function} reject
|
|
*/
|
|
|
|
function PendingJob(worker, id, resolve, reject) {
|
|
this.worker = worker;
|
|
this.id = id;
|
|
this.job = co.job(resolve, reject);
|
|
this.timer = null;
|
|
}
|
|
|
|
/**
|
|
* Start the timer.
|
|
* @param {Number} timeout
|
|
*/
|
|
|
|
PendingJob.prototype.start = function start(timeout) {
|
|
var self = this;
|
|
|
|
if (!timeout || timeout === -1)
|
|
return;
|
|
|
|
this.timer = setTimeout(function() {
|
|
self.reject(new Error('Worker timed out.'));
|
|
}, timeout);
|
|
};
|
|
|
|
/**
|
|
* Destroy the job with an error.
|
|
*/
|
|
|
|
PendingJob.prototype.destroy = function destroy() {
|
|
this.reject(new Error('Job was destroyed.'));
|
|
};
|
|
|
|
/**
|
|
* Cleanup job state.
|
|
* @returns {Job}
|
|
*/
|
|
|
|
PendingJob.prototype.cleanup = function cleanup() {
|
|
var job = this.job;
|
|
|
|
assert(job, 'Already finished.');
|
|
|
|
this.job = null;
|
|
|
|
if (this.timer != null) {
|
|
clearTimeout(this.timer);
|
|
this.timer = null;
|
|
}
|
|
|
|
assert(this.worker.pending[this.id]);
|
|
delete this.worker.pending[this.id];
|
|
|
|
return job;
|
|
};
|
|
|
|
/**
|
|
* Complete job with result.
|
|
* @param {Object} result
|
|
*/
|
|
|
|
PendingJob.prototype.resolve = function resolve(result) {
|
|
var job = this.cleanup();
|
|
job.resolve(result);
|
|
};
|
|
|
|
/**
|
|
* Complete job with error.
|
|
* @param {Error} err
|
|
*/
|
|
|
|
PendingJob.prototype.reject = function reject(err) {
|
|
var job = this.cleanup();
|
|
job.reject(err);
|
|
};
|
|
|
|
/*
|
|
* Helpers
|
|
*/
|
|
|
|
function getCores() {
|
|
if (os.unsupported)
|
|
return 2;
|
|
|
|
return Math.max(1, os.cpus().length);
|
|
}
|
|
|
|
/*
|
|
* Default Pool
|
|
*/
|
|
|
|
exports.pool = new WorkerPool();
|
|
exports.pool.enabled = true;
|
|
|
|
exports.set = function set(options) {
|
|
this.pool.set({
|
|
enabled: options.useWorkers,
|
|
size: options.maxWorkers || null,
|
|
timeout: options.workerTimeout || null
|
|
});
|
|
};
|
|
|
|
exports.set({
|
|
useWorkers: +process.env.BCOIN_USE_WORKERS !== 0,
|
|
maxWorkers: +process.env.BCOIN_MAX_WORKERS,
|
|
workerTimeout: +process.env.BCOIN_WORKER_TIMEOUT
|
|
});
|
|
|
|
/*
|
|
* Expose
|
|
*/
|
|
|
|
exports.WorkerPool = WorkerPool;
|
|
exports.Worker = Worker;
|
|
</code></pre>
|
|
</article>
|
|
</section>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
<nav>
|
|
<h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-bcoin.html">bcoin</a></li><li><a href="module-bip70.html">bip70</a></li><li><a href="module-bip70_pk.html">bip70/pk</a></li><li><a href="module-bip70_x509.html">bip70/x509</a></li><li><a href="module-blockchain.html">blockchain</a></li><li><a href="module-blockchain_common.html">blockchain/common</a></li><li><a href="module-btc.html">btc</a></li><li><a href="module-coins.html">coins</a></li><li><a href="module-crypto.html">crypto</a></li><li><a href="module-crypto_chachapoly.html">crypto/chachapoly</a></li><li><a href="module-crypto_ec.html">crypto/ec</a></li><li><a href="module-crypto_pk.html">crypto/pk</a></li><li><a href="module-crypto_schnorr.html">crypto/schnorr</a></li><li><a href="module-crypto_siphash.html">crypto/siphash</a></li><li><a href="module-db.html">db</a></li><li><a href="module-hd.html">hd</a></li><li><a href="module-http.html">http</a></li><li><a href="module-mempool.html">mempool</a></li><li><a href="module-mining.html">mining</a></li><li><a href="module-net.html">net</a></li><li><a href="module-net_bip152.html">net/bip152</a></li><li><a href="module-net_common.html">net/common</a></li><li><a href="module-net_dns.html">net/dns</a></li><li><a href="module-net_packets.html">net/packets</a></li><li><a href="module-net_socks.html">net/socks</a></li><li><a href="module-net_tcp.html">net/tcp</a></li><li><a href="module-node.html">node</a></li><li><a href="module-node_config.html">node/config</a></li><li><a href="module-primitives.html">primitives</a></li><li><a href="module-protocol.html">protocol</a></li><li><a href="module-protocol_consensus.html">protocol/consensus</a></li><li><a href="module-protocol_errors.html">protocol/errors</a></li><li><a href="module-protocol_networks.html">protocol/networks</a></li><li><a href="module-protocol_policy.html">protocol/policy</a></li><li><a href="module-script.html">script</a></li><li><a href="module-script_common.html">script/common</a></li><li><a href="module-utils.html">utils</a></li><li><a href="module-utils_asn1.html">utils/asn1</a></li><li><a href="module-utils_base32.html">utils/base32</a></li><li><a href="module-utils_base58.html">utils/base58</a></li><li><a href="module-utils_co.html">utils/co</a></li><li><a href="module-utils_encoding.html">utils/encoding</a></li><li><a href="module-utils_ip.html">utils/ip</a></li><li><a href="module-utils_pem.html">utils/pem</a></li><li><a href="module-utils_protobuf.html">utils/protobuf</a></li><li><a href="module-utils_util.html">utils/util</a></li><li><a href="module-wallet.html">wallet</a></li><li><a href="module-wallet_common.html">wallet/common</a></li><li><a href="module-wallet_records.html">wallet/records</a></li><li><a href="module-workers.html">workers</a></li><li><a href="module-workers_jobs.html">workers/jobs</a></li><li><a href="module-workers_packets.html">workers/packets</a></li></ul><h3>Classes</h3><ul><li><a href="Environment.html">Environment</a></li><li><a href="module-bip70.Payment.html">Payment</a></li><li><a href="module-bip70.PaymentACK.html">PaymentACK</a></li><li><a href="module-bip70.PaymentDetails.html">PaymentDetails</a></li><li><a href="module-bip70.PaymentRequest.html">PaymentRequest</a></li><li><a href="module-blockchain.Chain.html">Chain</a></li><li><a href="module-blockchain.ChainDB.html">ChainDB</a></li><li><a href="module-blockchain.ChainEntry.html">ChainEntry</a></li><li><a href="module-blockchain.ChainFlags.html">ChainFlags</a></li><li><a href="module-blockchain.ChainOptions.html">ChainOptions</a></li><li><a href="module-blockchain.ChainState.html">ChainState</a></li><li><a href="module-blockchain.DeploymentState.html">DeploymentState</a></li><li><a href="module-blockchain.StateCache.html">StateCache</a></li><li><a href="module-btc.Amount.html">Amount</a></li><li><a href="module-btc.URI.html">URI</a></li><li><a href="module-coins.CoinEntry.html">CoinEntry</a></li><li><a href="module-coins.Coins.html">Coins</a></li><li><a href="module-coins.CoinView.html">CoinView</a></li><li><a href="module-coins.UndoCoin.html">UndoCoin</a></li><li><a href="module-coins.UndoCoins.html">UndoCoins</a></li><li><a href="module-crypto_aes.AESCipher.html">AESCipher</a></li><li><a href="module-crypto_aes.AESDecipher.html">AESDecipher</a></li><li><a href="module-crypto_aes.AESKey.html">AESKey</a></li><li><a href="module-crypto_chachapoly.AEAD.html">AEAD</a></li><li><a href="module-crypto_chachapoly.ChaCha20.html">ChaCha20</a></li><li><a href="module-crypto_chachapoly.Poly1305.html">Poly1305</a></li><li><a href="module-crypto_sha256.SHA256.html">SHA256</a></li><li><a href="module-crypto_sha256.SHA256Hmac.html">SHA256Hmac</a></li><li><a href="module-db.LowlevelUp.html">LowlevelUp</a></li><li><a href="module-db.RBT.html">RBT</a></li><li><a href="module-hd.Mnemonic.html">Mnemonic</a></li><li><a href="module-hd.PrivateKey.html">PrivateKey</a></li><li><a href="module-hd.PublicKey.html">PublicKey</a></li><li><a href="module-http.Base.html">Base</a></li><li><a href="module-http.Client.html">Client</a></li><li><a href="module-http.HTTPBaseOptions.html">HTTPBaseOptions</a></li><li><a href="module-http.HTTPOptions.html">HTTPOptions</a></li><li><a href="module-http.Request.html">Request</a></li><li><a href="module-http.RPC.html">RPC</a></li><li><a href="module-http.RPCClient.html">RPCClient</a></li><li><a href="module-http.Server.html">Server</a></li><li><a href="module-http.Wallet.html">Wallet</a></li><li><a href="module-mempool.ConfirmStats.html">ConfirmStats</a></li><li><a href="module-mempool.Mempool.html">Mempool</a></li><li><a href="module-mempool.MempoolEntry.html">MempoolEntry</a></li><li><a href="module-mempool.MempoolOptions.html">MempoolOptions</a></li><li><a href="module-mempool.PolicyEstimator.html">PolicyEstimator</a></li><li><a href="module-mining.BlockEntry.html">BlockEntry</a></li><li><a href="module-mining.Miner.html">Miner</a></li><li><a href="module-mining.MinerBlock.html">MinerBlock</a></li><li><a href="module-mining.MinerOptions.html">MinerOptions</a></li><li><a href="module-net.AuthDB.html">AuthDB</a></li><li><a href="module-net.BIP150.html">BIP150</a></li><li><a href="module-net.BIP151.html">BIP151</a></li><li><a href="module-net.BIP151Stream.html">BIP151Stream</a></li><li><a href="module-net.BroadcastItem.html">BroadcastItem</a></li><li><a href="module-net.Framer.html">Framer</a></li><li><a href="module-net.HostEntry.html">HostEntry</a></li><li><a href="module-net.HostList.html">HostList</a></li><li><a href="module-net.Parser.html">Parser</a></li><li><a href="module-net.Peer.html">Peer</a></li><li><a href="module-net.PeerList.html">PeerList</a></li><li><a href="module-net.PeerOptions.html">PeerOptions</a></li><li><a href="module-net.Pool.html">Pool</a></li><li><a href="module-net.PoolOptions.html">PoolOptions</a></li><li><a href="module-net_bip152-CompactBlock.html">CompactBlock</a></li><li><a href="module-net_bip152-PrefilledTX.html">PrefilledTX</a></li><li><a href="module-net_bip152-TXRequest.html">TXRequest</a></li><li><a href="module-net_bip152-TXResponse.html">TXResponse</a></li><li><a href="module-net_packets-AddrPacket.html">AddrPacket</a></li><li><a href="module-net_packets-AuthChallengePacket.html">AuthChallengePacket</a></li><li><a href="module-net_packets-AuthProposePacket.html">AuthProposePacket</a></li><li><a href="module-net_packets-AuthReplyPacket.html">AuthReplyPacket</a></li><li><a href="module-net_packets-BlockPacket.html">BlockPacket</a></li><li><a href="module-net_packets-BlockTxnPacket.html">BlockTxnPacket</a></li><li><a href="module-net_packets-CmpctBlockPacket.html">CmpctBlockPacket</a></li><li><a href="module-net_packets-EncackPacket.html">EncackPacket</a></li><li><a href="module-net_packets-EncinitPacket.html">EncinitPacket</a></li><li><a href="module-net_packets-FeeFilterPacket.html">FeeFilterPacket</a></li><li><a href="module-net_packets-FilterAddPacket.html">FilterAddPacket</a></li><li><a href="module-net_packets-FilterClearPacket.html">FilterClearPacket</a></li><li><a href="module-net_packets-FilterLoadPacket.html">FilterLoadPacket</a></li><li><a href="module-net_packets-GetAddrPacket.html">GetAddrPacket</a></li><li><a href="module-net_packets-GetBlocksPacket.html">GetBlocksPacket</a></li><li><a href="module-net_packets-GetBlockTxnPacket.html">GetBlockTxnPacket</a></li><li><a href="module-net_packets-GetDataPacket.html">GetDataPacket</a></li><li><a href="module-net_packets-GetHeadersPacket.html">GetHeadersPacket</a></li><li><a href="module-net_packets-HeadersPacket.html">HeadersPacket</a></li><li><a href="module-net_packets-InvPacket.html">InvPacket</a></li><li><a href="module-net_packets-MempoolPacket.html">MempoolPacket</a></li><li><a href="module-net_packets-MerkleBlockPacket.html">MerkleBlockPacket</a></li><li><a href="module-net_packets-NotFoundPacket.html">NotFoundPacket</a></li><li><a href="module-net_packets-Packet.html">Packet</a></li><li><a href="module-net_packets-PingPacket.html">PingPacket</a></li><li><a href="module-net_packets-PongPacket.html">PongPacket</a></li><li><a href="module-net_packets-RejectPacket.html">RejectPacket</a></li><li><a href="module-net_packets-SendCmpctPacket.html">SendCmpctPacket</a></li><li><a href="module-net_packets-SendHeadersPacket.html">SendHeadersPacket</a></li><li><a href="module-net_packets-TXPacket.html">TXPacket</a></li><li><a href="module-net_packets-UnknownPacket.html">UnknownPacket</a></li><li><a href="module-net_packets-VerackPacket.html">VerackPacket</a></li><li><a href="module-net_packets-VersionPacket.html">VersionPacket</a></li><li><a href="module-net_socks-Proxy.html">Proxy</a></li><li><a href="module-net_socks-SOCKS.html">SOCKS</a></li><li><a href="module-node.FullNode.html">FullNode</a></li><li><a href="module-node.Logger.html">Logger</a></li><li><a href="module-node.Node.html">Node</a></li><li><a href="module-node.NodeClient.html">NodeClient</a></li><li><a href="module-node.SPVNode.html">SPVNode</a></li><li><a href="module-primitives.AbstractBlock.html">AbstractBlock</a></li><li><a href="module-primitives.Address.html">Address</a></li><li><a href="module-primitives.Block.html">Block</a></li><li><a href="module-primitives.Coin.html">Coin</a></li><li><a href="module-primitives.CoinSelector.html">CoinSelector</a></li><li><a href="module-primitives.Headers.html">Headers</a></li><li><a href="module-primitives.Input.html">Input</a></li><li><a href="module-primitives.InvItem.html">InvItem</a></li><li><a href="module-primitives.KeyRing.html">KeyRing</a></li><li><a href="module-primitives.MemBlock.html">MemBlock</a></li><li><a href="module-primitives.MerkleBlock.html">MerkleBlock</a></li><li><a href="module-primitives.MTX.html">MTX</a></li><li><a href="module-primitives.NetAddress.html">NetAddress</a></li><li><a href="module-primitives.Outpoint.html">Outpoint</a></li><li><a href="module-primitives.Output.html">Output</a></li><li><a href="module-primitives.TX.html">TX</a></li><li><a href="module-primitives.TXMeta.html">TXMeta</a></li><li><a href="module-protocol.Network.html">Network</a></li><li><a href="module-protocol.TimeData.html">TimeData</a></li><li><a href="module-protocol_errors-VerifyError.html">VerifyError</a></li><li><a href="module-protocol_errors-VerifyResult.html">VerifyResult</a></li><li><a href="module-script.Opcode.html">Opcode</a></li><li><a href="module-script.Program.html">Program</a></li><li><a href="module-script.Script.html">Script</a></li><li><a href="module-script.ScriptError.html">ScriptError</a></li><li><a href="module-script.SigCache.html">SigCache</a></li><li><a href="module-script.Stack.html">Stack</a></li><li><a href="module-script.Witness.html">Witness</a></li><li><a href="module-utils.AsyncEmitter.html">AsyncEmitter</a></li><li><a href="module-utils.AsyncObject.html">AsyncObject</a></li><li><a href="module-utils.Bloom.html">Bloom</a></li><li><a href="module-utils.BufferReader.html">BufferReader</a></li><li><a href="module-utils.BufferWriter.html">BufferWriter</a></li><li><a href="module-utils.List.html">List</a></li><li><a href="module-utils.ListItem.html">ListItem</a></li><li><a href="module-utils.Lock.html">Lock</a></li><li><a href="module-utils.LRU.html">LRU</a></li><li><a href="module-utils.LRUBatch.html">LRUBatch</a></li><li><a href="module-utils.LRUItem.html">LRUItem</a></li><li><a href="module-utils.LRUOp.html">LRUOp</a></li><li><a href="module-utils.Map.html">Map</a></li><li><a href="module-utils.MappedLock.html">MappedLock</a></li><li><a href="module-utils.RollingFilter.html">RollingFilter</a></li><li><a href="module-utils.StaticWriter.html">StaticWriter</a></li><li><a href="module-utils_ip.Address.html">Address</a></li><li><a href="module-utils_protobuf-ProtoReader.html">ProtoReader</a></li><li><a href="module-utils_protobuf-ProtoWriter.html">ProtoWriter</a></li><li><a href="module-wallet.Account.html">Account</a></li><li><a href="module-wallet.Balance.html">Balance</a></li><li><a href="module-wallet.BlockRecord.html">BlockRecord</a></li><li><a href="module-wallet.ChainState.html">ChainState</a></li><li><a href="module-wallet.Credit.html">Credit</a></li><li><a href="module-wallet.Details.html">Details</a></li><li><a href="module-wallet.DetailsMember.html">DetailsMember</a></li><li><a href="module-wallet.MasterKey.html">MasterKey</a></li><li><a href="module-wallet.Path.html">Path</a></li><li><a href="module-wallet.TXDB.html">TXDB</a></li><li><a href="module-wallet.Wallet.html">Wallet</a></li><li><a href="module-wallet.WalletClient.html">WalletClient</a></li><li><a href="module-wallet.WalletDB.html">WalletDB</a></li><li><a href="module-wallet.WalletKey.html">WalletKey</a></li><li><a href="module-wallet.WalletOptions.html">WalletOptions</a></li><li><a href="module-wallet_records-BlockMapRecord.html">BlockMapRecord</a></li><li><a href="module-wallet_records-BlockMeta.html">BlockMeta</a></li><li><a href="module-wallet_records-ChainState.html">ChainState</a></li><li><a href="module-wallet_records-OutpointMapRecord.html">OutpointMapRecord</a></li><li><a href="module-wallet_records-PathMapRecord.html">PathMapRecord</a></li><li><a href="module-wallet_records-TXMapRecord.html">TXMapRecord</a></li><li><a href="module-wallet_records-TXRecord.html">TXRecord</a></li><li><a href="module-workers.Framer.html">Framer</a></li><li><a href="module-workers.Master.html">Master</a></li><li><a href="module-workers.Parser.html">Parser</a></li><li><a href="module-workers.ParserClient.html">ParserClient</a></li><li><a href="module-workers.Worker.html">Worker</a></li><li><a href="module-workers.WorkerPool.html">WorkerPool</a></li><li><a href="module-workers_packets-ECSignPacket.html">ECSignPacket</a></li><li><a href="module-workers_packets-ECSignResultPacket.html">ECSignResultPacket</a></li><li><a href="module-workers_packets-ECVerifyPacket.html">ECVerifyPacket</a></li><li><a href="module-workers_packets-ECVerifyResultPacket.html">ECVerifyResultPacket</a></li><li><a href="module-workers_packets-ErrorPacket.html">ErrorPacket</a></li><li><a href="module-workers_packets-ErrorResultPacket.html">ErrorResultPacket</a></li><li><a href="module-workers_packets-EventPacket.html">EventPacket</a></li><li><a href="module-workers_packets-LogPacket.html">LogPacket</a></li><li><a href="module-workers_packets-MinePacket.html">MinePacket</a></li><li><a href="module-workers_packets-MineResultPacket.html">MineResultPacket</a></li><li><a href="module-workers_packets-Packet.html">Packet</a></li><li><a href="module-workers_packets-ScryptPacket.html">ScryptPacket</a></li><li><a href="module-workers_packets-ScryptResultPacket.html">ScryptResultPacket</a></li><li><a href="module-workers_packets-SignInputPacket.html">SignInputPacket</a></li><li><a href="module-workers_packets-SignInputResultPacket.html">SignInputResultPacket</a></li><li><a href="module-workers_packets-SignPacket.html">SignPacket</a></li><li><a href="module-workers_packets-SignResultPacket.html">SignResultPacket</a></li><li><a href="module-workers_packets-VerifyInputPacket.html">VerifyInputPacket</a></li><li><a href="module-workers_packets-VerifyInputResultPacket.html">VerifyInputResultPacket</a></li><li><a href="module-workers_packets-VerifyPacket.html">VerifyPacket</a></li><li><a href="module-workers_packets-VerifyResultPacket.html">VerifyResultPacket</a></li></ul><h3>Namespaces</h3><ul><li><a href="module-crypto_pk.ecdsa.html">ecdsa</a></li><li><a href="module-crypto_pk.rsa.html">rsa</a></li></ul><h3>Global</h3><ul><li><a href="global.html"></a></li><li><a href="global.html#DoubleMap">DoubleMap</a></li><li><a href="global.html#StatEntry">StatEntry</a></li></ul>
|
|
</nav>
|
|
|
|
<br class="clear">
|
|
|
|
<footer>
|
|
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0</a> on Fri Feb 10 2017 09:40:23 GMT-0800 (PST)
|
|
</footer>
|
|
|
|
<script> prettyPrint(); </script>
|
|
<script src="scripts/linenumber.js"> </script>
|
|
</body>
|
|
</html>
|
|
|