refactor(@embark/blockchain-process): introduce package for blockchain-process module

This commit is contained in:
Pascal Precht 2019-05-08 13:19:25 +02:00 committed by Iuri Matias
parent f9d7a3f41b
commit f868d1216d
23 changed files with 251 additions and 139 deletions

View File

@ -0,0 +1,4 @@
engine-strict = true
package-lock = false
save-exact = true
scripts-prepend-node-path = true

View File

@ -0,0 +1,6 @@
# `embark-blockchain-process`
> Blockchain Process abstraction for Embark
Visit [embark.status.im](https://embark.status.im/) to get started with
[Embark](https://github.com/embark-framework/embark).

View File

@ -0,0 +1,83 @@
{
"name": "embark-blockchain-process",
"version": "4.1.0-beta.0",
"author": "Iuri Matias <iuri.matias@gmail.com>",
"contributors": [],
"description": "Blockchain process abstraction for Embark",
"homepage": "https://github.com/embark-framework/embark/tree/master/packages/embark-blockchain-process#readme",
"bugs": "https://github.com/embark-framework/embark/issues",
"keywords": [
"blockchain",
"dapps",
"ethereum",
"ipfs",
"serverless",
"solc",
"solidity"
],
"files": [
"dist"
],
"license": "MIT",
"repository": {
"directory": "packages/embark-blockchain-process",
"type": "git",
"url": "https://github.com/embark-framework/embark.git"
},
"main": "./dist/index.js",
"scripts": {
"build": "cross-env BABEL_ENV=node babel src --extensions \".js\" --out-dir dist --root-mode upward --source-maps",
"ci": "npm run qa",
"clean": "npm run reset",
"lint": "npm-run-all lint:*",
"lint:js": "eslint src/",
"// lint:ts": "tslint -c tslint.json \"src/**/*.ts\"",
"package": "npm pack",
"// qa": "npm-run-all lint typecheck build package",
"qa": "npm-run-all lint build package",
"reset": "npx rimraf dist embark-*.tgz package",
"start": "npm run watch",
"// typecheck": "tsc",
"watch": "run-p watch:*",
"watch:build": "npm run build -- --verbose --watch",
"// watch:typecheck": "npm run typecheck -- --preserveWatchOutput --watch"
},
"eslintConfig": {
"extends": "../../.eslintrc.json"
},
"dependencies": {
"@babel/runtime-corejs2": "7.3.1",
"async": "2.6.1",
"embark-core": "^4.1.0-beta.0",
"embark-i18n": "^4.1.0-beta.0",
"embark-logger": "^4.1.0-beta.0",
"embark-utils": "^4.1.0-beta.0",
"ethereumjs-tx": "1.3.7",
"ethereumjs-util": "6.0.0",
"http-proxy": "1.17.0",
"netcat": "1.3.5",
"node-http-proxy-json": "0.1.6",
"pkg-up": "2.0.0",
"pump": "3.0.0",
"shelljs": "0.5.3",
"semver": "5.6.0",
"simples": "0.8.8",
"stream-json": "1.1.3",
"ws": "6.1.2"
},
"devDependencies": {
"@babel/cli": "7.2.3",
"@babel/core": "7.2.2",
"cross-env": "5.2.0",
"eslint": "5.7.0",
"npm-run-all": "4.1.5",
"rimraf": "2.6.3",
"tslint": "5.16.0",
"typescript": "3.4.5"
},
"engines": {
"node": ">=8.12.0",
"npm": ">=6.4.1",
"yarn": ">=1.12.3"
}
}

View File

@ -2,11 +2,10 @@ import { __ } from 'embark-i18n';
const async = require('async');
const {spawn, exec} = require('child_process');
const path = require('path');
const fs = require('../../core/fs.js');
const constants = require('embark-core/constants');
const GethClient = require('./gethClient.js');
const ParityClient = require('./parityClient.js');
const Proxy = require('./proxy');
import { Proxy } from './proxy';
import { IPC } from 'embark-core';
import { compact, defaultHost, dockerHostSwap, AccountParser} from 'embark-utils';
@ -16,7 +15,7 @@ const Logger = require('embark-logger');
const IPC_CONNECT_INTERVAL = 2000;
/*eslint complexity: ["error", 50]*/
var Blockchain = function(userConfig, clientClass) {
var Blockchain = function(userConfig, clientClass, fs) {
this.userConfig = userConfig;
this.env = userConfig.env || 'development';
this.isDev = userConfig.isDev;
@ -27,6 +26,7 @@ var Blockchain = function(userConfig, clientClass) {
this.proxyIpc = null;
this.isStandalone = userConfig.isStandalone;
this.certOptions = userConfig.certOptions;
this.fs = fs;
let defaultWsApi = clientClass.DEFAULTS.WS_API;
@ -81,9 +81,9 @@ var Blockchain = function(userConfig, clientClass) {
if (this.env === 'development') {
this.isDev = true;
} else {
this.config.genesisBlock = fs.embarkPath("templates/boilerplate/config/privatenet/genesis.json");
this.config.genesisBlock = this.fs.embarkPath("templates/boilerplate/config/privatenet/genesis.json");
}
this.config.datadir = fs.dappPath(".embark/development/datadir");
this.config.datadir = this.fs.dappPath(".embark/development/datadir");
this.config.wsOrigins = this.config.wsOrigins || "http://localhost:8000";
this.config.rpcCorsDomain = this.config.rpcCorsDomain || "http://localhost:8000";
this.config.targetGasLimit = 8000000;
@ -104,7 +104,7 @@ var Blockchain = function(userConfig, clientClass) {
process.exit(1);
}
this.initProxy();
this.client = new clientClass({config: this.config, env: this.env, isDev: this.isDev});
this.client = new clientClass({config: this.config, env: this.env, isDev: this.isDev, fs: this.fs});
this.initStandaloneProcess();
};
@ -131,7 +131,7 @@ Blockchain.prototype.initStandaloneProcess = function () {
}
});
this.ipc = new IPC({ipcRole: 'client', fs});
this.ipc = new IPC({ipcRole: 'client', fs: this.fs});
// Wait for an IPC server to start (ie `embark run`) by polling `.connect()`.
// Do not kill this interval as the IPC server may restart (ie restart
@ -161,9 +161,9 @@ Blockchain.prototype.initProxy = function () {
};
Blockchain.prototype.setupProxy = async function () {
if (!this.proxyIpc) this.proxyIpc = new IPC({ipcRole: 'client', fs});
if (!this.proxyIpc) this.proxyIpc = new IPC({ipcRole: 'client', fs: this.fs});
const addresses = AccountParser.parseAccountsConfig(this.userConfig.accounts, false, fs.dappPath(), this.logger);
const addresses = AccountParser.parseAccountsConfig(this.userConfig.accounts, false, this.fs.dappPath(), this.logger);
let wsProxy;
if (this.config.wsRPC) {
@ -304,7 +304,7 @@ Blockchain.prototype.kill = function () {
};
Blockchain.prototype.checkPathLength = function () {
let dappPath = fs.dappPath('');
let dappPath = this.fs.dappPath('');
if (dappPath.length > 66) {
// this.logger.error is captured and sent to the console output regardless of silent setting
this.logger.error("===============================================================================".yellow);
@ -403,7 +403,7 @@ Blockchain.prototype.initChainAndGetAddress = function (callback) {
async.waterfall([
function makeDir(next) {
fs.mkdirp(self.datadir, (err, _result) => {
this.fs.mkdirp(self.datadir, (err, _result) => {
next(err);
});
},
@ -450,14 +450,14 @@ Blockchain.prototype.initChainAndGetAddress = function (callback) {
});
};
var BlockchainClient = function(userConfig, clientName, env, certOptions, onReadyCallback, onExitCallback, logger, _events, isStandalone) {
if ((userConfig === {} || JSON.stringify(userConfig) === '{"enabled":true}') && env !== 'development') {
logger.info("===> " + __("warning: running default config on a non-development environment"));
export function BlockchainClient(userConfig, options) {
if ((userConfig === {} || JSON.stringify(userConfig) === '{"enabled":true}') && options.env !== 'development') {
options.logger.info("===> " + __("warning: running default config on a non-development environment"));
}
// if client is not set in preferences, default is geth
if (!userConfig.ethereumClientName) userConfig.ethereumClientName = constants.blockchain.clients.geth;
// if clientName is set, it overrides preferences
if (clientName) userConfig.ethereumClientName = clientName;
if (options.clientName) userConfig.ethereumClientName = options.clientName;
// Choose correct client instance based on clientName
let clientClass;
switch (userConfig.ethereumClientName) {
@ -473,13 +473,11 @@ var BlockchainClient = function(userConfig, clientName, env, certOptions, onRead
process.exit(1);
}
userConfig.isDev = (userConfig.isDev || userConfig.default);
userConfig.env = env;
userConfig.onReadyCallback = onReadyCallback;
userConfig.onExitCallback = onExitCallback;
userConfig.logger = logger;
userConfig.certOptions = certOptions;
userConfig.isStandalone = isStandalone;
return new Blockchain(userConfig, clientClass);
};
module.exports = BlockchainClient;
userConfig.env = options.env;
userConfig.onReadyCallback = options.onReadyCallback;
userConfig.onExitCallback = options.onExitCallback;
userConfig.logger = options.logger;
userConfig.certOptions = options.certOptions;
userConfig.isStandalone = options.isStandalone;
return new Blockchain(userConfig, clientClass, options.fs);
}

View File

@ -1,7 +1,7 @@
import * as i18n from 'embark-i18n';
import { ProcessWrapper } from 'embark-core';
const BlockchainClient = require('./blockchain');
const constants = require('embark-core/constants');
import { BlockchainClient } from './blockchain';
let blockchainProcess;
@ -13,18 +13,22 @@ class BlockchainProcess extends ProcessWrapper {
this.env = options.env;
this.isDev = options.isDev;
this.certOptions = options.certOptions;
this.embark = options.embark;
i18n.setOrDetectLocale(options.locale);
this.blockchainConfig.silent = true;
this.blockchain = BlockchainClient(
this.blockchainConfig,
this.client,
this.env,
this.certOptions,
this.blockchainReady.bind(this),
this.blockchainExit.bind(this),
console
{
clientName: this.client,
env: this.env,
certOptions: this.certOptions,
onReadyCallback: this.blockchainReady.bind(this),
onExitCallback: this.blockchainExit.bind(this),
logger: console,
fs: this.embark.fs
}
);
this.blockchain.run();

View File

@ -1,9 +1,9 @@
import { __ } from 'embark-i18n';
import { ProcessLauncher } from 'embark-core';
import {joinPath} from 'embark-utils';
import { joinPath } from 'embark-utils';
const constants = require('embark-core/constants');
class BlockchainProcessLauncher {
export class BlockchainProcessLauncher {
constructor (options) {
this.events = options.events;
@ -79,5 +79,3 @@ class BlockchainProcessLauncher {
}
}
module.exports = BlockchainProcessLauncher;

View File

@ -1,7 +1,6 @@
import { __ } from 'embark-i18n';
const async = require('async');
const {exec, spawn} = require('child_process');
const fs = require('../../core/fs');
const path = require('path');
const GethMiner = require('./miner');
const semver = require('semver');
@ -35,6 +34,7 @@ class GethClient {
this.versSupported = DEFAULTS.VERSIONS_SUPPORTED;
this.httpReady = false;
this.wsReady = !this.config.wsRPC;
this.fs = options.fs;
}
isReady(data) {
@ -79,7 +79,7 @@ class GethClient {
}
if (config.account && config.account.password) {
const resolvedPath = path.resolve(fs.dappPath(), config.account.password);
const resolvedPath = path.resolve(this.fs.dappPath(), config.account.password);
cmd.push(`--password=${resolvedPath}`);
}
@ -87,13 +87,13 @@ class GethClient {
cmd.push("--verbosity=" + config.verbosity);
}
cmd.push(`--ipcpath=${fs.ipcPath('geth.ipc', true)}`);
cmd.push(`--ipcpath=${this.fs.ipcPath('geth.ipc', true)}`);
return cmd;
}
getMiner() {
return new GethMiner({datadir: this.config.datadir});
return new GethMiner({datadir: this.config.datadir, fs: this.fs});
}
getBinaryPath() {
@ -392,3 +392,4 @@ class GethClient {
}
module.exports = GethClient;

View File

@ -1,11 +1,15 @@
import { __ } from 'embark-i18n';
const async = require('async');
const utils = require('../../utils/utils.js');
const {normalizeInput, buildUrlFromConfig} = require('embark-utils');
const { normalizeInput, buildUrlFromConfig } = require('embark-utils');
const constants = require('embark-core/constants');
const BlockchainProcessLauncher = require('./blockchainProcessLauncher');
import { BlockchainProcessLauncher } from './blockchainProcessLauncher';
import { pingEndpoint } from './utils';
class BlockchainModule {
export { BlockchainClient } from './blockchain';
export { Simulator } from './simulator';
export { Proxy } from './proxy';
export default class BlockchainModule {
constructor(embark, options) {
this.logger = embark.logger;
@ -84,12 +88,12 @@ class BlockchainModule {
next();
});
},
function pingEndpoint(next) {
function _pingEndpoint(next) {
if (!self.contractsConfig || !self.contractsConfig.deployment || !self.contractsConfig.deployment.host) {
return next();
}
const {host, port, type, protocol} = self.contractsConfig.deployment;
utils.pingEndpoint(host, port, type, protocol, self.blockchainConfig.wsOrigins.split(',')[0], next);
pingEndpoint(host, port, type, protocol, self.blockchainConfig.wsOrigins.split(',')[0], next);
}
], function(err) {
if (err === true || err === undefined) {
@ -147,7 +151,5 @@ class BlockchainModule {
cb();
});
}
}
module.exports = BlockchainModule;

View File

@ -1,5 +1,4 @@
const async = require('async');
const fs = require('../../core/fs');
const NetcatClient = require('netcat/client');
//Constants
@ -20,6 +19,7 @@ class GethMiner {
// In the meantime, just set an empty config object
this.config = {};
this.datadir = options.datadir;
this.fs = options.fs;
self.interval = null;
self.callback = null;
self.started = null;
@ -44,7 +44,7 @@ class GethMiner {
}
}
const ipcPath = fs.ipcPath('geth.ipc', true);
const ipcPath = this.fs.ipcPath('geth.ipc', true);
this.client = new NetcatClient();
this.client.unixSocket(ipcPath)

View File

@ -1,6 +1,5 @@
import { __ } from 'embark-i18n';
const async = require('async');
const fs = require('../../core/fs.js');
const path = require('path');
const os = require('os');
const semver = require('semver');
@ -53,6 +52,7 @@ class ParityClient {
this.prettyName = "Parity-Ethereum (https://github.com/paritytech/parity-ethereum)";
this.bin = this.config.ethereumClientBin || DEFAULTS.BIN;
this.versSupported = DEFAULTS.VERSIONS_SUPPORTED;
this.fs = options.fs;
}
isReady(data) {
@ -262,7 +262,7 @@ class ParityClient {
const keysDataDir = datadir + '/keys/DevelopmentChain';
async.waterfall([
function makeDir(next) {
fs.mkdirp(keysDataDir, (err, _result) => {
this.fs.mkdirp(keysDataDir, (err, _result) => {
next(err);
});
},
@ -270,7 +270,7 @@ class ParityClient {
self.createDevAccount(keysDataDir, next);
},
function mkDevPasswordDir(next) {
fs.mkdirp(path.dirname(self.config.account.devPassword), (err, _result) => {
this.fs.mkdirp(path.dirname(self.config.account.devPassword), (err, _result) => {
next(err);
});
},
@ -278,12 +278,12 @@ class ParityClient {
if (!self.config.account.password) {
return next(null, os.EOL + 'dev_password');
}
fs.readFile(fs.dappPath(self.config.account.password), {encoding: 'utf8'}, (err, content) => {
this.fs.readFile(this.fs.dappPath(self.config.account.password), {encoding: 'utf8'}, (err, content) => {
next(err, os.EOL + content);
});
},
function updatePasswordFile(passwordList, next) {
fs.writeFile(self.config.account.devPassword, passwordList, next);
this.fs.writeFile(self.config.account.devPassword, passwordList, next);
}
], (err) => {
callback(err);
@ -292,7 +292,7 @@ class ParityClient {
createDevAccount(keysDataDir, cb) {
const devAccountWallet = keysDataDir + '/dev.wallet';
fs.writeFile(devAccountWallet, JSON.stringify(DEFAULTS.DEV_WALLET), function(err) {
this.fs.writeFile(devAccountWallet, JSON.stringify(DEFAULTS.DEV_WALLET), function(err) {
if (err) {
return cb(err);
}

View File

@ -3,19 +3,19 @@
require('./httpProxyOverride');
const Asm = require('stream-json/Assembler');
import { __ } from 'embark-i18n';
import {canonicalHost, timer} from 'embark-utils';
import { canonicalHost, timer } from 'embark-utils';
const constants = require('embark-core/constants');
const {Duplex} = require('stream');
const http = require('http');
const httpProxy = require('http-proxy');
const {parser: jsonParser} = require('stream-json');
const pump = require('pump');
const utils = require('../../utils/utils');
const WsParser = require('simples/lib/parsers/ws');
const WsWrapper = require('simples/lib/ws/wrapper');
const modifyResponse = require('node-http-proxy-json');
const Transaction = require('ethereumjs-tx');
const ethUtil = require('ethereumjs-util');
import { pingEndpoint } from './utils';
const METHODS_TO_MODIFY = {accounts: 'eth_accounts'};
const REQUEST_TIMEOUT = 5000;
@ -53,7 +53,7 @@ const parseJsonMaybe = (string) => {
return object;
};
class Proxy {
export class Proxy {
constructor(ipc) {
this.ipc = ipc;
this.commList = {};
@ -209,7 +209,7 @@ class Proxy {
const start = Date.now();
await (function waitOnTarget() {
return new Promise(resolve => {
utils.pingEndpoint(
pingEndpoint(
canonicalHost(host),
port,
ws ? 'ws': false,
@ -317,5 +317,3 @@ class Proxy {
});
}
}
module.exports = Proxy;

View File

@ -1,18 +1,18 @@
const path = require('path');
const pkgUp = require('pkg-up');
let shelljs = require('shelljs');
let Proxy = require('./proxy');
import { Proxy } from './proxy';
import { IPC } from 'embark-core';
const constants = require('embark-core/constants');
import {defaultHost, dockerHostSwap} from 'embark-utils';
const fs = require('../../core/fs.js');
import { defaultHost, dockerHostSwap } from 'embark-utils';
const { AccountParser } = require('embark-utils');
class Simulator {
export class Simulator {
constructor(options) {
this.blockchainConfig = options.blockchainConfig;
this.contractsConfig = options.contractsConfig;
this.logger = options.logger;
this.fs = options.fs;
}
/*eslint complexity: ["error", 25]*/
@ -44,7 +44,7 @@ class Simulator {
let simulatorAccounts = this.blockchainConfig.simulatorAccounts || options.simulatorAccounts;
if (simulatorAccounts && simulatorAccounts.length > 0) {
let web3 = new (require('web3'))();
let parsedAccounts = AccountParser.parseAccountsConfig(simulatorAccounts, web3, fs.dappPath(), this.logger);
let parsedAccounts = AccountParser.parseAccountsConfig(simulatorAccounts, web3, this.fs.dappPath(), this.logger);
parsedAccounts.forEach((account) => {
let cmd = '--account="' + account.privateKey + ','+account.hexBalance + '"';
cmds.push(cmd);
@ -68,7 +68,7 @@ class Simulator {
}
runCommand(cmds, useProxy, host, port) {
const ganache_main = require.resolve('ganache-cli', {paths: [fs.embarkPath('node_modules')]});
const ganache_main = require.resolve('ganache-cli', {paths: [this.fs.embarkPath('node_modules')]});
const ganache_json = pkgUp.sync(path.dirname(ganache_main));
const ganache_root = path.dirname(ganache_json);
const ganache_bin = require(ganache_json).bin;
@ -86,7 +86,7 @@ class Simulator {
shelljs.exec(`node ${program} ${cmds.join(' ')}`, {async : true});
if(useProxy){
let ipcObject = new IPC({ipcRole: 'client', fs});
let ipcObject = new IPC({ipcRole: 'client', fs: this.fs});
if (this.blockchainConfig.wsRPC) {
return new Proxy(ipcObject).serve(host, port, true, this.blockchainConfig.wsOrigins, []);
}
@ -95,5 +95,3 @@ class Simulator {
}
}
}
module.exports = Simulator;

View File

@ -0,0 +1,58 @@
export function pingEndpoint(host, port, type, protocol, origin, callback) {
// remove any extra information from a host string, e.g. port, path, query
const _host = require("url").parse(
// url.parse() expects a protocol segment else it won't parse as desired
host.slice(0, 4) === "http" ? host : `${protocol}://${host}`
).hostname;
let closed = false;
const close = (req, closeMethod) => {
if (!closed) {
closed = true;
req[closeMethod]();
}
};
const handleEvent = (req, closeMethod, ...args) => {
close(req, closeMethod);
setImmediate(() => { callback(...args); });
};
const handleError = (req, closeMethod) => {
req.on("error", (err) => {
if (err.code !== "ECONNREFUSED") {
console.error(
`Ping: Network error` +
(err.message ? ` '${err.message}'` : "") +
(err.code ? ` (code: ${err.code})` : "")
);
}
// when closed additional error events will not callback
if (!closed) { handleEvent(req, closeMethod, err); }
});
};
const handleSuccess = (req, closeMethod, event) => {
req.once(event, () => {
handleEvent(req, closeMethod);
});
};
const handleRequest = (req, closeMethod, event) => {
handleError(req, closeMethod);
handleSuccess(req, closeMethod, event);
};
if (type === "ws") {
const url = `${protocol === "https" ? "wss" : "ws"}://${_host}:${port}/`;
const req = new (require("ws"))(url, origin ? {origin} : {});
handleRequest(req, "close", "open");
} else {
const headers = origin ? {Origin: origin} : {};
const req = (protocol === "https" ? require("https") : require("http")).get(
{headers, host: _host, port}
);
handleRequest(req, "abort", "response");
}
}

View File

@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.json",
"include": ["src/**/*"]
}

View File

@ -0,0 +1,3 @@
{
"extends": "../../tslint.json"
}

View File

@ -92,6 +92,7 @@
"deep-equal": "1.0.1",
"ejs": "2.6.1",
"embark-authenticator": "^4.1.0-beta.0",
"embark-blockchain-process": "^4.1.0-beta.0",
"embark-api": "^4.1.0-beta.0",
"embark-blockchain-listener": "^4.1.0-beta.0",
"embark-code-generator": "^4.1.0-beta.0",

View File

@ -1,3 +1,4 @@
import { BlockchainClient, Simulator } from 'embark-blockchain-process';
import { __ } from 'embark-i18n';
let async = require('async');
const constants = require('embark-core/constants');
@ -34,17 +35,24 @@ class EmbarkController {
blockchain(env, client) {
this.context = [constants.contexts.blockchain];
return require('../lib/modules/blockchain_process/blockchain.js')(this.config.blockchainConfig, client, env,
this.config.webServerConfig.certOptions, null, null, this.logger, this.events, true).run();
return BlockchainClient(this.config.blockchainConfig, {
clientName: client,
env,
certOptions: this.config.webServerConfig.certOptions,
logger: this.logger,
events: this.events,
isStandalone: true,
fs
}).run();
}
simulator(options) {
this.context = options.context || [constants.contexts.simulator, constants.contexts.blockchain];
let Simulator = require('../lib/modules/blockchain_process/simulator.js');
let simulator = new Simulator({
blockchainConfig: this.config.blockchainConfig,
contractsConfig: this.config.contractsConfig,
logger: this.logger
logger: this.logger,
fs
});
simulator.run(options);
}

View File

@ -298,7 +298,7 @@ class Engine {
}
web3Service(options) {
this.registerModule('blockchain_process', {
this.registerModulePackage('embark-blockchain-process', {
client: this.client,
locale: this.locale,
isDev: this.isDev,

View File

@ -108,6 +108,11 @@ Plugin.prototype.loadPlugin = function() {
};
Plugin.prototype.loadInternalPlugin = function() {
if (utils.isEs6Module(this.pluginModule)) {
if (this.pluginModule.default) {
this.pluginModule = this.pluginModule.default;
}
}
new this.pluginModule(this, this.pluginConfig); /*eslint no-new: "off"*/
};

View File

@ -68,64 +68,6 @@ function getJson(url, cb) {
httpGetJson(url, cb);
}
function pingEndpoint(host, port, type, protocol, origin, callback) {
// remove any extra information from a host string, e.g. port, path, query
const _host = require('url').parse(
// url.parse() expects a protocol segment else it won't parse as desired
host.slice(0, 4) === 'http' ? host : `${protocol}://${host}`
).hostname;
let closed = false;
const close = (req, closeMethod) => {
if (!closed) {
closed = true;
req[closeMethod]();
}
};
const handleEvent = (req, closeMethod, ...args) => {
close(req, closeMethod);
setImmediate(() => { callback(...args); });
};
const handleError = (req, closeMethod) => {
req.on('error', (err) => {
if (err.code !== 'ECONNREFUSED') {
console.error(
`Ping: Network error` +
(err.message ? ` '${err.message}'` : '') +
(err.code ? ` (code: ${err.code})` : '')
);
}
// when closed additional error events will not callback
if (!closed) { handleEvent(req, closeMethod, err); }
});
};
const handleSuccess = (req, closeMethod, event) => {
req.once(event, () => {
handleEvent(req, closeMethod);
});
};
const handleRequest = (req, closeMethod, event) => {
handleError(req, closeMethod);
handleSuccess(req, closeMethod, event);
};
if (type === 'ws') {
const url = `${protocol === 'https' ? 'wss' : 'ws'}://${_host}:${port}/`;
const req = new (require('ws'))(url, origin ? {origin} : {});
handleRequest(req, 'close', 'open');
} else {
const headers = origin ? {Origin: origin} : {};
const req = (protocol === 'https' ? require('https') : require('http')).get(
{headers, host: _host, port}
);
handleRequest(req, 'abort', 'response');
}
}
function cd(folder) {
const shelljs = require('shelljs');
shelljs.cd(folder);
@ -385,7 +327,6 @@ module.exports = {
httpsGetJson,
getJson,
isValidDomain,
pingEndpoint,
cd,
sed,
downloadFile,

View File

@ -1,5 +1,5 @@
/*globals describe, it*/
const Blockchain = require('../lib/modules/blockchain_process/blockchain.js');
import { BlockchainClient } from 'embark-blockchain-process';
const constants = require('embark-core/constants');
import {defaultHost} from 'embark-utils';
const path = require('path');
@ -13,7 +13,7 @@ describe('embark.Blockchain', function() {
describe('with empty config', function() {
it('should have a default config', function(done) {
const blockchain = new Blockchain({});
const blockchain = new BlockchainClient({}, { fs });
const expectedConfig = {
networkType: 'custom',
genesisBlock: false,
@ -93,7 +93,7 @@ describe('embark.Blockchain', function() {
}
]
};
let blockchain = new Blockchain(config);
let blockchain = new BlockchainClient(config, { fs });
let expectedConfig = {
networkType: 'livenet',

View File

@ -5,7 +5,7 @@ const {
const sinon = require('sinon');
import { IPC } from 'embark-core';
let fs = require('../lib/core/fs');
let Proxy = require('../lib/modules/blockchain_process/proxy');
const { Proxy } = require('embark-blockchain-process');
const constants = require('embark-core/constants');
describe('embark.Proxy', function () {