@midwayjs/web 3.0.13 → 3.0.14-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.
@@ -19,7 +19,7 @@ module.exports = {
19
19
  if (this[ctxLogger]) {
20
20
  return this[ctxLogger];
21
21
  }
22
- return this.getLogger('logger');
22
+ return this.app.createContextLogger(this, 'logger');
23
23
  },
24
24
 
25
25
  set logger(customLogger) {
package/dist/base.js CHANGED
@@ -38,9 +38,6 @@ const createAppWorkerLoader = () => {
38
38
  this.useEggSocketIO = false;
39
39
  }
40
40
  getEggPaths() {
41
- if ((0, core_1.getCurrentApplicationContext)()) {
42
- this.singleProcessMode = true;
43
- }
44
41
  if (!this.appDir) {
45
42
  // 这里的逻辑是为了兼容老 cluster 模式
46
43
  if (this.app.options.typescript || this.app.options.isTsMode) {
@@ -104,19 +101,30 @@ const createAppWorkerLoader = () => {
104
101
  return serverEnv;
105
102
  }
106
103
  load() {
107
- if (!this.singleProcessMode) {
108
- // 多进程模式,从 egg-scripts 启动的
109
- process.env['EGG_CLUSTER_MODE'] = 'true';
110
- debug('[egg]: run with egg-scripts in cluster mode');
111
- // 如果不走 bootstrap,就得在这里初始化 applicationContext
112
- (0, core_1.initializeGlobalApplicationContext)({
113
- ...this.globalOptions,
114
- appDir: this.appDir,
115
- baseDir: this.baseDir,
116
- ignore: ['**/app/extend/**'],
117
- application: this.app,
118
- }).then(_ => {
119
- debug('[egg]: global context: init complete');
104
+ /**
105
+ * 由于使用了新的 hook 方式,这个时候 midway 已经初始化了一部分
106
+ * 但是我们把初始化分为了两个部分,framework 相关的留到这里初始化
107
+ * 避免 app 不存在,也能尽可能和单进程模式执行一样的逻辑
108
+ */
109
+ // lazy initialize framework
110
+ if (process.env['EGG_CLUSTER_MODE'] === 'true') {
111
+ this.app.beforeStart(async () => {
112
+ debug('[egg]: start "initialize framework service with lazy in app.load"');
113
+ const applicationContext = (0, core_1.getCurrentApplicationContext)();
114
+ /**
115
+ * 这里 logger service 已经被 get loggers() 初始化过了,就不需要在这里初始化了
116
+ */
117
+ // framework/config/plugin/logger/app decorator support
118
+ await applicationContext.getAsync(core_1.MidwayFrameworkService, [
119
+ applicationContext,
120
+ {
121
+ application: this.app,
122
+ },
123
+ ]);
124
+ // lifecycle support
125
+ await applicationContext.getAsync(core_1.MidwayLifeCycleService, [
126
+ applicationContext,
127
+ ]);
120
128
  });
121
129
  }
122
130
  }
@@ -126,15 +134,13 @@ const createAppWorkerLoader = () => {
126
134
  }
127
135
  loadConfig() {
128
136
  super.loadConfig();
129
- if (this.singleProcessMode) {
130
- const configService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayConfigService);
131
- configService.addObject(this.config);
132
- Object.defineProperty(this, 'config', {
133
- get() {
134
- return configService.getConfiguration();
135
- },
136
- });
137
- }
137
+ const configService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayConfigService);
138
+ configService.addObject(this.config, true);
139
+ Object.defineProperty(this, 'config', {
140
+ get() {
141
+ return configService.getConfiguration();
142
+ },
143
+ });
138
144
  }
139
145
  loadMiddleware() {
140
146
  super.loadMiddleware();
@@ -155,9 +161,6 @@ const createAgentWorkerLoader = () => {
155
161
  require('egg').AgentWorkerLoader;
156
162
  class EggAgentWorkerLoader extends AppWorkerLoader {
157
163
  getEggPaths() {
158
- if ((0, core_1.getCurrentApplicationContext)()) {
159
- this.singleProcessMode = true;
160
- }
161
164
  if (!this.appDir) {
162
165
  if (this.app.options.typescript || this.app.options.isTsMode) {
163
166
  process.env.EGG_TYPESCRIPT = 'true';
@@ -222,21 +225,16 @@ const createAgentWorkerLoader = () => {
222
225
  load() {
223
226
  this.app.beforeStart(async () => {
224
227
  debug('[egg]: start "initializeAgentApplicationContext"');
225
- await (0, utils_1.initializeAgentApplicationContext)(this.app, {
226
- ...this.globalOptions,
227
- appDir: this.appDir,
228
- baseDir: this.baseDir,
229
- ignore: ['**/app/extend/**'],
230
- });
228
+ await (0, utils_1.initializeAgentApplicationContext)(this.app);
231
229
  super.load();
232
230
  debug('[egg]: agent load run complete');
233
231
  });
234
232
  }
235
233
  loadConfig() {
236
234
  super.loadConfig();
237
- if (this.singleProcessMode) {
235
+ if ((0, core_1.getCurrentApplicationContext)()) {
238
236
  const configService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayConfigService);
239
- configService.addObject(this.config);
237
+ configService.addObject(this.config, true);
240
238
  Object.defineProperty(this, 'config', {
241
239
  get() {
242
240
  return configService.getConfiguration();
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cluster.d.ts.map
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const core_1 = require("@midwayjs/core");
4
+ const path_1 = require("path");
5
+ const utils_1 = require("./utils");
6
+ const util_1 = require("util");
7
+ const debug = (0, util_1.debuglog)('midway:debug');
8
+ function runInAgent() {
9
+ return (process.title.indexOf('agent') !== -1 ||
10
+ (process.argv[1] && process.argv[1].indexOf('agent_worker') !== -1));
11
+ }
12
+ // 多进程模式,从 egg-scripts 启动的
13
+ process.env['EGG_CLUSTER_MODE'] = 'true';
14
+ const isAgent = runInAgent();
15
+ debug('[egg]: run with egg-scripts in worker and init midway container in cluster mode');
16
+ const appDir = process.cwd();
17
+ let baseDir;
18
+ if ((0, utils_1.isTypeScriptEnvironment)()) {
19
+ baseDir = (0, path_1.join)(appDir, 'src');
20
+ }
21
+ else {
22
+ baseDir = (0, path_1.join)(appDir, 'dist');
23
+ }
24
+ (0, core_1.initializeGlobalApplicationContext)({
25
+ appDir,
26
+ baseDir,
27
+ ignore: ['**/app/extend/**'],
28
+ lazyInitializeFramework: true,
29
+ });
30
+ if (!isAgent) {
31
+ debug('[egg]: run with egg-scripts in worker and init midway container complete');
32
+ }
33
+ else {
34
+ debug('[egg]: run with egg-scripts in agent and init midway container complete');
35
+ }
36
+ //# sourceMappingURL=cluster.js.map
@@ -0,0 +1,3 @@
1
+ declare const _default: (appInfo: any) => any;
2
+ export default _default;
3
+ //# sourceMappingURL=config.default.d.ts.map
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path = require("path");
4
+ const mkdirp = require("mkdirp");
5
+ const os = require("os");
6
+ const fs = require("fs");
7
+ exports.default = appInfo => {
8
+ const exports = {};
9
+ exports.rundir = path.join(appInfo.appDir, 'run');
10
+ // 修改默认的日志名
11
+ exports.midwayLogger = {
12
+ clients: {
13
+ appLogger: {
14
+ fileLogName: 'midway-web.log',
15
+ aliasName: 'logger',
16
+ },
17
+ agentLogger: {
18
+ fileLogName: 'midway-agent.log',
19
+ },
20
+ },
21
+ };
22
+ exports.egg = {
23
+ dumpConfig: true,
24
+ contextLoggerFormat: info => {
25
+ const ctx = info.ctx;
26
+ // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
27
+ const userId = ctx.userId || '-';
28
+ const traceId = (ctx.tracer && ctx.tracer.traceId) || '-';
29
+ const use = Date.now() - ctx.startTime;
30
+ const label = userId +
31
+ '/' +
32
+ ctx.ip +
33
+ '/' +
34
+ traceId +
35
+ '/' +
36
+ use +
37
+ 'ms ' +
38
+ ctx.method +
39
+ ' ' +
40
+ ctx.url;
41
+ return `${info.timestamp} ${info.LEVEL} ${info.pid} [${label}] ${info.message}`;
42
+ },
43
+ };
44
+ exports.pluginOverwrite = false;
45
+ exports.security = {
46
+ csrf: {
47
+ ignoreJSON: false,
48
+ },
49
+ };
50
+ // alinode runtime 写入的日志策略是: 如果 NODE_LOG_DIR 有设置,写入 NODE_LOG_DIR 设置的目录;否则为 /tmp
51
+ let alinodeLogdir = fs.existsSync('/tmp') ? '/tmp' : os.tmpdir();
52
+ // try to use NODE_LOG_DIR first
53
+ if (process.env.NODE_LOG_DIR) {
54
+ alinodeLogdir = process.env.NODE_LOG_DIR;
55
+ }
56
+ mkdirp.sync(alinodeLogdir);
57
+ exports.alinode = {
58
+ logdir: alinodeLogdir,
59
+ error_log: [
60
+ path.join(appInfo.root, `logs/${appInfo.pkg.name}/common-error.log`),
61
+ path.join(appInfo.root, 'logs/stderr.log'),
62
+ ],
63
+ packages: [path.join(appInfo.appDir, 'package.json')],
64
+ };
65
+ return exports;
66
+ };
67
+ //# sourceMappingURL=config.default.js.map
@@ -0,0 +1,9 @@
1
+ export declare const egg: {
2
+ plugins: {
3
+ 'egg-mock': {
4
+ enable: boolean;
5
+ package: string;
6
+ };
7
+ };
8
+ };
9
+ //# sourceMappingURL=config.local.d.ts.map
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.egg = void 0;
4
+ exports.egg = {
5
+ plugins: {
6
+ 'egg-mock': {
7
+ enable: true,
8
+ package: 'egg-mock',
9
+ },
10
+ },
11
+ };
12
+ //# sourceMappingURL=config.local.js.map
@@ -0,0 +1,9 @@
1
+ export declare const egg: {
2
+ plugins: {
3
+ 'egg-mock': {
4
+ enable: boolean;
5
+ package: string;
6
+ };
7
+ };
8
+ };
9
+ //# sourceMappingURL=config.unittest.d.ts.map
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.egg = void 0;
4
+ exports.egg = {
5
+ plugins: {
6
+ 'egg-mock': {
7
+ enable: true,
8
+ package: 'egg-mock',
9
+ },
10
+ },
11
+ };
12
+ //# sourceMappingURL=config.unittest.js.map
@@ -1,13 +1,15 @@
1
1
  import { IMidwayWebApplication } from './interface';
2
2
  import { MidwayDecoratorService } from '@midwayjs/core';
3
+ import { MidwayWebFramework } from './framework/web';
3
4
  export declare class EggConfiguration {
4
5
  baseDir: any;
5
6
  appDir: any;
6
7
  app: IMidwayWebApplication;
7
8
  decoratorService: MidwayDecoratorService;
9
+ framework: MidwayWebFramework;
8
10
  init(): void;
9
11
  onReady(): Promise<void>;
10
- onServerReady(): Promise<void>;
12
+ onServerReady(container: any): Promise<void>;
11
13
  onStop(): Promise<void>;
12
14
  }
13
15
  //# sourceMappingURL=configuration.d.ts.map
@@ -12,6 +12,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.EggConfiguration = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const core_1 = require("@midwayjs/core");
15
+ const path_1 = require("path");
16
+ const web_1 = require("./framework/web");
15
17
  let EggConfiguration = class EggConfiguration {
16
18
  init() {
17
19
  this.decoratorService.registerParameterHandler(decorator_1.WEB_ROUTER_PARAM_KEY, options => {
@@ -26,9 +28,16 @@ let EggConfiguration = class EggConfiguration {
26
28
  ? this.app.middleware.slice()
27
29
  : [];
28
30
  }
29
- async onServerReady() {
31
+ async onServerReady(container) {
30
32
  // trigger server didReady
31
33
  this.app.messenger.emit('egg-ready');
34
+ if (process.env['EGG_CLUSTER_MODE'] === 'true') {
35
+ this.app.once('server', server => {
36
+ this.framework.setServer(server);
37
+ // register httpServer to applicationContext
38
+ container.registerObject(core_1.HTTP_SERVER_KEY, server);
39
+ });
40
+ }
32
41
  }
33
42
  async onStop() {
34
43
  // TODO flush egg logger and close it
@@ -50,6 +59,10 @@ __decorate([
50
59
  (0, decorator_1.Inject)(),
51
60
  __metadata("design:type", core_1.MidwayDecoratorService)
52
61
  ], EggConfiguration.prototype, "decoratorService", void 0);
62
+ __decorate([
63
+ (0, decorator_1.Inject)(),
64
+ __metadata("design:type", web_1.MidwayWebFramework)
65
+ ], EggConfiguration.prototype, "framework", void 0);
53
66
  __decorate([
54
67
  (0, decorator_1.Init)(),
55
68
  __metadata("design:type", Function),
@@ -59,65 +72,7 @@ __decorate([
59
72
  EggConfiguration = __decorate([
60
73
  (0, decorator_1.Configuration)({
61
74
  namespace: 'egg',
62
- importConfigs: [
63
- {
64
- default: {
65
- midwayLogger: {
66
- clients: {
67
- appLogger: {
68
- fileLogName: 'midway-web.log',
69
- aliasName: 'logger',
70
- },
71
- agentLogger: {
72
- fileLogName: 'midway-agent.log',
73
- },
74
- },
75
- },
76
- egg: {
77
- dumpConfig: true,
78
- contextLoggerFormat: info => {
79
- const ctx = info.ctx;
80
- // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
81
- const userId = ctx.userId || '-';
82
- const traceId = (ctx.tracer && ctx.tracer.traceId) || '-';
83
- const use = Date.now() - ctx.startTime;
84
- const label = userId +
85
- '/' +
86
- ctx.ip +
87
- '/' +
88
- traceId +
89
- '/' +
90
- use +
91
- 'ms ' +
92
- ctx.method +
93
- ' ' +
94
- ctx.url;
95
- return `${info.timestamp} ${info.LEVEL} ${info.pid} [${label}] ${info.message}`;
96
- },
97
- },
98
- },
99
- test: {
100
- egg: {
101
- plugins: {
102
- 'egg-mock': {
103
- enable: true,
104
- package: 'egg-mock',
105
- },
106
- },
107
- },
108
- },
109
- unittest: {
110
- egg: {
111
- plugins: {
112
- 'egg-mock': {
113
- enable: true,
114
- package: 'egg-mock',
115
- },
116
- },
117
- },
118
- },
119
- },
120
- ],
75
+ importConfigs: [(0, path_1.join)(__dirname, 'config')],
121
76
  })
122
77
  ], EggConfiguration);
123
78
  exports.EggConfiguration = EggConfiguration;
@@ -29,6 +29,7 @@ export declare class MidwayWebFramework extends BaseFramework<Application, Conte
29
29
  setContextLoggerClass(): void;
30
30
  generateMiddleware(middlewareId: any): Promise<any>;
31
31
  beforeStop(): Promise<void>;
32
+ setServer(server: any): void;
32
33
  }
33
34
  export {};
34
35
  //# sourceMappingURL=web.d.ts.map
@@ -87,17 +87,19 @@ let MidwayWebFramework = class MidwayWebFramework extends core_1.BaseFramework {
87
87
  this.app.use(midwayRootMiddleware);
88
88
  this.generator = new EggControllerGenerator(this.app);
89
89
  this.overwriteApplication('app');
90
- await new Promise(resolve => {
91
- this.app.once('application-ready', () => {
92
- debug('[egg]: web framework: init egg end');
93
- resolve();
90
+ this.app.loader.loadOrigin();
91
+ // 这里拦截 app.use 方法,让他可以加到 midway 的 middlewareManager 中
92
+ this.app.originUse = this.app.use;
93
+ this.app.use = this.app.useMiddleware;
94
+ if (!this.isClusterMode) {
95
+ await new Promise(resolve => {
96
+ this.app.once('application-ready', () => {
97
+ debug('[egg]: web framework: init egg end');
98
+ resolve();
99
+ });
100
+ this.app.ready();
94
101
  });
95
- this.app.loader.loadOrigin();
96
- // 这里拦截 app.use 方法,让他可以加到 midway 的 middlewareManager 中
97
- this.app.originUse = this.app.use;
98
- this.app.use = this.app.useMiddleware;
99
- this.app.ready();
100
- });
102
+ }
101
103
  }
102
104
  overwriteApplication(processType) {
103
105
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -136,6 +138,9 @@ let MidwayWebFramework = class MidwayWebFramework extends core_1.BaseFramework {
136
138
  return core_1.MidwayProcessTypeEnum.AGENT;
137
139
  }
138
140
  },
141
+ createContextLogger: (ctx, name) => {
142
+ return this.createContextLogger(ctx, name);
143
+ },
139
144
  }, ['createAnonymousContext']);
140
145
  // if use midway logger will be use midway custom context logger
141
146
  debug(`[egg]: overwrite BaseContextLoggerClass to "${processType}"`);
@@ -238,6 +243,9 @@ let MidwayWebFramework = class MidwayWebFramework extends core_1.BaseFramework {
238
243
  await this.agent.close();
239
244
  }
240
245
  }
246
+ setServer(server) {
247
+ this.server = server;
248
+ }
241
249
  };
242
250
  __decorate([
243
251
  (0, decorator_1.Inject)(),
package/dist/index.d.ts CHANGED
@@ -2,6 +2,6 @@ export * from './interface';
2
2
  export { MidwayWebFramework as Framework } from './framework/web';
3
3
  export { createEggApplication, createEggAgent, createAppWorkerLoader, createAgentWorkerLoader, } from './base';
4
4
  export { Application, Agent } from './application';
5
- export { startCluster } from 'egg';
6
5
  export { EggConfiguration as Configuration } from './configuration';
6
+ export declare function startCluster(serverConfig: any, callback?: any): any;
7
7
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -10,7 +10,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.Configuration = exports.startCluster = exports.Agent = exports.Application = exports.createAgentWorkerLoader = exports.createAppWorkerLoader = exports.createEggAgent = exports.createEggApplication = exports.Framework = void 0;
13
+ exports.startCluster = exports.Configuration = exports.Agent = exports.Application = exports.createAgentWorkerLoader = exports.createAppWorkerLoader = exports.createEggAgent = exports.createEggApplication = exports.Framework = void 0;
14
+ const egg_cluster_1 = require("egg-cluster");
15
+ const path_1 = require("path");
14
16
  __exportStar(require("./interface"), exports);
15
17
  var web_1 = require("./framework/web");
16
18
  Object.defineProperty(exports, "Framework", { enumerable: true, get: function () { return web_1.MidwayWebFramework; } });
@@ -22,8 +24,17 @@ Object.defineProperty(exports, "createAgentWorkerLoader", { enumerable: true, ge
22
24
  var application_1 = require("./application");
23
25
  Object.defineProperty(exports, "Application", { enumerable: true, get: function () { return application_1.Application; } });
24
26
  Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return application_1.Agent; } });
25
- var egg_1 = require("egg");
26
- Object.defineProperty(exports, "startCluster", { enumerable: true, get: function () { return egg_1.startCluster; } });
27
27
  var configuration_1 = require("./configuration");
28
28
  Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.EggConfiguration; } });
29
+ function startCluster(serverConfig, callback) {
30
+ if (!serverConfig['require']) {
31
+ serverConfig['require'] = [];
32
+ }
33
+ if (!Array.isArray(serverConfig['require'])) {
34
+ serverConfig['require'] = [serverConfig['require']];
35
+ }
36
+ serverConfig['require'].push((0, path_1.join)(__dirname, 'cluster'));
37
+ return (0, egg_cluster_1.startCluster)(serverConfig, callback);
38
+ }
39
+ exports.startCluster = startCluster;
29
40
  //# sourceMappingURL=index.js.map
package/dist/logger.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { ILogger } from '@midwayjs/logger';
2
2
  import { Application } from 'egg';
3
+ import { MidwayLoggerService } from '@midwayjs/core';
3
4
  declare class MidwayLoggers extends Map<string, ILogger> {
4
- app: Application;
5
+ protected app: Application;
6
+ protected loggerService: MidwayLoggerService;
5
7
  /**
6
8
  * @constructor
7
9
  * - logger
@@ -20,13 +22,17 @@ declare class MidwayLoggers extends Map<string, ILogger> {
20
22
  * - {String} eol - end of line char
21
23
  * - {String} [concentrateError = duplicate] - whether write error logger to common-error.log, `duplicate` / `redirect` / `ignore`
22
24
  * - customLogger
23
- * @param options
24
25
  * @param app
25
26
  */
26
- constructor(options: any, app: Application, processType: 'agent' | 'app');
27
+ constructor(app: Application);
27
28
  createLogger(options: any, loggerKey: string): ILogger;
28
29
  disableConsole(): void;
29
30
  reload(): void;
31
+ transformEggLogger(eggCustomLogger: any): {
32
+ midwayLogger: {
33
+ clients: {};
34
+ };
35
+ };
30
36
  }
31
37
  export declare const createLoggers: (app: Application, processType: 'agent' | 'app') => MidwayLoggers;
32
38
  export {};