-
Notifications
You must be signed in to change notification settings - Fork 568
/
framework.ts
292 lines (263 loc) · 7.99 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
import {
sendUnaryData,
Server,
ServerCredentials,
setLogger,
UntypedServiceImplementation,
UntypedHandleCall,
ServerUnaryCall,
} from '@grpc/grpc-js';
import {
Config,
Framework,
getClassMetadata,
getPropertyMetadata,
getProviderName,
GRPCMetadata,
GrpcStreamTypeEnum,
listModule,
MS_GRPC_METHOD_KEY,
MS_PROVIDER_KEY,
MSProviderType,
Utils,
BaseFramework,
IMidwayBootstrapOptions,
MidwayCommonError,
MidwayFrameworkType,
MidwayInvokeForbiddenError,
} from '@midwayjs/core';
import {
Context,
IMidwayGRPCApplication,
IMidwayGRPFrameworkOptions,
} from '../interface';
import { loadProto } from '../util';
import { PackageDefinition } from '@grpc/proto-loader';
import type { EventEmitter } from 'events';
@Framework()
export class MidwayGRPCFramework extends BaseFramework<
IMidwayGRPCApplication,
Context,
IMidwayGRPFrameworkOptions
> {
public app: IMidwayGRPCApplication;
private server: Server;
@Config()
providerConfig;
configure() {
return this.configService.getConfiguration('grpcServer');
}
isEnable(): boolean {
return this.configurationOptions.services?.length > 0;
}
async applicationInitialize(options: Partial<IMidwayBootstrapOptions>) {
// set logger to grpc server
setLogger(this.logger);
const server: Server = new Server(
Object.assign(
{
'grpc.max_receive_message_length': -1,
'grpc.max_send_message_length': -1,
},
this.configurationOptions.serverOptions || {}
)
);
this.app = server as IMidwayGRPCApplication;
this.server = server;
}
protected async afterContainerReady(
options: Partial<IMidwayBootstrapOptions>
): Promise<void> {
await this.loadService();
}
protected async loadService() {
// find all code service
const gRPCModules = listModule(MS_PROVIDER_KEY, module => {
const info: GRPCMetadata.ProviderMetadata = getClassMetadata(
MS_PROVIDER_KEY,
module
);
return info.type === MSProviderType.GRPC;
});
this.logger.info(
`Find ${gRPCModules.length} class has gRPC provider decorator`
);
// get definition from proto file
const serviceClassDefinition: Map<string, PackageDefinition> = new Map();
for (const service of this.configurationOptions.services ?? []) {
const definitions = await loadProto({
protoPath: service.protoPath,
loaderOptions: this.configurationOptions.loaderOptions,
});
serviceClassDefinition.set(service.package, definitions);
}
// register method to service
for (const module of gRPCModules) {
const providerName = getProviderName(module);
const info: GRPCMetadata.ProviderMetadata = getClassMetadata(
MS_PROVIDER_KEY,
module
);
const classMetadata = info.metadata;
const serviceName =
classMetadata.serviceName || Utils.pascalCase(providerName);
if (serviceClassDefinition.has(classMetadata?.package)) {
const serviceInstance = {} as UntypedServiceImplementation;
const serviceDefinition: any = serviceClassDefinition.get(
classMetadata.package
)[`${classMetadata?.package}.${serviceName}`];
if (!serviceDefinition) {
throw new MidwayCommonError(
`${classMetadata?.package}.${serviceName} definition not found and init fail`
);
}
for (const method in serviceDefinition) {
serviceInstance[method] = async (
call: Parameters<UntypedHandleCall>[0],
callback?: sendUnaryData<any>
) => {
// merge ctx and call
const ctx = call as Context;
ctx.method = method;
this.app.createAnonymousContext(ctx);
// get metadata from decorator
const grpcMethodData: {
methodName: string;
type: GrpcStreamTypeEnum;
onEnd: string;
} = getPropertyMetadata(
MS_GRPC_METHOD_KEY,
module,
Utils.camelCase(method)
);
const isPassed = await this.app
.getFramework()
.runGuard(ctx, module, ctx.method);
if (!isPassed) {
throw new MidwayInvokeForbiddenError(ctx.method, module);
}
// get service from request container
const service = await ctx.requestContext.getAsync(module);
if (
grpcMethodData.type === GrpcStreamTypeEnum.DUPLEX ||
grpcMethodData.type === GrpcStreamTypeEnum.READABLE
) {
// listen data and trigger binding method
(call as EventEmitter).on('data', async data => {
await this.handleContextMethod({
service,
ctx,
callback,
data,
grpcMethodData,
});
});
(call as EventEmitter).on('end', async () => {
if (grpcMethodData.onEnd) {
try {
const endResult = await service[grpcMethodData.onEnd]();
callback && callback(null, endResult);
} catch (err) {
callback && callback(err);
}
}
});
} else {
// writable and base type will be got data directly
await this.handleContextMethod({
service,
ctx,
callback,
data: (call as ServerUnaryCall<any, any>).request,
grpcMethodData,
});
}
};
}
this.server.addService(serviceDefinition, serviceInstance);
this.logger.info(
`Proto ${classMetadata?.package}.${serviceName} found and add to gRPC server`
);
}
}
}
protected async handleContextMethod(options: {
service;
ctx: Context;
callback;
data: any;
grpcMethodData: {
methodName: string;
type: GrpcStreamTypeEnum;
onEnd: string;
};
}) {
const { ctx, callback, grpcMethodData } = options;
const fn = await this.applyMiddleware(async ctx => {
return await options.service[Utils.camelCase(ctx.method)]?.call(
options.service,
options.data
);
});
try {
const result = await fn(ctx);
if (grpcMethodData.type === GrpcStreamTypeEnum.BASE) {
// base 才返回,其他的要等服务端自己 end,或者等客户端 end 事件才结束
callback && callback(null, result);
}
} catch (err) {
callback && callback(err);
}
}
public async run(): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.server.bindAsync(
`${this.configurationOptions.url || '0.0.0.0:6565'}`,
this.configurationOptions.credentials ||
ServerCredentials.createInsecure(),
(err: Error | null, bindPort: number) => {
if (err) {
reject(err);
}
this.server.start();
this.logger.info(`Server port = ${bindPort} start success`);
resolve();
}
);
});
}
public async beforeStop() {
if (!this.server) {
return;
}
await new Promise<void>(resolve => {
const shutdownTimer = setTimeout(() => {
this.server.forceShutdown();
resolve();
}, 2000);
this.server.tryShutdown(err => {
clearTimeout(shutdownTimer);
if (err) {
this.logger.error(
'Server shutdown error and will invoke force shutdown, err=' +
err.message
);
this.server.forceShutdown();
resolve();
} else {
this.logger.info('Server shutdown success');
resolve();
}
});
});
}
public getFrameworkType(): MidwayFrameworkType {
return MidwayFrameworkType.MS_GRPC;
}
public getServer() {
return this.server;
}
public getFrameworkName() {
return 'midway:gRPC';
}
}