-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathGrpcServiceClient.js
More file actions
279 lines (256 loc) · 9.46 KB
/
GrpcServiceClient.js
File metadata and controls
279 lines (256 loc) · 9.46 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
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
/**
* @license
* Copyright 2019-2020 CERN and copyright holders of ALICE O2.
* See http://alice-o2.web.cern.ch/copyright for details of the copyright holders.
* All rights not expressly granted are reserved.
*
* This software is distributed under the terms of the GNU General Public
* License v3 (GPL Version 3), copied verbatim in the file "COPYING".
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
// Doc: https://grpc.io/docs/languages/node/
const protoLoader = require('@grpc/proto-loader');
const grpcLibrary = require('@grpc/grpc-js');
const {LogManager, ServiceUnavailableError, InvalidInputError} = require('@aliceo2/web-ui');
const RECONNECT_DELTA_TIME = 1000; // 1 second
/**
* @class GrpcServiceClient
* @description
* A wrapper class which manages a gRPC client connection and its respective calls. This class provides:
* - Automatic connection handling with retry logic.
* - Dynamic method binding for gRPC service methods defined in the proto file.
* - Promisified gRPC calls for easier asynchronous handling.
* - Connection state monitoring and error logging.
*
* @example
* const client = new GrpcServiceClient(config, protoPath);
* try {
* client.someMethod({ arg1: 'value' });
* console.log(response);
* } catch(error){
* console.error(error);
* }
*/
class GrpcServiceClient {
/**
* Create gRPC client and sets the methods identified in the provided path of protofile
* https://grpc.io/grpc/node/grpc.Client.html
* @param {object} config - Configuration for the gRPC client.
* @param {string} config.hostname - The hostname of the gRPC server.
* @param {number} config.port - The port of the gRPC server.
* @param {string} config.label - The service label defined in the proto file.
* @param {string} config.package - The package name defined in the proto file.
* @param {number} [config.timeout=30000] - Timeout for gRPC calls in milliseconds.
* @param {number} [config.connectionTimeout=10000] - Timeout for establishing a connection in milliseconds.
* @param {number} [config.maxMessageLength=50] - Maximum message size allowed in MB.
* @param {string} protoPath - Path to the proto file defining the gRPC service.
*/
constructor(config, path) {
this._logger = LogManager.getLogger(`${process.env.npm_config_log_label ?? 'cog'}/GrpcServiceClient`);
this._isConnectionReady = false;
this._connectionError = null;
if (this._isConfigurationValid(config, path)) {
this._label = config.label;
this._package = config.package;
this._timeout = config.timeout ?? 30000;
this._connectionTimeout = config.connectionTimeout ?? 10000;
this._retryConnectionInterval = this._connectionTimeout + RECONNECT_DELTA_TIME;
this._maxMessageLength = config.maxMessageLength ?? 50;
const address = `${config.hostname}:${config.port}`;
const packageDefinition = protoLoader.loadSync(path, {longs: String, keepCase: true, arrays: true});
const octlProto = grpcLibrary.loadPackageDefinition(packageDefinition);
const protoService = octlProto[this._package][this._label];
const credentials = grpcLibrary.credentials.createInsecure();
const options = {'grpc.max_receive_message_length': 1024 * 1024 * this._maxMessageLength}; // MB
this.client = new protoService(address, credentials, options);
this._establishConnectionWithRetry(address);
this._initializeMethods(protoService);
} else {
this._connectionError = new InvalidInputError('Invalid configuration for gRPC client');
}
}
/**
* Bind an exposed gRPC service to the current object, promisify it and add default options like deadline.
* @private
* @param {string} methodName - gRPC method to be added to `this`
* @returns {string} - The method name
*/
_getAndSetPromisifiedMethod(methodName) {
/**
* Definition of each call that can be made based on the proto file definition
* @param {JSON} args - arguments to be passed to gRPC Server
* @param {JSON} options - metadata for gRPC call such as deadline
* @returns
*/
this[methodName] = (args = {}, options = {deadline: Date.now() + this._timeout}) => {
return new Promise((resolve, reject) => {
this.client[methodName](args, options, (error, response) => {
if (error) {
reject(error);
}
resolve(response);
});
});
};
return methodName;
}
/**
* Checks if configuration provided for gRPC Connection is valid
* @param {JSON} config
* @param {String} path - location of gRPC file containing API
*/
_isConfigurationValid(config, path) {
let isValid = true;
if (!config.hostname) {
this._logger.errorMessage('Missing configuration: hostname');
isValid = false;
}
if (!config.port) {
this._logger.errorMessage('Missing configuration: port');
isValid = false;
}
if (!path) {
this._logger.errorMessage('Missing path for gRPC API declaration');
isValid = false;
}
if (!config.label) {
this._logger.errorMessage('Missing service label for gRPC API');
isValid = false;
}
if (!config.package) {
this._logger.errorMessage('Missing service package for gRPC API');
isValid = false;
}
return isValid;
}
/**
* Method to log an error or success message when attempting to connect to the gRPC server
* @private
* @param {Error} error - error following attempt to connect to gRPC server
* @param {string} address - address on which connection was attempted
*/
_handleConnectionStatus(error, address) {
if (error) {
this._logger.errorMessage(`Connection to ${this._label} server (${address}) failed due to: ${error}`);
this.connectionError = error;
this.isConnectionReady = false;
} else {
this._logger.infoMessage(`${this._label} gRPC connected to ${address}`);
this.connectionError = null;
this.isConnectionReady = true;
}
}
/**
* Initialize gRPC methods and bind them to the instance:
* - Filter out methods starting with $ (private)
* - Filter out methods starting with lowercase (not a method)
* - Bind the method to the instance
* - Promisify the method
* - Add default options (deadline)
* @private
* @param {Object} protoService - The gRPC service definition
* @returns {void}
*/
_initializeMethods(protoService) {
this.methods = Object.keys(protoService.prototype)
.filter((method) =>
method.charAt(0) !== '$'
&& method.charAt(0) === method.charAt(0).toUpperCase()
&& typeof protoService.prototype[method] === 'function')
.map((method) => this._getAndSetPromisifiedMethod(method));
}
/**
* Attempt to establish a first connection to the gRPC server with retry logic in case of failure
* @private
* @param {string} address - Address of the gRPC server
* @returns {void}
*/
_establishConnectionWithRetry(address) {
/**
* Method to attempt to connect to the gRPC server
* @private
* @returns {void}
*/
const tryConnect = () => {
this.client.waitForReady(Date.now() + this._connectionTimeout, (error) => {
if (error) {
this._handleConnectionStatus(error, address);
setTimeout(tryConnect, this._retryConnectionInterval);
} else {
this._handleConnectionStatus(null, address);
this._monitorChannelStateAndReconnect();
}
});
};
tryConnect();
}
/**
* Monitor the state of the gRPC channel and trigger the reconnection logic if necessary
* @private
* @returns {void}
*/
_monitorChannelStateAndReconnect() {
const channel = this.client.getChannel();
/**
* Method to check the state of the gRPC channel and attempt to reconnect if necessary
* @private
* @returns {void}
*/
const checkState = () => {
try {
const currentState = channel.getConnectivityState(true);
if (
currentState !== grpcLibrary.connectivityState.READY
&& currentState !== grpcLibrary.connectivityState.IDLE
&& currentState !== grpcLibrary.connectivityState.CONNECTING
) {
this._handleConnectionStatus(
new ServiceUnavailableError(`Channel state changed to ${grpcLibrary.connectivityState[currentState]}`),
channel.getTarget()
);
this._establishConnectionWithRetry(channel.getTarget());
return;
}
channel.watchConnectivityState(currentState, Date.now() + this._connectionTimeout, checkState);
} catch (error) {
this._logger.errorMessage(`Error while monitoring channel state: ${error.message}`);
}
};
checkState();
}
/*
* Getters & Setters
*/
/**
* Get the status of the connection to gRPC
* @return {boolean}
*/
get isConnectionReady() {
return this._isConnectionReady;
}
/**
* Set the status of the connection to gRPC
* @param {boolean} connection
*/
set isConnectionReady(connection) {
this._isConnectionReady = connection;
}
/**
* Get the error of the connection if present.
* @return {Error}
*/
get connectionError() {
return this._connectionError;
}
/**
* Set an error for the connection to gRPC
* @param {Error} error
*/
set connectionError(error) {
this._connectionError = error;
}
}
module.exports = GrpcServiceClient;