ee-core 1.5.2-beta.2 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/config/config.default.js +8 -1
  2. package/core/lib/ee.js +1 -1
  3. package/core/lib/loader/ee_loader.js +7 -3
  4. package/core/lib/loader/mixin/controller.js +3 -2
  5. package/core/lib/utils/function.js +30 -0
  6. package/index.js +2 -2
  7. package/lib/appLoader.js +0 -5
  8. package/lib/application.js +7 -6
  9. package/lib/baseApp.js +9 -26
  10. package/lib/eeApp.js +18 -52
  11. package/{lib/constant.js → module/const/index.js} +3 -0
  12. package/{lib/httpclient.js → module/httpclient/index.js} +45 -11
  13. package/module/jobs/child/forkProcess.js +99 -0
  14. package/module/jobs/child/index.js +33 -0
  15. package/module/jobs/index.js +55 -0
  16. package/module/jobs/renderer/index.js +140 -0
  17. package/module/jobs/renderer/loadView.js +40 -0
  18. package/module/loader/index.js +78 -0
  19. package/module/log/index.js +53 -0
  20. package/module/log/logger.js +61 -0
  21. package/module/message/index.js +13 -0
  22. package/module/message/ipcMain.js +160 -0
  23. package/module/message/ipcRender.js +0 -0
  24. package/{lib → module}/socket/httpServer.js +0 -0
  25. package/{lib → module}/socket/io.js +0 -0
  26. package/{lib → module}/socket/ipcServer.js +6 -8
  27. package/{lib → module}/socket/socketClient.js +4 -3
  28. package/{lib → module}/socket/socketServer.js +4 -3
  29. package/module/socket/start.js +22 -0
  30. package/{lib → module}/storage/index.js +13 -12
  31. package/module/storage/jsondb/adapters/Base.js +14 -0
  32. package/module/storage/jsondb/adapters/FileSync.js +32 -0
  33. package/{lib/storage/lowdb → module/storage/jsondb}/main.js +6 -10
  34. package/{lib/storage/lowdbStorage.js → module/storage/jsondbStorage.js} +13 -14
  35. package/{lib → module}/storage/sqliteStorage.js +7 -11
  36. package/module/utils/copyto.js +161 -0
  37. package/module/utils/helper.js +117 -0
  38. package/module/utils/index.js +120 -0
  39. package/module/utils/json.js +72 -0
  40. package/module/utils/ps.js +175 -0
  41. package/{utils → module/utils}/wrap.js +0 -2
  42. package/package.json +3 -7
  43. package/tools/encrypt.js +2 -2
  44. package/utils/index.js +17 -135
  45. package/lib/logger.js +0 -47
  46. package/lib/socket/start.js +0 -22
  47. package/lib/storage/lowdb/adapters/Base.js +0 -15
  48. package/lib/storage/lowdb/adapters/FileAsync.js +0 -41
  49. package/lib/storage/lowdb/adapters/FileSync.js +0 -39
  50. package/lib/storage/lowdb/adapters/LocalStorage.js +0 -20
  51. package/lib/storage/lowdb/adapters/Memory.js +0 -8
  52. package/lib/storage/lowdb/adapters/_stringify.js +0 -4
  53. package/lib/storage/lowdb/common.js +0 -33
  54. package/lib/storage/lowdb/fp.js +0 -23
  55. package/lib/storage/lowdb/isPromise.js +0 -6
  56. package/lib/storage/lowdb/nano.js +0 -5
  57. package/utils/common.js +0 -91
