-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc-server.ts
149 lines (127 loc) · 4.51 KB
/
grpc-server.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
import { injectable, inject } from 'inversify';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import * as grpc from 'grpc';
import { Context } from './context';
import { Config } from './config';
import { Logger } from './logger';
import { ServiceResponse, ServiceHandlerFunction } from './service';
import { HealthManager } from './health';
import { ProtoConfig } from './proto-config';
export interface GrpcService {
grpcMethod: string;
handler: ServiceHandlerFunction;
}
interface UnaryCall {
cancelled: boolean;
metadata: any;
request: any;
}
interface MethodDefinition {
originalName: string;
path: string;
requestStream: boolean;
responseStream: boolean;
requestType: Object;
responseType: Object;
}
interface ServiceDefinition {
service: {
[method: string]: MethodDefinition;
};
}
interface MessageDefinition {
[key: string]: any;
}
interface ProtobufDefinition {
[service: string]: ServiceDefinition | MessageDefinition; // reality it's either message or service entries
}
interface PackagedProtobufDefinition {
[packageName: string]: ProtobufDefinition;
}
type CallbackFn = (error: string | null, content: string | null) => any;
type HandlerFn = (call: UnaryCall, callback: CallbackFn) => any;
interface GrpcImplementation {
[methodName: string]: HandlerFn;
};
@injectable()
export class GrpcServer {
private server: any;
private services: GrpcImplementation = {};
private proto: PackagedProtobufDefinition | ProtobufDefinition;
private health = new BehaviorSubject(false);
constructor(
@inject('protoconfig') private protoConfig: ProtoConfig,
private config: Config,
private logger: Logger,
private healthManager: HealthManager
) {
this.healthManager.registerCheck('GRPC server', this.health);
this.proto = grpc.load(this.protoConfig.path);
}
public registerService(service: GrpcService) {
const serviceName = this.normalizeServiceName(service.grpcMethod);
this.logger.info(`Registering GRPC service: ${serviceName}`);
if (!this.service[serviceName]) {
throw new Error(`Trying to register unknown GRPC method: ${serviceName}`)
}
// Setup handler
const handler: HandlerFn = (call, callback) => {
this.logger.info(`GRPC request started ${serviceName}`);
const context = this.createContext(call.metadata);
service.handler(context, call.request)
.then((response: ServiceResponse | void) => {
if (!response) {
throw new Error('Empty response returned');
}
callback(null, response.content);
})
.catch((response: ServiceResponse) => {
this.logger.error(response.content);
callback(response.content, null);
});
};
this.services[serviceName] = handler;
}
private checkMissingServices(): void {
const missingServices: Array<string> = Object.keys(this.service)
.filter(propertyKey => this.service.hasOwnProperty(propertyKey))
.filter(method => this.services[method] === undefined);
if (missingServices.length > 0) {
throw new Error(`Missing GRPC implementation of services: ${JSON.stringify(missingServices.toString())}`);
}
}
public start(): void {
this.checkMissingServices();
this.server = new grpc.Server();
this.server.addService(this.service, this.services);
this.server.bind(`0.0.0.0:${(<any>this.config)['grpcPort']}`, grpc.ServerCredentials.createInsecure());
this.server.start();
this.logger.info(`Grpc server started listening on: ${(<any>this.config)['grpcPort']}`);
// Notify the server is healhty
this.health.next(true);
}
private get service() {
let definition: ProtobufDefinition;
if (this.protoConfig.package) {
definition = this.proto[this.protoConfig.package];
} else {
definition = this.proto;
}
return (<ServiceDefinition>definition[this.protoConfig.service]).service
}
private createContext(metadata: Map<string, any>): Context {
return {
token: (metadata.get('authorization')[0] || '').split('Token ')[1],
requestId: metadata.get('request-id')[0],
user: metadata.get('remoteuser')[0]
}
}
// A small method to normalize names of the gRPC calls. This is
// required since all 'CapitalizedMethodNames' defined in protobuf
// will be turned into 'camelCasedMethodNames' by grpc library by
// default. As a convenience for the user of this class we do the
// conversion under the hood.
private normalizeServiceName(name: string): string {
return name[0].toLowerCase() + name.slice(1);
}
}