-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathapp.ts
More file actions
241 lines (215 loc) · 7.59 KB
/
app.ts
File metadata and controls
241 lines (215 loc) · 7.59 KB
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
import http from 'http';
import https from 'https';
import net from 'net';
import os from 'os';
import path from 'path';
import type Koa from 'koa';
import { Injector } from '@opensumi/di';
import { WebSocketHandler } from '@opensumi/ide-connection/lib/node';
import { ContributionProvider, createContributionProvider, getDebugLogger, isWindows } from '@opensumi/ide-core-common';
import { ILogServiceManager, ILogService, SupportLogNamespace, StoragePaths } from '@opensumi/ide-core-common';
import { DEFAULT_TRS_REGISTRY } from '@opensumi/ide-core-common/lib/const';
import { createServerConnection2, createNetServerConnection, RPCServiceCenter } from '../connection';
import { NodeModule } from '../node-module';
import { AppConfig, IServerApp, IServerAppOpts, ModuleConstructor, ServerAppContribution } from '../types';
import { injectInnerProviders } from './inner-providers';
export class ServerApp implements IServerApp {
private _injector: Injector;
private config: IServerAppOpts;
private logger: Pick<ILogService, 'log' | 'error'> = getDebugLogger();
private webSocketHandler: WebSocketHandler[];
private modulesInstances: NodeModule[];
use: (middleware: Koa.Middleware<Koa.ParameterizedContext<any, any>>) => void;
protected contributionsProvider: ContributionProvider<ServerAppContribution>;
/**
* 启动初始化
* 1. 绑定 process 报错处理
* 2. 初始化内置的 Provider
* 3. 获取 Modules 的实例
* 4. 设置默认的实例
* @param opts
*/
constructor(private opts: IServerAppOpts) {
this._injector = opts.injector || new Injector();
this.webSocketHandler = opts.webSocketHandler || [];
// 使用外部传入的中间件
this.use = opts.use || ((middleware) => null);
this.config = {
injector: this.injector,
logDir: opts.logDir,
logLevel: opts.logLevel,
LogServiceClass: opts.LogServiceClass,
marketplace: Object.assign(
{
endpoint: DEFAULT_TRS_REGISTRY.ENDPOINT,
extensionDir: path.join(
os.homedir(),
...(isWindows ? [StoragePaths.WINDOWS_APP_DATA_DIR, StoragePaths.WINDOWS_ROAMING_DIR] : ['']),
StoragePaths.DEFAULT_STORAGE_DIR_NAME,
StoragePaths.MARKETPLACE_DIR,
),
showBuiltinExtensions: false,
accountId: DEFAULT_TRS_REGISTRY.ACCOUNT_ID,
masterKey: DEFAULT_TRS_REGISTRY.MASTER_KEY,
ignoreId: [],
},
opts.marketplace,
),
processCloseExitThreshold: opts.processCloseExitThreshold,
terminalPtyCloseThreshold: opts.terminalPtyCloseThreshold,
staticAllowOrigin: opts.staticAllowOrigin,
staticAllowPath: opts.staticAllowPath,
extLogServiceClassPath: opts.extLogServiceClassPath,
maxExtProcessCount: opts.maxExtProcessCount,
onDidCreateExtensionHostProcess: opts.onDidCreateExtensionHostProcess,
extHost: process.env.EXTENSION_HOST_ENTRY || opts.extHost,
blockPatterns: opts.blockPatterns,
extHostIPCSockPath: opts.extHostIPCSockPath,
extHostForkOptions: opts.extHostForkOptions,
rpcMessageTimeout: opts.rpcMessageTimeout || -1,
};
this.bindProcessHandler();
this.initBaseProvider();
this.createNodeModules(opts.modules, opts.modulesInstances);
this.logger = this.injector.get(ILogServiceManager).getLogger(SupportLogNamespace.App);
this.contributionsProvider = this.injector.get(ServerAppContribution);
}
get injector() {
return this._injector;
}
/**
* 将被依赖但未被加入modules的模块加入到待加载模块最后
*/
public resolveModuleDeps(moduleConstructor: ModuleConstructor, modules: any[]) {
const dependencies = Reflect.getMetadata('dependencies', moduleConstructor) as [];
if (dependencies) {
dependencies.forEach((dep) => {
if (modules.indexOf(dep) === -1) {
modules.push(dep);
}
});
}
}
private get contributions(): ServerAppContribution[] {
return this.contributionsProvider.getContributions();
}
private initBaseProvider() {
// 创建 contributionsProvider
createContributionProvider(this.injector, ServerAppContribution);
this.injector.addProviders({
token: AppConfig,
useValue: this.config,
});
injectInnerProviders(this.injector);
}
private async initializeContribution() {
for (const contribution of this.contributions) {
if (contribution.initialize) {
try {
await contribution.initialize(this);
} catch (error) {
this.logger.error('Could not initialize contribution', error);
}
}
}
}
private async startContribution() {
for (const contrib of this.contributions) {
if (contrib.onStart) {
try {
await contrib.onStart(this);
} catch (error) {
this.logger.error('Could not start contribution', error);
}
}
}
}
async start(
server: http.Server | https.Server | net.Server,
serviceHandler?: (serviceCenter: RPCServiceCenter) => void,
) {
await this.initializeContribution();
if (serviceHandler) {
serviceHandler(new RPCServiceCenter());
} else {
if (server instanceof http.Server || server instanceof https.Server) {
// 创建 websocket 通道
createServerConnection2(server, this.injector, this.modulesInstances, this.webSocketHandler, this.opts);
} else if (server instanceof net.Server) {
createNetServerConnection(server, this.injector, this.modulesInstances);
}
}
await this.startContribution();
}
private async onStop() {
for (const contrib of this.contributions) {
if (contrib.onStop) {
try {
await contrib.onStop(this);
} catch (error) {
this.logger.error('Could not stop contribution', error);
}
}
}
}
/**
* 绑定 process 退出逻辑
*/
private bindProcessHandler() {
process.on('uncaughtException', (error) => {
if (error) {
this.logger.error('Uncaught Exception: ', error.toString());
if (error.stack) {
this.logger.error(error.stack);
}
}
});
// Handles normal process termination.
process.on('exit', () => {
this.logger.log('process exit');
});
// Handles `Ctrl+C`.
process.on('SIGINT', async () => {
this.logger.log('process SIGINT');
await this.onStop();
this.logger.log('process SIGINT DONE');
process.exit(0);
});
// Handles `kill pid`.
process.on('SIGTERM', async () => {
this.logger.log('process SIGTERM');
await this.onStop();
this.logger.log('process SIGTERM DONE');
process.exit(0);
});
}
/**
* 收集 module 实例
* @param Constructors
* @param modules
*/
private createNodeModules(Constructors: ModuleConstructor[] = [], modules: NodeModule[] = []) {
const allModules = [...modules];
Constructors.forEach((c) => {
this.resolveModuleDeps(c, Constructors);
});
for (const Constructor of Constructors) {
allModules.push(this.injector.get(Constructor));
}
for (const instance of allModules) {
if (instance.providers) {
this.injector.addProviders(...instance.providers);
}
if (instance.contributionProvider) {
if (Array.isArray(instance.contributionProvider)) {
for (const contributionProvider of instance.contributionProvider) {
createContributionProvider(this.injector, contributionProvider);
}
} else {
createContributionProvider(this.injector, instance.contributionProvider);
}
}
}
this.modulesInstances = allModules;
}
}