itns-sidechain/lib/workers/workerpool.js

909 lines
18 KiB
JavaScript
Raw Normal View History

/*!
2016-11-19 06:48:55 -08:00
* workerpool.js - worker processes for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
2017-02-03 22:47:26 -08:00
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
2016-06-09 16:18:50 -07:00
* https://github.com/bcoin-org/bcoin
*/
2016-06-13 01:06:01 -07:00
'use strict';
2016-12-02 11:06:01 -08:00
var assert = require('assert');
2016-05-02 19:47:41 -07:00
var EventEmitter = require('events').EventEmitter;
2017-01-14 14:41:55 -08:00
var os = require('os');
var cp = require('child_process');
2016-11-19 10:45:31 -08:00
var util = require('../utils/util');
2016-10-02 02:43:50 -07:00
var co = require('../utils/co');
2016-11-19 10:45:31 -08:00
var global = util.global;
2016-10-02 01:01:16 -07:00
var Network = require('../protocol/network');
2016-08-23 23:56:50 -07:00
var jobs = require('./jobs');
2016-10-02 01:01:16 -07:00
var Parser = require('./parser');
var Framer = require('./framer');
2016-12-02 11:06:01 -08:00
var packets = require('./packets');
/**
2016-05-02 19:47:41 -07:00
* A worker pool.
2017-02-03 22:47:26 -08:00
* @alias module:workers.WorkerPool
2016-05-02 19:47:41 -07:00
* @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
2016-07-04 05:36:06 -07:00
* @property {Number} nonce
*/
2016-10-12 22:28:29 -07:00
function WorkerPool(options) {
if (!(this instanceof WorkerPool))
return new WorkerPool(options);
2016-05-02 19:47:41 -07:00
EventEmitter.call(this);
2017-01-14 14:41:55 -08:00
this.size = WorkerPool.CORES;
this.timeout = 60000;
2016-05-03 18:53:43 -07:00
this.children = [];
2016-07-04 05:36:06 -07:00
this.nonce = 0;
2016-10-05 16:16:08 -07:00
this.enabled = true;
2017-01-14 14:41:55 -08:00
this.set(options);
2017-01-14 19:21:46 -08:00
this.on('error', util.nop);
2016-05-02 19:47:41 -07:00
}
2016-11-19 10:45:31 -08:00
util.inherits(WorkerPool, EventEmitter);
2016-11-19 06:48:55 -08:00
/**
* Whether workers are supported.
* @const {Boolean}
*/
WorkerPool.support = true;
2016-11-19 10:45:31 -08:00
if (util.isBrowser) {
2016-11-19 06:48:55 -08:00
WorkerPool.support = typeof global.Worker === 'function'
|| typeof global.postMessage === 'function';
}
/**
2016-05-02 19:47:41 -07:00
* Number of CPUs/cores available.
* @const {Number}
*/
2016-10-12 22:28:29 -07:00
WorkerPool.CORES = getCores();
2016-05-22 18:13:54 -07:00
/**
* Global list of workers.
* @type {Array}
*/
2016-10-12 22:28:29 -07:00
WorkerPool.children = [];
2016-05-22 18:13:54 -07:00
/**
2016-07-04 05:36:06 -07:00
* Destroy all workers.
* Used for cleaning up workers on exit.
* @private
2016-05-22 18:13:54 -07:00
*/
2016-10-12 22:28:29 -07:00
WorkerPool.cleanup = function cleanup() {
while (WorkerPool.children.length > 0)
WorkerPool.children.pop().destroy();
2016-05-22 18:13:54 -07:00
};
2017-01-14 14:41:55 -08:00
/**
* Whether exit events have been bound globally.
* @private
* @type {Boolean}
*/
WorkerPool.bound = false;
2016-05-22 18:13:54 -07:00
2016-06-02 01:01:54 -07:00
/**
2017-01-09 14:59:35 -08:00
* Bind to process events in
* order to cleanup listeners.
2016-06-02 01:01:54 -07:00
* @private
*/
2017-01-14 14:41:55 -08:00
WorkerPool.bindExit = function bindExit() {
2016-11-19 10:45:31 -08:00
if (util.isBrowser)
2016-06-02 01:01:54 -07:00
return;
2017-01-14 14:41:55 -08:00
if (WorkerPool.bound)
2016-06-02 01:01:54 -07:00
return;
2017-01-14 14:41:55 -08:00
WorkerPool.bound = true;
2016-06-02 01:01:54 -07:00
2017-01-09 14:59:35 -08:00
function onSignal() {
2016-10-12 22:28:29 -07:00
WorkerPool.cleanup();
2017-01-09 14:59:35 -08:00
process.exit(0);
}
2016-07-04 05:36:06 -07:00
2017-01-09 14:59:35 -08:00
function onError(err) {
WorkerPool.cleanup();
if (err && err.stack)
2016-11-19 10:45:31 -08:00
util.error(err.stack + '');
2017-01-09 14:59:35 -08:00
process.exit(1);
2016-06-02 01:01:54 -07:00
}
process.once('exit', function() {
2016-10-12 22:28:29 -07:00
WorkerPool.cleanup();
2016-06-02 01:01:54 -07:00
});
if (process.listeners('SIGINT').length === 0)
2017-01-09 14:59:35 -08:00
process.once('SIGINT', onSignal);
2016-06-02 01:01:54 -07:00
if (process.listeners('SIGTERM').length === 0)
2017-01-09 14:59:35 -08:00
process.once('SIGTERM', onSignal);
2016-06-02 01:01:54 -07:00
if (process.listeners('uncaughtException').length === 0)
2017-01-09 14:59:35 -08:00
process.once('uncaughtException', onError);
2016-06-02 01:01:54 -07:00
process.on('newListener', function(name) {
2017-01-09 14:59:35 -08:00
switch (name) {
case 'SIGINT':
case 'SIGTERM':
process.removeListener(name, onSignal);
break;
case 'uncaughtException':
process.removeListener(name, onError);
break;
2016-06-02 01:01:54 -07:00
}
});
};
2017-01-14 14:41:55 -08:00
/**
* 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.
2016-05-03 18:53:43 -07:00
* @param {Number} id - Worker ID.
2016-05-03 03:56:07 -07:00
* @returns {Worker}
*/
2016-10-12 22:28:29 -07:00
WorkerPool.prototype.spawn = function spawn(id) {
2016-05-02 19:47:41 -07:00
var self = this;
2016-07-04 05:36:06 -07:00
var child;
2016-07-04 05:36:06 -07:00
child = new Worker(id);
child.on('error', function(err) {
2016-07-04 05:36:06 -07:00
self.emit('error', err, child);
});
child.on('exit', function(code) {
2016-07-04 05:36:06 -07:00
self.emit('exit', code, child);
2016-05-02 19:47:41 -07:00
if (self.children[child.id] === child)
2016-05-03 18:53:43 -07:00
self.children[child.id] = null;
});
2016-07-04 05:36:06 -07:00
child.on('event', function(items) {
self.emit('event', items, child);
self.emit.apply(self, items);
});
2016-07-04 05:36:06 -07:00
this.emit('spawn', child);
2016-05-22 18:13:54 -07:00
return child;
};
/**
2016-05-02 19:47:41 -07:00
* Allocate a new worker, will not go above `size` option
2016-07-04 05:36:06 -07:00
* and will automatically load balance the workers.
2016-05-03 03:56:07 -07:00
* @returns {Worker}
*/
2016-10-12 22:28:29 -07:00
WorkerPool.prototype.alloc = function alloc() {
2016-07-04 05:36:06 -07:00
var id = this.nonce++ % this.size;
2016-05-02 19:47:41 -07:00
if (!this.children[id])
this.children[id] = this.spawn(id);
return this.children[id];
};
2016-05-03 18:53:43 -07:00
/**
* Emit an event on the worker side (all workers).
* @param {String} event
* @param {...Object} arg
* @returns {Boolean}
*/
2016-10-12 22:28:29 -07:00
WorkerPool.prototype.sendEvent = function sendEvent() {
2016-05-03 18:53:43 -07:00
var result = true;
2017-01-09 14:59:35 -08:00
var i, child;
2016-05-03 18:53:43 -07:00
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.
*/
2016-10-12 22:28:29 -07:00
WorkerPool.prototype.destroy = function destroy() {
2016-05-03 18:53:43 -07:00
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.
2016-12-02 11:06:01 -08:00
* @param {Packet} packet
* @param {Number} timeout
2016-09-23 01:05:06 -07:00
* @returns {Promise}
*/
2016-12-02 11:06:01 -08:00
WorkerPool.prototype.execute = function execute(packet, timeout) {
var result, child;
2016-11-19 06:48:55 -08:00
if (!this.enabled || !WorkerPool.support) {
2016-10-05 14:37:29 -07:00
return new Promise(function(resolve, reject) {
2016-11-19 10:45:31 -08:00
util.nextTick(function() {
2016-10-05 14:37:29 -07:00
try {
2016-12-02 11:06:01 -08:00
result = jobs._execute(packet);
2016-10-05 14:37:29 -07:00
} catch (e) {
reject(e);
return;
}
resolve(result);
});
});
}
2016-05-03 12:45:56 -07:00
if (!timeout)
timeout = this.timeout;
2016-07-04 05:36:06 -07:00
child = this.alloc();
2016-05-02 19:47:41 -07:00
2016-12-02 11:06:01 -08:00
return child.execute(packet, timeout);
2016-05-02 19:47:41 -07:00
};
/**
* Execute the tx verification job (default timeout).
2017-02-03 22:47:26 -08:00
* @method
2016-05-02 19:47:41 -07:00
* @param {TX} tx
2016-12-10 19:42:46 -08:00
* @param {CoinView} view
2016-05-02 19:47:41 -07:00
* @param {VerifyFlags} flags
2016-09-23 01:05:06 -07:00
* @returns {Promise} - Returns Boolean.
2016-05-02 19:47:41 -07:00
*/
WorkerPool.prototype.verify = co(function* verify(tx, view, flags) {
var packet = new packets.VerifyPacket(tx, view, flags);
2016-12-02 11:06:01 -08:00
var result = yield this.execute(packet, -1);
return result.value;
});
2016-09-22 02:49:18 -07:00
2016-07-15 08:36:19 -07:00
/**
* Execute the tx signing job (default timeout).
2017-02-03 22:47:26 -08:00
* @method
2016-07-15 08:36:19 -07:00
* @param {MTX} tx
2016-09-22 02:49:18 -07:00
* @param {KeyRing[]} ring
* @param {SighashType} type
2016-09-23 01:05:06 -07:00
* @returns {Promise}
2016-07-15 08:36:19 -07:00
*/
2016-10-12 22:28:29 -07:00
WorkerPool.prototype.sign = co(function* sign(tx, ring, type) {
2016-12-02 11:06:01 -08:00
var rings = ring;
var packet, result;
2016-07-15 08:36:19 -07:00
2016-12-02 11:06:01 -08:00
if (!Array.isArray(rings))
rings = [rings];
2016-07-15 08:36:19 -07:00
2016-12-02 11:06:01 -08:00
packet = new packets.SignPacket(tx, rings, type);
result = yield this.execute(packet, -1);
2016-07-15 08:36:19 -07:00
2016-12-02 11:06:01 -08:00
result.inject(tx);
2016-07-15 08:36:19 -07:00
2016-12-02 11:06:01 -08:00
return result.total;
});
/**
* Execute the tx input verification job (default timeout).
2017-02-03 22:47:26 -08:00
* @method
2016-12-02 11:06:01 -08:00
* @param {TX} tx
* @param {Number} index
2016-12-06 17:37:35 -08:00
* @param {Coin|Output} coin
2016-12-02 11:06:01 -08:00
* @param {VerifyFlags} flags
* @returns {Promise} - Returns Boolean.
*/
2016-12-06 17:37:35 -08:00
WorkerPool.prototype.verifyInput = co(function* verifyInput(tx, index, coin, flags) {
var packet = new packets.VerifyInputPacket(tx, index, coin, flags);
2016-12-02 11:06:01 -08:00
var result = yield this.execute(packet, -1);
return result.value;
2016-09-21 22:58:27 -07:00
});
2016-07-15 08:36:19 -07:00
2016-09-22 02:49:18 -07:00
/**
* Execute the tx input signing job (default timeout).
2017-02-03 22:47:26 -08:00
* @method
2016-09-22 02:49:18 -07:00
* @param {MTX} tx
* @param {Number} index
2016-12-06 17:37:35 -08:00
* @param {Coin|Output} coin
2016-12-02 11:06:01 -08:00
* @param {KeyRing} ring
2016-09-22 02:49:18 -07:00
* @param {SighashType} type
2016-09-23 01:05:06 -07:00
* @returns {Promise}
2016-09-22 02:49:18 -07:00
*/
2016-12-06 17:37:35 -08:00
WorkerPool.prototype.signInput = co(function* signInput(tx, index, coin, ring, type) {
var packet = new packets.SignInputPacket(tx, index, coin, ring, type);
2016-12-03 18:02:10 -08:00
var result = yield this.execute(packet, -1);
2016-12-02 11:06:01 -08:00
result.inject(tx);
return result.value;
2016-09-22 02:49:18 -07:00
});
/**
* Execute the ec verify job (no timeout).
2017-02-03 22:47:26 -08:00
* @method
2016-09-22 02:49:18 -07:00
* @param {Buffer} msg
* @param {Buffer} sig - DER formatted.
* @param {Buffer} key
2016-09-23 01:05:06 -07:00
* @returns {Promise}
2016-09-22 02:49:18 -07:00
*/
2016-12-02 11:06:01 -08:00
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;
});
2016-09-22 02:49:18 -07:00
/**
* Execute the ec signing job (no timeout).
2017-02-03 22:47:26 -08:00
* @method
2016-09-22 02:49:18 -07:00
* @param {Buffer} msg
* @param {Buffer} key
2016-09-23 01:05:06 -07:00
* @returns {Promise}
2016-09-22 02:49:18 -07:00
*/
2016-12-02 11:06:01 -08:00
WorkerPool.prototype.ecSign = co(function* ecSign(msg, key) {
2017-02-21 22:33:42 -08:00
var packet = new packets.ECSignPacket(msg, key);
2016-12-02 11:06:01 -08:00
var result = yield this.execute(packet, -1);
return result.sig;
});
2016-09-22 02:49:18 -07:00
2016-05-02 19:47:41 -07:00
/**
* Execute the mining job (no timeout).
2017-02-03 22:47:26 -08:00
* @method
2016-10-05 16:16:08 -07:00
* @param {Buffer} data
* @param {Buffer} target
* @param {Number} min
* @param {Number} max
* @returns {Promise} - Returns {Number}.
2016-05-02 19:47:41 -07:00
*/
2016-12-02 11:06:01 -08:00
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;
});
2016-05-02 19:47:41 -07:00
2016-06-01 22:27:33 -07:00
/**
* Execute scrypt job (no timeout).
2017-02-03 22:47:26 -08:00
* @method
2016-06-01 22:27:33 -07:00
* @param {Buffer} passwd
* @param {Buffer} salt
* @param {Number} N
* @param {Number} r
* @param {Number} p
* @param {Number} len
2016-09-23 01:05:06 -07:00
* @returns {Promise}
2016-06-01 22:27:33 -07:00
*/
2016-12-02 11:06:01 -08:00
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;
});
2016-06-01 22:27:33 -07:00
2016-05-02 19:47:41 -07:00
/**
* Represents a worker.
2017-02-03 22:47:26 -08:00
* @alias module:workers.Worker
2016-05-02 19:47:41 -07:00
* @constructor
2016-07-04 05:36:06 -07:00
* @param {Number?} id
2016-05-02 19:47:41 -07:00
*/
2016-07-04 05:36:06 -07:00
function Worker(id) {
2016-05-02 19:47:41 -07:00
if (!(this instanceof Worker))
2016-10-12 22:28:29 -07:00
return new Worker(id);
2016-05-02 19:47:41 -07:00
EventEmitter.call(this);
this.framer = new Framer();
this.parser = new Parser();
2017-01-09 14:59:35 -08:00
2016-07-04 05:36:06 -07:00
this.id = id != null ? id : -1;
2016-07-27 17:17:17 -07:00
this.child = null;
2016-12-02 11:06:01 -08:00
this.pending = {};
2017-01-09 14:59:35 -08:00
2016-12-02 18:14:17 -08:00
this.env = {
2016-12-02 18:34:29 -08:00
BCOIN_WORKER_NETWORK: Network.type,
BCOIN_WORKER_ISTTY: process.stdout
? (process.stdout.isTTY ? '1' : '0')
: '0'
2016-12-02 18:14:17 -08:00
};
2016-07-27 17:17:17 -07:00
this._init();
}
2016-11-19 10:45:31 -08:00
util.inherits(Worker, EventEmitter);
2016-09-20 14:56:54 -07:00
2016-07-27 17:17:17 -07:00
/**
* Initialize worker. Bind to events.
* @private
*/
Worker.prototype._init = function _init() {
var self = this;
2016-05-02 19:47:41 -07:00
2016-12-02 18:14:17 -08:00
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);
});
2016-05-06 23:28:14 -07:00
2016-11-19 10:45:31 -08:00
if (util.isBrowser) {
2016-12-02 18:14:17 -08:00
// Web workers
this._initWebWorkers();
2016-05-02 19:47:41 -07:00
} else {
2016-12-02 18:14:17 -08:00
// Child process + pipes
this._initChildProcess();
}
2016-05-02 19:47:41 -07:00
2016-12-02 18:14:17 -08:00
this._bind();
this._listen();
};
2016-05-02 19:47:41 -07:00
2016-12-02 18:14:17 -08:00
/**
* Initialize worker (web workers).
* @private
*/
2016-05-02 19:47:41 -07:00
2016-12-02 18:14:17 -08:00
Worker.prototype._initWebWorkers = function _initWebWorkers() {
var self = this;
2016-05-02 19:47:41 -07:00
2016-12-02 18:14:17 -08:00
this.child = new global.Worker('/bcoin-worker.js');
2016-12-02 18:14:17 -08:00
this.child.onerror = function onerror(err) {
self.emit('error', err);
self.emit('exit', -1, null);
};
2016-12-02 18:14:17 -08:00
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);
};
2016-05-02 19:47:41 -07:00
2016-12-02 18:14:17 -08:00
this.child.postMessage(JSON.stringify(this.env));
};
2016-05-02 19:47:41 -07:00
2016-12-02 18:14:17 -08:00
/**
* 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);
2017-05-01 11:41:05 -07:00
2017-04-30 06:10:01 -07:00
this.child.unref();
2017-05-01 11:41:05 -07:00
this.child.stdin.unref();
this.child.stdout.unref();
this.child.stderr.unref();
2016-12-02 18:14:17 -08:00
this.child.on('error', function(err) {
self.emit('error', err);
2016-12-02 11:06:01 -08:00
});
2016-12-02 18:14:17 -08:00
this.child.on('exit', function(code, signal) {
self.emit('exit', code == null ? -1 : code, signal);
2016-12-02 11:06:01 -08:00
});
2016-12-02 18:14:17 -08:00
this.child.on('close', function() {
self.emit('exit', -1, null);
2016-05-02 19:47:41 -07:00
});
2016-12-02 18:14:17 -08:00
this.child.stdin.on('error', function(err) {
self.emit('error', err);
2016-05-02 19:47:41 -07:00
});
2016-12-02 18:14:17 -08:00
this.child.stdout.on('error', function(err) {
self.emit('error', err);
2016-05-02 19:47:41 -07:00
});
2016-07-04 05:36:06 -07:00
2016-12-02 18:14:17 -08:00
this.child.stderr.on('error', function(err) {
self.emit('error', err);
});
this.child.stdout.on('data', function(data) {
self.emit('data', data);
});
2016-07-29 10:13:51 -07:00
};
2016-05-02 19:47:41 -07:00
2016-07-04 05:36:06 -07:00
/**
2016-12-02 18:14:17 -08:00
* Bind to exit listener.
2016-07-04 05:36:06 -07:00
* @private
*/
2016-07-27 17:17:17 -07:00
Worker.prototype._bind = function _bind() {
2016-07-04 05:36:06 -07:00
var self = this;
this.on('exit', function(code) {
2016-10-12 22:28:29 -07:00
var i = WorkerPool.children.indexOf(self);
2016-07-04 05:36:06 -07:00
if (i !== -1)
2016-10-12 22:28:29 -07:00
WorkerPool.children.splice(i, 1);
2016-07-04 05:36:06 -07:00
});
2016-12-02 18:14:17 -08:00
WorkerPool.children.push(this);
2017-01-14 14:41:55 -08:00
WorkerPool.bindExit();
2016-12-02 18:14:17 -08:00
};
/**
* Listen for packets.
* @private
*/
Worker.prototype._listen = function _listen() {
var self = this;
this.on('exit', function() {
self.killJobs();
});
2016-12-10 21:44:01 -08:00
this.on('error', function(err) {
2016-12-02 18:14:17 -08:00
self.killJobs();
});
2016-07-27 05:42:36 -07:00
this.on('packet', function(packet) {
2016-12-02 18:14:17 -08:00
try {
self.handlePacket(packet);
} catch (e) {
self.emit('error', e);
2016-07-04 05:36:06 -07:00
}
});
2016-12-02 18:14:17 -08:00
};
2016-07-04 05:36:06 -07:00
2016-12-02 18:14:17 -08:00
/**
* Handle packet.
* @private
* @param {Packet} packet
*/
2016-07-04 05:36:06 -07:00
2016-12-02 18:14:17 -08:00
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);
2016-12-02 18:34:29 -08:00
util.log(packet.text);
2016-12-02 18:14:17 -08:00
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;
}
2016-07-04 05:36:06 -07:00
};
2016-05-02 19:47:41 -07:00
/**
* Send data to worker.
* @param {Buffer} data
* @returns {Boolean}
*/
Worker.prototype.write = function write(data) {
2016-11-19 10:45:31 -08:00
if (util.isBrowser) {
2016-05-02 19:47:41 -07:00
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.
2016-12-02 11:06:01 -08:00
* @param {Packet} packet
2016-05-03 18:53:43 -07:00
* @returns {Boolean}
2016-05-02 19:47:41 -07:00
*/
2016-12-02 11:06:01 -08:00
Worker.prototype.send = function send(packet) {
return this.write(this.framer.packet(packet));
2016-05-02 19:47:41 -07:00
};
/**
* Emit an event on the worker side.
* @param {String} event
* @param {...Object} arg
2016-05-03 18:53:43 -07:00
* @returns {Boolean}
2016-05-02 19:47:41 -07:00
*/
Worker.prototype.sendEvent = function sendEvent() {
2016-06-13 03:17:28 -07:00
var items = new Array(arguments.length);
var i;
for (i = 0; i < items.length; i++)
items[i] = arguments[i];
2016-12-02 11:06:01 -08:00
return this.send(new packets.EventPacket(items));
2016-05-02 19:47:41 -07:00
};
/**
* Destroy the worker.
*/
Worker.prototype.destroy = function destroy() {
2016-11-19 10:45:31 -08:00
if (util.isBrowser) {
2016-05-02 19:47:41 -07:00
this.child.terminate();
this.emit('exit', -1, 'SIGTERM');
return;
}
return this.child.kill('SIGTERM');
};
/**
* Call a method for a worker to execute.
2016-12-02 11:06:01 -08:00
* @param {Packet} packet
* @param {Number} timeout
2016-09-23 01:05:06 -07:00
* @returns {Promise}
2016-05-02 19:47:41 -07:00
*/
2016-12-02 11:06:01 -08:00
Worker.prototype.execute = function execute(packet, timeout) {
2016-05-02 19:47:41 -07:00
var self = this;
2016-12-02 11:06:01 -08:00
return new Promise(function(resolve, reject) {
2017-01-05 04:30:29 -08:00
self._execute(packet, timeout, resolve, reject);
2016-12-02 11:06:01 -08:00
});
};
2016-07-04 05:36:06 -07:00
2016-12-02 11:06:01 -08:00
/**
* Call a method for a worker to execute.
* @private
* @param {Packet} packet
* @param {Number} timeout
2017-01-05 04:30:29 -08:00
* @param {Function} resolve
* @param {Function} reject
2016-12-02 11:06:01 -08:00
* the worker method specifies.
*/
2016-05-02 19:47:41 -07:00
2017-01-05 04:30:29 -08:00
Worker.prototype._execute = function _execute(packet, timeout, resolve, reject) {
var job = new PendingJob(this, packet.id, resolve, reject);
2016-12-02 18:34:29 -08:00
assert(!this.pending[packet.id], 'ID overflow.');
2016-12-02 11:06:01 -08:00
this.pending[packet.id] = job;
2016-05-03 18:53:43 -07:00
2016-12-02 11:06:01 -08:00
job.start(timeout);
2016-12-02 11:06:01 -08:00
this.send(packet);
};
2016-12-02 11:06:01 -08:00
/**
* Resolve a job.
* @param {Number} id
* @param {Packet} result
*/
Worker.prototype.resolveJob = function resolveJob(id, result) {
var job = this.pending[id];
2016-12-02 18:34:29 -08:00
if (!job)
throw new Error('Job ' + id + ' is not in progress.');
2017-01-05 04:30:29 -08:00
job.resolve(result);
};
2016-09-20 14:56:54 -07:00
/**
2016-12-02 11:06:01 -08:00
* Reject a job.
* @param {Number} id
* @param {Error} err
2016-09-20 14:56:54 -07:00
*/
2016-12-02 11:06:01 -08:00
Worker.prototype.rejectJob = function rejectJob(id, err) {
var job = this.pending[id];
2016-12-02 18:34:29 -08:00
if (!job)
throw new Error('Job ' + id + ' is not in progress.');
2017-01-05 04:30:29 -08:00
job.reject(err);
2016-12-02 11:06:01 -08:00
};
/**
* 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();
}
};
/**
2017-02-03 22:47:26 -08:00
* Pending Job
2016-12-02 11:06:01 -08:00
* @constructor
2017-02-03 22:47:26 -08:00
* @ignore
2016-12-02 18:14:17 -08:00
* @param {Worker} worker
* @param {Number} id
2017-01-05 04:30:29 -08:00
* @param {Function} resolve
* @param {Function} reject
2016-12-02 11:06:01 -08:00
*/
2017-01-05 04:30:29 -08:00
function PendingJob(worker, id, resolve, reject) {
2016-12-02 11:06:01 -08:00
this.worker = worker;
this.id = id;
2017-01-05 04:30:29 -08:00
this.job = co.job(resolve, reject);
2016-12-02 11:06:01 -08:00
this.timer = null;
}
2016-12-02 18:14:17 -08:00
/**
* Start the timer.
* @param {Number} timeout
*/
2016-12-02 11:06:01 -08:00
PendingJob.prototype.start = function start(timeout) {
2016-09-20 14:56:54 -07:00
var self = this;
2016-12-02 11:06:01 -08:00
2016-12-02 18:34:29 -08:00
if (!timeout || timeout === -1)
2016-12-02 11:06:01 -08:00
return;
this.timer = setTimeout(function() {
2017-01-05 04:30:29 -08:00
self.reject(new Error('Worker timed out.'));
2016-12-02 11:06:01 -08:00
}, timeout);
};
2016-12-02 18:14:17 -08:00
/**
* Destroy the job with an error.
*/
2016-12-02 11:06:01 -08:00
PendingJob.prototype.destroy = function destroy() {
2017-01-05 04:30:29 -08:00
this.reject(new Error('Job was destroyed.'));
2016-12-02 11:06:01 -08:00
};
2016-12-02 18:14:17 -08:00
/**
2017-01-05 04:30:29 -08:00
* Cleanup job state.
* @returns {Job}
2016-12-02 18:14:17 -08:00
*/
2017-01-05 04:30:29 -08:00
PendingJob.prototype.cleanup = function cleanup() {
var job = this.job;
2016-12-02 11:06:01 -08:00
2017-01-05 04:30:29 -08:00
assert(job, 'Already finished.');
2016-12-02 11:06:01 -08:00
2017-01-05 04:30:29 -08:00
this.job = null;
2016-12-02 11:06:01 -08:00
if (this.timer != null) {
clearTimeout(this.timer);
this.timer = null;
}
assert(this.worker.pending[this.id]);
delete this.worker.pending[this.id];
2017-01-05 04:30:29 -08:00
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);
2016-09-20 14:56:54 -07:00
};
2016-05-02 19:47:41 -07:00
2016-07-04 05:36:06 -07:00
/*
* Helpers
2016-05-02 19:47:41 -07:00
*/
2016-05-02 19:47:41 -07:00
function getCores() {
if (os.unsupported)
2016-06-05 06:55:35 -07:00
return 2;
2016-11-19 02:27:26 -08:00
2017-01-14 14:41:55 -08:00
return Math.max(1, os.cpus().length);
}
/*
2017-01-14 14:41:55 -08:00
* Default Pool
*/
2016-10-12 22:28:29 -07:00
exports.pool = new WorkerPool();
exports.pool.enabled = true;
2016-10-05 16:16:08 -07:00
2016-10-12 22:28:29 -07:00
exports.set = function set(options) {
2017-01-14 19:21:46 -08:00
this.pool.set({
enabled: options.useWorkers,
size: options.maxWorkers || null,
timeout: options.workerTimeout || null
});
};
2016-10-12 22:28:29 -07:00
exports.set({
useWorkers: +process.env.BCOIN_USE_WORKERS !== 0,
2017-01-14 19:21:46 -08:00
maxWorkers: +process.env.BCOIN_MAX_WORKERS,
workerTimeout: +process.env.BCOIN_WORKER_TIMEOUT
});
2016-05-15 18:07:06 -07:00
/*
* Expose
*/
2016-10-12 22:28:29 -07:00
exports.WorkerPool = WorkerPool;
2016-05-15 18:07:06 -07:00
exports.Worker = Worker;