@@ -134,6 +134,7 @@ module.exports = appInfo => {
134
134
  * @property {Boolean} enablePerformanceTimer - using performance.now() timer instead of Date.now() for more more precise milliseconds, defaults to false. e.g.: logger will set 1.456ms instead of 1ms.
135
135
  */
136
136
  config.logger = {
137
+ type: 'application',
137
138
  dir: path.join(appInfo.root, 'logs'),
138
139
  encoding: 'utf8',
139
140
  env: appInfo.env,
@@ -151,6 +152,13 @@ module.exports = appInfo => {
151
152
  enablePerformanceTimer: false,
152
153
  };
153
154
 
155
+ /**
156
+ * customLogger options
157
+ * @member Config#customLogger
158
+ *
159
+ */
160
+ config.customLogger = {}
161
+
154
162
  /**
155
163
  * The option for httpclient
156
164
  * @member Config#httpclient
@@ -173,7 +181,6 @@ module.exports = appInfo => {
173
181
  enableDNSCache: false,
174
182
  dnsCacheLookupInterval: 10000,
175
183
  dnsCacheMaxLength: 1000,
176
-
177
184
  request: {
178
185
  timeout: 5000,
179
186
  },
package/core/lib/ee.js CHANGED
@@ -33,7 +33,7 @@ class EeCore extends KoaApplication {
33
33
 
34
34
  this.timing = new Timing();
35
35
 
36
- this.console = new EggConsoleLogger();
36
+ this.console = new EggConsoleLogger({level: 'INFO'});
37
37
 
38
38
  /**
39
39
  * @member {Object} EeCore#options
@@ -7,9 +7,9 @@ const is = require('is-type-of');
7
7
  const debug = require('debug')('ee-core:EeLoader');
8
8
  const FileLoader = require('./file_loader');
9
9
  const ContextLoader = require('./context_loader');
10
- const utility = require('utility');
11
10
  const utils = require('../utils');
12
11
  const Timing = require('../utils/timing');
12
+ const Ps = require('../../../module/utils/ps');
13
13
 
14
14
  const REQUIRE_COUNT = Symbol('EeLoader#requireCount');
15
15
 
@@ -199,7 +199,7 @@ class EeLoader {
199
199
  * The directory whether is homeDir or appUserData depend on env.
200
200
  * @member {String} AppInfo#root
201
201
  */
202
- root: env === 'local' || env === 'unittest' ? this.getHomedir() : this.options.appUserData,
202
+ root: Ps.getRootDir(),
203
203
 
204
204
  /**
205
205
  * electron application data dir
@@ -433,7 +433,11 @@ class EeLoader {
433
433
 
434
434
  getPkg() {
435
435
  const filePath = path.join(this.options.homeDir, 'package.json');
436
- const json = utility.readJSONSync(filePath);
436
+ if (!fs.existsSync(filePath)) {
437
+ throw new Error(filePath + ' is not found');
438
+ }
439
+ const json = JSON.parse(fs.readFileSync(filePath));
440
+
437
441
  return json;
438
442
  }
439
443
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  const path = require('path');
4
4
  const is = require('is-type-of');
5
- const utility = require('utility');
5
+ const utilsFn = require('../../utils/function');
6
6
  const utils = require('../../utils');
7
7
  const FULLPATH = require('../file_loader').FULLPATH;
8
8
 
@@ -97,7 +97,7 @@ function wrapObject(obj, path, prefix) {
97
97
  const ret = {};
98
98
  for (const key of keys) {
99
99
  if (is.function(obj[key])) {
100
- const names = utility.getParamNames(obj[key]);
100
+ const names = utilsFn.getParamNames(obj[key]);
101
101
  if (names[0] === 'next') {
102
102
  throw new Error(`controller \`${prefix || ''}${key}\` should not use next as argument from file ${path}`);
103
103
  }
@@ -122,3 +122,4 @@ function wrapObject(obj, path, prefix) {
122
122
  return objectControllerMiddleware;
123
123
  }
124
124
  }
125
+
@@ -0,0 +1,30 @@
1
+ const assert = require('assert');
2
+
3
+ /**
4
+ * A empty function.
5
+ *
6
+ * @return {Function}
7
+ * @public
8
+ */
9
+ exports.noop = function noop() {};
10
+
11
+ /**
12
+ * Get a function parameter's names.
13
+ *
14
+ * @param {Function} func
15
+ * @param {Boolean} [useCache], default is true
16
+ * @return {Array} names
17
+ */
18
+ exports.getParamNames = function getParamNames(func, cache) {
19
+ var type = typeof func;
20
+ assert(type === 'function', 'The "func" must be a function. Received type "' + type + '"');
21
+
22
+ cache = cache !== false;
23
+ if (cache && func.__cache_names) {
24
+ return func.__cache_names;
25
+ }
26
+ var str = func.toString();
27
+ var names = str.slice(str.indexOf('(') + 1, str.indexOf(')')).match(/([^\s,]+)/g) || [];
28
+ func.__cache_names = names;
29
+ return names;
30
+ };
package/index.js CHANGED
@@ -26,7 +26,7 @@ const Service = require('./core/lib/utils/base_context_class');
26
26
  * @member {Storage}
27
27
  * @since 1.0.0
28
28
  */
29
- const Storage = require('./lib/storage/index');
29
+ const Storage = require('./module/storage/index');
30
30
 
31
31
  /**
32
32
  * @member {Utils}
@@ -38,7 +38,7 @@ const Utils = require('./utils/index');
38
38
  * @member {Socket}
39
39
  * @since 1.0.0
40
40
  */
41
- const Socket = require('./lib/socket/io');
41
+ const Socket = require('./module/socket/io');
42
42
 
43
43
  module.exports = {
44
44
  Appliaction,
package/lib/appLoader.js CHANGED
@@ -1,5 +1,3 @@
1
- 'use strict';
2
-
3
1
  const EeLoader = require('../core/index').EeLoader;
4
2
 
5
3
  /**
@@ -43,9 +41,6 @@ class AppLoader extends EeLoader {
43
41
  * @since 1.0.0
44
42
  */
45
43
  loadElectron() {
46
-
47
- // 预加载功能模块
48
- //this.loadPreload();
49
44
 
50
45
  }
51
46
  }
@@ -1,8 +1,8 @@
1
1
  const {app} = require('electron');
2
2
  const path = require('path');
3
- const EeApp = require('./eeApp');
4
3
  const debug = require('debug')('ee-core:Appliaction');
5
4
  const fs = require('fs');
5
+ const EeApp = require('./eeApp');
6
6
 
7
7
  class Appliaction extends EeApp {
8
8
  constructor() {
@@ -18,7 +18,6 @@ class Appliaction extends EeApp {
18
18
  userHome: app.getPath('home'),
19
19
  appData: app.getPath('appData'),
20
20
  appUserData: app.getPath('userData'),
21
- //logsDir: app.getPath('logs'),
22
21
  appVersion: app.getVersion(),
23
22
  isPackaged: app.isPackaged,
24
23
  execDir: app.getAppPath()
@@ -49,19 +48,21 @@ class Appliaction extends EeApp {
49
48
  }
50
49
 
51
50
  // normalize env
52
- env.NODE_ENV = 'production';
51
+ env.NODE_ENV = options.env;
53
52
  env.EE_HOME = options.homeDir;
53
+ env.EE_BASE_DIR = options.baseDir;
54
54
  env.EE_SERVER_ENV = options.env;
55
55
  env.EE_SERVER_SCOPE = options.serverScope;
56
56
  env.EE_USER_HOME = options.userHome;
57
57
  env.EE_APP_DATA = options.appData;
58
58
  env.EE_APP_USER_DATA = options.appUserData;
59
- env.EE_MAIN_PORT = null;
60
- env.EE_SOCKET_PORT = null;
61
- env.EE_HTTP_PORT = null;
62
59
  env.HOT_RELOAD = hotReload;
63
60
  env.EE_EXEC_DIR = options.execDir;
61
+ env.EE_IS_PACKAGED = options.isPackaged;
64
62
  env.EE_DATABASE_DIR = null;
63
+ env.EE_MAIN_PORT = null;
64
+ env.EE_SOCKET_PORT = null;
65
+ env.EE_HTTP_PORT = null;
65
66
  debug('options:%j', options)
66
67
 
67
68
  super(options);
package/lib/baseApp.js CHANGED
@@ -1,35 +1,30 @@
1
- 'use strict';
2
-
3
1
  const EeAppCore = require('../core/index').EeCore;
4
2
  const EE_PATH = Symbol.for('ee#eePath');
5
3
  const path = require('path');
6
4
  const EE_LOADER = Symbol.for('ee#loader');
7
5
  const AppLoader = require('./appLoader');
8
- const LOGGERS = Symbol('EeApplication#loggers');
9
- const ELoggers = require('./logger');
10
- const HttpClient = require('./httpclient');
6
+ const HttpClient = require('../module/httpclient');
11
7
  const HTTPCLIENT = Symbol('EeApplication#httpclient');
8
+ const LOGGERS = Symbol('EeApplication#loggers');
9
+ const Log = require('../module/log');
10
+ const Storage = require('../module/storage');
12
11
 
13
12
  class BaseApp extends EeAppCore {
14
13
  constructor (options = {}) {
15
14
 
16
15
  super(options);
17
-
18
- this.HttpClient = HttpClient;
19
16
 
20
17
  this.loader.loadConfig();
21
18
 
22
- // todo
23
- //this.setDatabaseDir();
24
-
25
19
  // 缓存配置
26
20
  this.getCoreDB().setItem('config', this.config);
27
21
 
28
22
  this.loader.load();
29
23
 
24
+ this.HttpClient = HttpClient;
25
+
30
26
  // TODO 这个不行,要么每次new对象,要么所有地方都用同一个实例,否则会出现数据无法刷新的情况
31
27
  //this.coreDB = this.getCoreDB();
32
-
33
28
  }
34
29
 
35
30
  get [EE_PATH]() {
@@ -47,7 +42,7 @@ class BaseApp extends EeAppCore {
47
42
  */
48
43
  get loggers() {
49
44
  if (!this[LOGGERS]) {
50
- this[LOGGERS] = ELoggers.getInstance(this.config);
45
+ this[LOGGERS] = Log.create(this.config);
51
46
  }
52
47
  return this[LOGGERS];
53
48
  }
@@ -85,7 +80,7 @@ class BaseApp extends EeAppCore {
85
80
  * @since 1.0.0
86
81
  */
87
82
  getCoreDB () {
88
- const db = require('./storage/index').JsonDB.connection('system');
83
+ const db = Storage.connection('system');
89
84
  return db;
90
85
  }
91
86
 
@@ -104,23 +99,11 @@ class BaseApp extends EeAppCore {
104
99
  */
105
100
  get httpclient() {
106
101
  if (!this[HTTPCLIENT]) {
107
- this[HTTPCLIENT] = new this.HttpClient(this);
102
+ this[HTTPCLIENT] = new this.HttpClient(this.config.httpclient);
108
103
  }
109
104
  return this[HTTPCLIENT];
110
105
  }
111
106
 
112
- /**
113
- * todo 设置db存储目录
114
- */
115
- setDatabaseDir (dirPath) {
116
- if (dirPath) {
117
- assert(typeof dirPath === 'string', ` ${dirPath} dirPath required, and must be a string`);
118
- process.env.EE_DATABASE_DIR = dirPath;
119
- } else {
120
- process.env.EE_DATABASE_DIR = this.config.database.dir;
121
- }
122
- }
123
-
124
107
  /**
125
108
  * core app have been loaded
126
109
  */
package/lib/eeApp.js CHANGED
@@ -2,13 +2,13 @@ const path = require('path');
2
2
  const fs = require('fs');
3
3
  const assert = require('assert');
4
4
  const getPort = require('get-port');
5
- const {app, BrowserWindow, BrowserView, Menu} = require('electron');
6
- const BaseApp = require('./baseApp');
5
+ const {app, BrowserWindow, Menu, protocol} = require('electron');
7
6
  const is = require('is-type-of');
8
7
  const Koa = require('koa');
9
8
  const koaServe = require('koa-static');
10
9
  const https = require('https');
11
- const utilsCommon = require('../utils/common');
10
+ const BaseApp = require('./baseApp');
11
+ const Log = require('../module/log');
12
12
 
13
13
  class EeApp extends BaseApp {
14
14
  constructor(options = {}) {
@@ -51,7 +51,7 @@ class EeApp extends BaseApp {
51
51
  * 启动通信模块
52
52
  */
53
53
  async startSocket () {
54
- const socket = require('./socket/start');
54
+ const socket = require('../module/socket/start');
55
55
  socket(this);
56
56
  }
57
57
 
@@ -80,7 +80,7 @@ class EeApp extends BaseApp {
80
80
 
81
81
  app.on('window-all-closed', () => {
82
82
  if (process.platform !== 'darwin') {
83
- self.coreLogger.info('[Appliaction] [initialize] window-all-closed quit');
83
+ Log.coreLogger.info('[Appliaction] [initialize] window-all-closed quit');
84
84
  self.appQuit();
85
85
  }
86
86
  })
@@ -100,6 +100,15 @@ class EeApp extends BaseApp {
100
100
  * 创建应用主窗口
101
101
  */
102
102
  async createWindow () {
103
+
104
+ // todo
105
+ const protocolName = 'eefile';
106
+ protocol.registerFileProtocol(protocolName, (request, callback) => {
107
+ const url = request.url.substring(protocolName.length + 3);
108
+ console.log('[ee-core:job] ----url: ', url);
109
+ callback({ path: path.normalize(decodeURIComponent(url)) })
110
+ });
111
+
103
112
  const winOptions = this.config.windowsOption;
104
113
  this.electron.mainWindow = new BrowserWindow(winOptions);
105
114
  let win = this.electron.mainWindow;
@@ -114,8 +123,6 @@ class EeApp extends BaseApp {
114
123
  // nothing
115
124
  }
116
125
 
117
- this.loadingView(winOptions);
118
-
119
126
  await this.windowReady();
120
127
 
121
128
  await this._loderAddons();
@@ -142,45 +149,6 @@ class EeApp extends BaseApp {
142
149
  }
143
150
  }
144
151
 
145
- /**
146
- * 加载已经实现的功能
147
- */
148
- async loadPreference () {
149
- const preferences = require('./preferences');
150
- return await preferences(this);
151
- }
152
-
153
- /**
154
- * 加载loading页面
155
- */
156
- loadingView (winOptions) {
157
- let currentV = process.versions.electron;
158
- if (utilsCommon.compareVersion(currentV, '12.2.3') == 1) {
159
- return;
160
- }
161
- if (!this.config.loadingPage) {
162
- return;
163
- }
164
- const self = this;
165
- const loadingBrowserView = new BrowserView();
166
- this.electron.mainWindow.setBrowserView(loadingBrowserView);
167
- loadingBrowserView.setBounds({
168
- x: 0,
169
- y: 0,
170
- width: winOptions.width,
171
- height: winOptions.height
172
- });
173
-
174
- // loading html
175
- const loadingHtml = path.join('file://', this.config.homeDir, 'public', 'html', 'loading.html');
176
- loadingBrowserView.webContents.loadURL(loadingHtml);
177
- this.logger.info('loadingHtml:', loadingHtml);
178
-
179
- this.electron.mainWindow.webContents.on('dom-ready', async (event) => {
180
- self.electron.mainWindow.removeBrowserView(loadingBrowserView);
181
- });
182
- }
183
-
184
152
  /**
185
153
  * 应用类型 (远程、html、单页应用)
186
154
  */
@@ -252,7 +220,7 @@ class EeApp extends BaseApp {
252
220
  };
253
221
  https.createServer(sslOpt, koaApp.callback()).listen(mainServer.port, (err) => {
254
222
  if (err) {
255
- self.coreLogger.info('[error] ', err);
223
+ Log.coreLogger.info('[error] ', err);
256
224
  return
257
225
  }
258
226
  self.loadMainUrl(mode, url);
@@ -269,8 +237,8 @@ class EeApp extends BaseApp {
269
237
  */
270
238
  loadMainUrl (type, url) {
271
239
  const mainServer = this.config.mainServer;
272
- this.logger.info('[ee-core:main] Env: %s, Type: %s', this.config.env, type);
273
- this.logger.info('[ee-core:main] App running at: %s', url);
240
+ Log.coreLogger.info('[ee-core:main] Env: %s, Type: %s', this.config.env, type);
241
+ Log.coreLogger.info('[ee-core:main] App running at: %s', url);
274
242
  this.electron.mainWindow.loadURL(url, mainServer.options);
275
243
  }
276
244
 
@@ -328,10 +296,8 @@ class EeApp extends BaseApp {
328
296
  * 捕获异常
329
297
  */
330
298
  async catchLog () {
331
- const self = this;
332
-
333
299
  process.on('uncaughtException', function(err) {
334
- self.logger.error(err);
300
+ Log.coreLogger.error(err);
335
301
  });
336
302
  }
337
303
 
@@ -6,5 +6,8 @@ module.exports = {
6
6
  channel: {
7
7
  partySoftware: 'c1',
8
8
  }
9
+ },
10
+ jobs: {
11
+ inspectStartIndex: 5858
9
12
  }
10
13
  };
@@ -1,10 +1,10 @@
1
- 'use strict';
2
-
3
1
  const Agent = require('agentkeepalive');
4
2
  const HttpsAgent = require('agentkeepalive').HttpsAgent;
5
3
  const urllib = require('urllib');
6
4
  const ms = require('humanize-ms');
7
5
  const { FrameworkBaseError } = require('egg-errors');
6
+ const Storage = require('../storage');
7
+ const Log = require('../log');
8
8
 
9
9
  class HttpClientError extends FrameworkBaseError {
10
10
  get module() {
@@ -13,18 +13,52 @@ class HttpClientError extends FrameworkBaseError {
13
13
  }
14
14
 
15
15
  class HttpClient extends urllib.HttpClient2 {
16
- constructor(app) {
17
- normalizeConfig(app);
18
- const config = app.config.httpclient;
16
+ constructor(options = {}) {
17
+
18
+ if (Object.keys(options).length == 0) {
19
+ const sysConfig = this._getCoreDB().getItem('config');
20
+ options = sysConfig.httpclient;
21
+ }
22
+
23
+ const config = Object.assign({
24
+ enableDNSCache: false,
25
+ dnsCacheLookupInterval: 10000,
26
+ dnsCacheMaxLength: 1000,
27
+ request: {
28
+ timeout: 5000,
29
+ },
30
+ httpAgent: {
31
+ keepAlive: true,
32
+ freeSocketTimeout: 4000,
33
+ maxSockets: Number.MAX_SAFE_INTEGER,
34
+ maxFreeSockets: 256,
35
+ },
36
+ httpsAgent: {
37
+ keepAlive: true,
38
+ freeSocketTimeout: 4000,
39
+ maxSockets: Number.MAX_SAFE_INTEGER,
40
+ maxFreeSockets: 256,
41
+ },
42
+ }, options);
43
+
44
+ normalizeConfig(config);
45
+
19
46
  super({
20
- app,
21
47
  defaultArgs: config.request,
22
48
  agent: new Agent(config.httpAgent),
23
49
  httpsAgent: new HttpsAgent(config.httpsAgent),
24
50
  });
25
- this.app = app;
51
+ this.config = config;
26
52
  }
27
53
 
54
+ /**
55
+ * 获取 coredb
56
+ */
57
+ _getCoreDB() {
58
+ const coreDB = Storage.connection('system');
59
+ return coreDB;
60
+ }
61
+
28
62
  request(url, args, callback) {
29
63
  if (typeof args === 'function') {
30
64
  callback = args;
@@ -74,8 +108,8 @@ class HttpClient extends urllib.HttpClient2 {
74
108
  }
75
109
  }
76
110
 
77
- function normalizeConfig(app) {
78
- const config = app.config.httpclient;
111
+ function normalizeConfig(httpConfig) {
112
+ const config = httpConfig;
79
113
 
80
114
  // compatibility
81
115
  if (typeof config.keepAlive === 'boolean') {
@@ -118,12 +152,12 @@ function normalizeConfig(app) {
118
152
  }
119
153
 
120
154
  if (config.httpAgent.timeout < 30000) {
121
- app.coreLogger.warn('[ee:httpclient] config.httpclient.httpAgent.timeout(%s) can\'t below 30000, auto reset to 30000',
155
+ Log.coreLogger.warn('[ee:httpclient] config.httpclient.httpAgent.timeout(%s) can\'t below 30000, auto reset to 30000',
122
156
  config.httpAgent.timeout);
123
157
  config.httpAgent.timeout = 30000;
124
158
  }
125
159
  if (config.httpsAgent.timeout < 30000) {
126
- app.coreLogger.warn('[ee:httpclient] config.httpclient.httpsAgent.timeout(%s) can\'t below 30000, auto reset to 30000',
160
+ Log.coreLogger.warn('[ee:httpclient] config.httpclient.httpsAgent.timeout(%s) can\'t below 30000, auto reset to 30000',
127
161
  config.httpsAgent.timeout);
128
162
  config.httpsAgent.timeout = 30000;
129
163
  }
@@ -0,0 +1,99 @@
1
+ const { fork } = require('child_process');
2
+
3
+ class ForkProcess {
4
+ constructor(host, modulePath, processArgs = [], processOptions = {}) {
5
+ this.host = host;
6
+ this.modulePath = modulePath;
7
+ this.args = processArgs;
8
+ this.options = processOptions;
9
+ this.sleeping = false;
10
+ this.activitiesCount = 0;
11
+ this.activitiesMap = new Map();
12
+
13
+ this.child = fork(
14
+ this.modulePath,
15
+ this.args,
16
+ this.options
17
+ );
18
+
19
+ this.pid = this.child.pid;
20
+ this._init();
21
+ }
22
+
23
+ /**
24
+ * 进程挂起
25
+ */
26
+ sleep() {
27
+ if (this.activitiesCount) {
28
+ if (this.sleeping) return;
29
+ process.kill(this.pid, 'SIGSTOP');
30
+ this.sleeping = true;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * 进程唤醒
36
+ */
37
+ wakeup() {
38
+ if (!this.sleeping) return;
39
+ process.kill(this.pid, 'SIGCONT');
40
+ this.sleeping = false;
41
+ }
42
+
43
+ /**
44
+ * 进程初始化
45
+ */
46
+ _init() {
47
+ this.child.on('message', (data) => {
48
+ const id = data.id;
49
+ this.connectionsCountMinus(id);
50
+ delete data.id;
51
+ delete data.action;
52
+ //this.host.emit('forked_message', {data, id});
53
+ });
54
+ this.child.on('exit', (code, signal) => {
55
+ // if (code !== 0 && code !== null) {
56
+ // this.host.emit('forked_error', code, this.pid);
57
+ // } else {
58
+ // this.host.emit('forked_exit', this.pid);
59
+ // }
60
+ });
61
+ this.child.on('error', (err) => {
62
+ console.log('forked error: ', err);
63
+ // this.host.emit('forked_error', err, this.pid);
64
+ });
65
+ }
66
+
67
+ /**
68
+ * 向进程发消息
69
+ */
70
+ send(params) {
71
+ if (this.sleeping) {
72
+ this.wakeup();
73
+ }
74
+ this.connectionsCountPlus(params.id);
75
+ this.child.send(params);
76
+ }
77
+
78
+ /**
79
+ * 连接数+
80
+ */
81
+ _connectionsCountPlus(id) {
82
+ this.activitiesMap.set(id, 1);
83
+ this.activitiesCount += 1;
84
+ this.host.connectionsMap[this.pid] = this.activitiesCount;
85
+ }
86
+
87
+ /**
88
+ * 连接数-
89
+ */
90
+ _connectionsCountMinus(id) {
91
+ if (this.activitiesMap.has(id)) {
92
+ this.activitiesCount = (this.activitiesCount > 0) ? (this.activitiesCount - 1) : 0;
93
+ this.activitiesMap.delete(id);
94
+ }
95
+ this.host.connectionsMap[this.pid] = this.activitiesCount;
96
+ }
97
+ }
98
+
99
+ module.exports = ForkProcess;
@@ -0,0 +1,33 @@
1
+ //require('bytenode');
2
+ const path = require('path');
3
+ const ForkProcess = require('./forkProcess');
4
+ const Ps = require('../../utils/ps');
5
+ const Constants = require('../../const');
6
+
7
+ class ChildJob {
8
+
9
+ /**
10
+ * constructor
11
+ * @param {String} name - job name
12
+ * @param {String} filepath - filepath
13
+ * @param {Object} opt - child process options
14
+ */
15
+ constructor(name, filepath, opt = {}) {
16
+ let options = Object.assign({
17
+ processArgs: Ps.isDev() ? [`--inspect=${Constants.jobs.inspectStartIndex}`] : [],
18
+ processOptions: {
19
+ //cwd: path.dirname(filepath),
20
+ env: Ps.allEnv(),
21
+ stdio: 'pipe'
22
+ }
23
+ }, opt);
24
+
25
+ this.childProcess = new ForkProcess(this, filepath, options.processArgs, options.processOptions);
26
+
27
+ this.jobReady = false;
28
+ this.exec = filepath;
29
+ this.name = name;
30
+ }
31
+ }
32
+
33
+ module.exports = ChildJob;