/
framework.ts
367 lines (338 loc) · 11.1 KB
/
framework.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import {
BaseFramework,
CommonMiddlewareUnion,
ContextMiddlewareManager,
HTTP_SERVER_KEY,
IMidwayBootstrapOptions,
MidwayFrameworkType,
Types,
WS_CONTROLLER_KEY,
WS_EVENT_KEY,
WSEventInfo,
WSEventTypeEnum,
getClassMetadata,
listModule,
Framework,
WSControllerOption,
MidwayInvokeForbiddenError,
} from '@midwayjs/core';
import * as http from 'http';
import { debuglog } from 'util';
const debug = debuglog('midway:debug');
import {
Application,
Context,
IMidwayWSApplication,
IMidwayWSConfigurationOptions,
IMidwayWSContext,
NextFunction,
} from './interface';
import * as WebSocket from 'ws';
@Framework()
export class MidwayWSFramework extends BaseFramework<
Application,
Context,
IMidwayWSConfigurationOptions
> {
server: http.Server;
protected heartBeatInterval: NodeJS.Timeout;
protected connectionMiddlewareManager = this.createMiddlewareManager();
configure(): IMidwayWSConfigurationOptions {
return this.configService.getConfiguration('webSocket');
}
applicationInitialize(options: IMidwayBootstrapOptions) {
this.configurationOptions.noServer = true;
const opts = Object.assign({}, this.configurationOptions, { port: null });
this.app = new WebSocket.Server(opts) as IMidwayWSApplication;
this.defineApplicationProperties({
useConnectionMiddleware: (
middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>
) => {
return this.useConnectionMiddleware(middleware);
},
getConnectionMiddleware: (): ContextMiddlewareManager<
Context,
NextFunction,
undefined
> => {
return this.getConnectionMiddleware();
},
});
}
public app: IMidwayWSApplication;
protected async afterContainerReady(
options: Partial<IMidwayBootstrapOptions>
): Promise<void> {
await this.loadMidwayController();
}
public async run(): Promise<void> {
let server: http.Server;
if (!this.configurationOptions.port) {
server = this.applicationContext.get(HTTP_SERVER_KEY);
this.logger.info(
'[midway:ws] WebSocket server find shared http server and will be attach.'
);
} else {
server = this.configurationOptions.server ?? http.createServer();
}
server.on('upgrade', (request, socket: any, head: Buffer) => {
this.app.handleUpgrade(request, socket, head, ws => {
this.app.emit('connection', ws, request);
});
});
this.server = server;
if (this.configurationOptions.port) {
await new Promise<void>(resolve => {
server.listen(this.configurationOptions.port, () => {
this.logger.info(
`[midway:ws] WebSocket server port = ${this.configurationOptions.port} start success.`
);
if (this.configurationOptions.enableServerHeartbeatCheck) {
this.startHeartBeat();
}
resolve();
});
});
}
}
protected async beforeStop(): Promise<void> {
return new Promise<void>(resolve => {
this.app.close(() => {
setTimeout(() => {
resolve();
}, 1000);
});
this.server.close();
});
}
public getFrameworkType(): MidwayFrameworkType {
return MidwayFrameworkType.WS;
}
private async loadMidwayController() {
// create room
const controllerModules = listModule(WS_CONTROLLER_KEY);
if (controllerModules.length > 0) {
// ws just one namespace
await this.addNamespace(controllerModules[0]);
}
}
private async addNamespace(target: any) {
const controllerOption: WSControllerOption = getClassMetadata(
WS_CONTROLLER_KEY,
target
);
const controllerMiddleware =
controllerOption.routerOptions.middleware ?? [];
const controllerConnectionMiddleware =
controllerOption.routerOptions.connectionMiddleware ?? [];
this.app.on(
'connection',
async (socket: IMidwayWSContext, request: http.IncomingMessage) => {
socket.isAlive = true;
socket.on('error', error => {
this.logger.error(`socket got error: ${error}`);
});
socket.on('pong', () => {
socket.isAlive = true;
});
// create request context
this.app.createAnonymousContext(socket);
socket.requestContext.registerObject('socket', socket);
socket.app = this.app;
// run connection middleware
const connectFn = await this.middlewareService.compose(
[
...this.connectionMiddlewareManager,
...controllerConnectionMiddleware,
],
this.app
);
await connectFn(socket);
const wsEventInfos: WSEventInfo[] = getClassMetadata(
WS_EVENT_KEY,
target
);
// 存储方法对应的响应处理
const methodMap = {};
if (wsEventInfos.length) {
for (const wsEventInfo of wsEventInfos) {
methodMap[wsEventInfo.propertyName] = methodMap[
wsEventInfo.propertyName
] || { responseEvents: [] };
const controller = await socket.requestContext.getAsync(target);
// on connection
if (wsEventInfo.eventType === WSEventTypeEnum.ON_CONNECTION) {
try {
const fn = await this.middlewareService.compose(
[
...(wsEventInfo?.eventOptions?.middleware || []),
async (ctx, next) => {
const isPassed = await this.app
.getFramework()
.runGuard(ctx, target, wsEventInfo.propertyName);
if (!isPassed) {
throw new MidwayInvokeForbiddenError(
wsEventInfo.propertyName,
target
);
}
// eslint-disable-next-line prefer-spread
return controller[wsEventInfo.propertyName].apply(
controller,
[socket, request]
);
},
],
this.app
);
const result = await fn(socket);
await this.bindSocketResponse(
result,
socket,
wsEventInfo.propertyName,
methodMap
);
} catch (err) {
this.logger.error(err);
}
} else if (wsEventInfo.eventType === WSEventTypeEnum.ON_MESSAGE) {
// on user custom event
socket.on(wsEventInfo.messageEventName, async (...args) => {
debug('[ws]: got message', wsEventInfo.messageEventName, args);
try {
const result = await (
await this.applyMiddleware(async (ctx, next) => {
// add controller middleware
const fn = await this.middlewareService.compose(
[
...controllerMiddleware,
...(wsEventInfo?.eventOptions?.middleware || []),
async (ctx, next) => {
// eslint-disable-next-line prefer-spread
return controller[wsEventInfo.propertyName].apply(
controller,
args
);
},
],
this.app
);
return await fn(ctx, next);
})
)(socket);
if (typeof args[args.length - 1] === 'function') {
// ack
args[args.length - 1](result);
} else {
// emit
await this.bindSocketResponse(
result,
socket,
wsEventInfo.propertyName,
methodMap
);
}
} catch (error) {
this.logger.error(error);
}
});
} else if (
wsEventInfo.eventType === WSEventTypeEnum.ON_DISCONNECTION
) {
// on socket disconnect
socket.on('close', async (reason: string) => {
try {
const result = await controller[
wsEventInfo.propertyName
].apply(controller, [reason]);
await this.bindSocketResponse(
result,
socket,
wsEventInfo.propertyName,
methodMap
);
} catch (err) {
this.logger.error(err);
}
});
} else {
// 存储每个方法对应的后置响应处理,供后续快速匹配
methodMap[wsEventInfo.propertyName].responseEvents.push(
wsEventInfo
);
}
}
}
}
);
this.app.on('error', err => {
this.logger.error('socket server got error', err);
});
this.app.on('close', () => {
if (this.heartBeatInterval) {
clearInterval(this.heartBeatInterval);
}
this.logger.info('socket server close');
});
}
private async bindSocketResponse(
result: any,
socket: IMidwayWSContext,
propertyName: string,
methodMap: {
responseEvents?: WSEventInfo[];
}
) {
if (!result) return;
if (methodMap[propertyName]) {
for (const wsEventInfo of methodMap[propertyName].responseEvents) {
if (wsEventInfo.eventType === WSEventTypeEnum.EMIT) {
socket.send(formatResult(result));
} else if (wsEventInfo.eventType === WSEventTypeEnum.BROADCAST) {
this.app.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(formatResult(result));
}
});
}
}
if (methodMap[propertyName].responseEvents.length === 0) {
// no emit decorator
socket.send(formatResult(result));
}
} else {
// just send
socket.send(formatResult(result));
}
}
public getFrameworkName() {
return 'midway:ws';
}
public useConnectionMiddleware(
middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>
) {
this.connectionMiddlewareManager.insertLast(middleware);
}
public getConnectionMiddleware(): ContextMiddlewareManager<
Context,
NextFunction,
undefined
> {
return this.connectionMiddlewareManager;
}
public startHeartBeat() {
this.heartBeatInterval = setInterval(() => {
this.app.clients.forEach((socket: IMidwayWSContext) => {
if (socket.isAlive === false) {
debug('[ws]: socket terminate');
return socket.terminate();
}
socket.isAlive = false;
socket.ping();
});
}, this.configurationOptions.serverHeartbeatInterval);
}
}
function formatResult(result) {
return Types.isObject(result) ? JSON.stringify(result) : result;
}