-
Notifications
You must be signed in to change notification settings - Fork 568
/
bootstrap.ts
270 lines (241 loc) · 7.53 KB
/
bootstrap.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import {
IMidwayBootstrapOptions,
IMidwayContainer,
MidwayApplicationManager,
initializeGlobalApplicationContext,
destroyGlobalApplicationContext,
loadModule,
isTypeScriptEnvironment,
MidwayMainFrameworkMissingError,
MidwayFrameworkService,
} from '@midwayjs/core';
import { join } from 'path';
import { ILogger, MidwayLoggerContainer, loggers } from '@midwayjs/logger';
import { createContextManager } from '@midwayjs/async-hooks-context-manager';
import {
ChildProcessEventBus,
ThreadEventBus,
IEventBus,
} from '@midwayjs/event-bus';
import { setupWorker } from './sticky';
export class BootstrapStarter {
protected appDir: string;
protected baseDir: string;
protected globalOptions: Partial<IMidwayBootstrapOptions> = {};
protected globalConfig: any;
private applicationContext: IMidwayContainer;
private eventBus: IEventBus<any>;
public configure(options: IMidwayBootstrapOptions = {}) {
this.globalOptions = options;
return this;
}
public async init() {
this.appDir = this.globalOptions.appDir =
this.globalOptions.appDir || process.cwd();
this.baseDir = this.globalOptions.baseDir = this.getBaseDir();
if (process.env['MIDWAY_FORK_MODE']) {
if (process.env['MIDWAY_FORK_MODE'] === 'cluster') {
this.eventBus = new ChildProcessEventBus({
isWorker: true,
});
} else if (process.env['MIDWAY_FORK_MODE'] === 'thread') {
this.eventBus = new ThreadEventBus({
isWorker: true,
});
}
}
if (!this.globalOptions.moduleLoadType) {
const pkgJSON = await loadModule(join(this.appDir, 'package.json'), {
safeLoad: true,
enableCache: false,
});
this.globalOptions.moduleLoadType =
pkgJSON?.type === 'module' ? 'esm' : 'commonjs';
}
this.applicationContext = await initializeGlobalApplicationContext({
asyncContextManager: createContextManager(),
loggerFactory: loggers,
...this.globalOptions,
});
return this.applicationContext;
}
public async run() {
this.applicationContext = await this.init();
if (this.eventBus) {
await this.eventBus.start();
if (process.env['MIDWAY_STICKY_MODE'] === 'true') {
const applicationManager = this.applicationContext.get(
MidwayApplicationManager
);
const io = applicationManager.getApplication('socketIO');
setupWorker(io);
}
}
const frameworkService = this.applicationContext.get(
MidwayFrameworkService
);
// check main framework
if (!frameworkService.getMainApp()) {
throw new MidwayMainFrameworkMissingError();
}
}
public async stop() {
if (this.applicationContext) {
await destroyGlobalApplicationContext(this.applicationContext);
}
if (this.eventBus) {
await this.eventBus.stop();
}
}
public getApplicationContext() {
return this.applicationContext;
}
protected getBaseDir() {
if (this.globalOptions.baseDir) {
return this.globalOptions.baseDir;
}
if (isTypeScriptEnvironment()) {
return join(this.appDir, 'src');
} else {
return join(this.appDir, 'dist');
}
}
}
export class Bootstrap {
protected static starter: BootstrapStarter;
protected static logger: ILogger;
protected static configured = false;
protected static bootstrapLoggerFactory = new MidwayLoggerContainer();
/**
* set global configuration for midway
* @param configuration
*/
static configure(configuration: IMidwayBootstrapOptions = {}) {
this.configured = true;
if (!this.logger && !configuration.logger) {
this.logger = this.bootstrapLoggerFactory.createLogger('bootstrap', {
enableError: false,
enableFile: false,
enableConsole: true,
} as any);
if (configuration.logger === false) {
if (this.logger['disableConsole']) {
// v2
this.logger['disableConsole']();
} else {
// v3
this.logger['level'] = 'none';
}
}
configuration.logger = this.logger;
} else {
this.logger = this.logger || (configuration.logger as ILogger);
}
// 处理三方框架内部依赖 process.cwd 来查找 node_modules 等问题
if (configuration.appDir && configuration.appDir !== process.cwd()) {
process.chdir(configuration.appDir);
}
this.getStarter().configure(configuration);
return this;
}
static getStarter() {
if (!this.starter) {
this.starter = new BootstrapStarter();
}
return this.starter;
}
static async run() {
if (!this.configured) {
this.configure();
}
// https://nodejs.org/api/process.html#process_signal_events
// https://en.wikipedia.org/wiki/Unix_signal
// kill(2) Ctrl-C
process.once('SIGINT', this.onSignal.bind(this, 'SIGINT'));
// kill(3) Ctrl-\
process.once('SIGQUIT', this.onSignal.bind(this, 'SIGQUIT'));
// kill(15) default
process.once('SIGTERM', this.onSignal.bind(this, 'SIGTERM'));
process.once('exit', this.onExit.bind(this));
this.uncaughtExceptionHandler = this.uncaughtExceptionHandler.bind(this);
process.on('uncaughtException', this.uncaughtExceptionHandler);
this.unhandledRejectionHandler = this.unhandledRejectionHandler.bind(this);
process.on('unhandledRejection', this.unhandledRejectionHandler);
return this.getStarter()
.run()
.then(() => {
this.logger.info('[midway:bootstrap] current app started');
global['MIDWAY_BOOTSTRAP_APP_READY'] = true;
return this.getApplicationContext();
})
.catch(err => {
this.logger.error(err);
process.exit(1);
});
}
static async stop() {
await this.getStarter().stop();
process.removeListener('uncaughtException', this.uncaughtExceptionHandler);
process.removeListener(
'unhandledRejection',
this.unhandledRejectionHandler
);
this.reset();
global['MIDWAY_BOOTSTRAP_APP_READY'] = false;
}
static reset() {
this.configured = false;
this.starter = null;
this.bootstrapLoggerFactory.close();
}
/**
* on bootstrap receive a exit signal
* @param signal
*/
private static async onSignal(signal) {
this.logger.info('[midway:bootstrap] receive signal %s, closing', signal);
try {
await this.stop();
this.logger.info('[midway:bootstrap] close done, exiting with code:0');
process.exit(0);
} catch (err) {
this.logger.error('[midway:bootstrap] close with error: ', err);
process.exit(1);
}
}
/**
* on bootstrap process exit
* @param code
*/
private static onExit(code) {
this.logger.info('[midway:bootstrap] exit with code:%s', code);
}
private static uncaughtExceptionHandler(err) {
if (!(err instanceof Error)) {
err = new Error(String(err));
}
if (err.name === 'Error') {
err.name = 'unhandledExceptionError';
}
this.logger.error(err);
}
private static unhandledRejectionHandler(err) {
if (!(err instanceof Error)) {
const newError = new Error(String(err));
// err maybe an object, try to copy the name, message and stack to the new error instance
if (err) {
if (err.name) newError.name = err.name;
if (err.message) newError.message = err.message;
if (err.stack) newError.stack = err.stack;
}
err = newError;
}
if (err.name === 'Error') {
err.name = 'unhandledRejectionError';
}
this.logger.error(err);
}
static getApplicationContext(): IMidwayContainer {
return this.getStarter().getApplicationContext();
}
}