UNPKG

13.2 kBJavaScriptView Raw
1/**
2 * @license
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19'use strict';
20
21var path = require('path');
22var fs = require('fs');
23var util = require('util');
24
25var SSL_ROOTS_PATH = path.resolve(__dirname, 'deps', 'grpc', 'etc', 'roots.pem');
26
27var client = require('./src/client.js');
28
29var server = require('./src/server.js');
30
31var common = require('./src/common.js');
32
33var Metadata = require('./src/metadata.js');
34
35var grpc = require('./src/grpc_extension');
36
37var protobuf_js_5_common = require('./src/protobuf_js_5_common');
38var protobuf_js_6_common = require('./src/protobuf_js_6_common');
39
40var constants = require('./src/constants.js');
41
42grpc.setDefaultRootsPem(fs.readFileSync(SSL_ROOTS_PATH, 'ascii'));
43
44/**
45 * @namespace grpc
46 */
47
48/**
49 * Load a ProtoBuf.js object as a gRPC object.
50 * @memberof grpc
51 * @alias grpc.loadObject
52 * @param {Object} value The ProtoBuf.js reflection object to load
53 * @param {Object=} options Options to apply to the loaded file
54 * @param {bool=} [options.binaryAsBase64=false] deserialize bytes values as
55 * base64 strings instead of Buffers
56 * @param {bool=} [options.longsAsStrings=true] deserialize long values as
57 * strings instead of objects
58 * @param {bool=} [options.enumsAsStrings=true] deserialize enum values as
59 * strings instead of numbers. Only works with Protobuf.js 6 values.
60 * @param {bool=} [options.deprecatedArgumentOrder=false] use the beta method
61 * argument order for client methods, with optional arguments after the
62 * callback. This option is only a temporary stopgap measure to smooth an
63 * API breakage. It is deprecated, and new code should not use it.
64 * @param {(number|string)=} [options.protobufjsVersion='detect'] 5 and 6
65 * respectively indicate that an object from the corresponding version of
66 * Protobuf.js is provided in the value argument. If the option is 'detect',
67 * gRPC will guess what the version is based on the structure of the value.
68 * @return {Object<string, *>} The resulting gRPC object.
69 */
70exports.loadObject = function loadObject(value, options) {
71 options = Object.assign({}, common.defaultGrpcOptions, options);
72 options = Object.assign({}, {'protobufjsVersion': 'detect'}, options);
73 var protobufjsVersion;
74 if (options.protobufjsVersion === 'detect') {
75 if (protobuf_js_6_common.isProbablyProtobufJs6(value)) {
76 protobufjsVersion = 6;
77 } else if (protobuf_js_5_common.isProbablyProtobufJs5(value)) {
78 protobufjsVersion = 5;
79 } else {
80 var error_message = 'Could not detect ProtoBuf.js version. Please ' +
81 'specify the version number with the "protobufjsVersion" option';
82 throw new Error(error_message);
83 }
84 } else {
85 protobufjsVersion = options.protobufjsVersion;
86 }
87 switch (protobufjsVersion) {
88 case 6: return protobuf_js_6_common.loadObject(value, options);
89 case 5:
90 return protobuf_js_5_common.loadObject(value, options);
91 default:
92 throw new Error('Unrecognized protobufjsVersion', protobufjsVersion);
93 }
94};
95
96var loadObject = exports.loadObject;
97
98/**
99 * Load a gRPC object from a .proto file.
100 * @deprecated Use the {@link https://www.npmjs.com/package/@grpc/proto-loader|proto-loader module}
101 with grpc.loadPackageDefinition instead.
102 * @memberof grpc
103 * @alias grpc.load
104 * @param {string|{root: string, file: string}} filename The file to load
105 * @param {string=} format The file format to expect. Must be either 'proto' or
106 * 'json'. Defaults to 'proto'
107 * @param {Object=} options Options to apply to the loaded file
108 * @param {bool=} [options.convertFieldsToCamelCase=false] Load this file with
109 * field names in camel case instead of their original case
110 * @param {bool=} [options.binaryAsBase64=false] deserialize bytes values as
111 * base64 strings instead of Buffers
112 * @param {bool=} [options.longsAsStrings=true] deserialize long values as
113 * strings instead of objects
114 * @param {bool=} [options.deprecatedArgumentOrder=false] use the beta method
115 * argument order for client methods, with optional arguments after the
116 * callback. This option is only a temporary stopgap measure to smooth an
117 * API breakage. It is deprecated, and new code should not use it.
118 * @return {Object<string, *>} The resulting gRPC object
119 */
120exports.load = util.deprecate(function load(filename, format, options) {
121 const ProtoBuf = require('protobufjs');
122 options = Object.assign({}, common.defaultGrpcOptions, options);
123 options.protobufjsVersion = 5;
124 if (!format) {
125 format = 'proto';
126 }
127 var convertFieldsToCamelCaseOriginal = ProtoBuf.convertFieldsToCamelCase;
128 if(options && options.hasOwnProperty('convertFieldsToCamelCase')) {
129 ProtoBuf.convertFieldsToCamelCase = options.convertFieldsToCamelCase;
130 }
131 var builder;
132 try {
133 switch(format) {
134 case 'proto':
135 builder = ProtoBuf.loadProtoFile(filename);
136 break;
137 case 'json':
138 builder = ProtoBuf.loadJsonFile(filename);
139 break;
140 default:
141 throw new Error('Unrecognized format "' + format + '"');
142 }
143 } finally {
144 ProtoBuf.convertFieldsToCamelCase = convertFieldsToCamelCaseOriginal;
145 }
146
147 if (!builder) {
148 throw new Error('Could not load file "' + filename + '"');
149 }
150
151 return loadObject(builder.ns, options);
152}, 'grpc.load: Use the @grpc/proto-loader module with grpc.loadPackageDefinition instead');
153
154/**
155 * Load a gRPC package definition as a gRPC object hierarchy
156 * @param packageDef grpc~PackageDefinition The package definition object
157 * @return {Object<string, *>} The resulting gRPC object
158 */
159exports.loadPackageDefinition = function loadPackageDefintion(packageDef) {
160 const result = {};
161 for (const serviceFqn in packageDef) {
162 const service = packageDef[serviceFqn];
163 const nameComponents = serviceFqn.split('.');
164 const serviceName = nameComponents[nameComponents.length-1];
165 let current = result;
166 for (const packageName of nameComponents.slice(0, -1)) {
167 if (!current[packageName]) {
168 current[packageName] = {};
169 }
170 current = current[packageName];
171 }
172 if (service.hasOwnProperty('format')) {
173 current[serviceName] = service;
174 } else {
175 current[serviceName] = client.makeClientConstructor(service, serviceName, {});
176 }
177 }
178 return result;
179};
180
181var log_template = function(args) {
182 var file = args.file;
183 var line = args.line;
184 var severity = args.severity;
185 var message = args.message;
186 var timestamp = args.timestamp;
187 return `${severity} ${timestamp}\t${file}:${line}]\t${message}`;
188};
189
190/**
191 * Sets the logger function for the gRPC module. For debugging purposes, the C
192 * core will log synchronously directly to stdout unless this function is
193 * called. Note: the output format here is intended to be informational, and
194 * is not guaranteed to stay the same in the future.
195 * Logs will be directed to logger.error.
196 * @memberof grpc
197 * @alias grpc.setLogger
198 * @param {Console} logger A Console-like object.
199 */
200exports.setLogger = function setLogger(logger) {
201 common.logger = logger;
202 grpc.setDefaultLoggerCallback(function(file, line, severity,
203 message, timestamp) {
204 logger.error(log_template({
205 file: path.basename(file),
206 line: line,
207 severity: severity,
208 message: message,
209 timestamp: timestamp.toISOString()
210 }));
211 });
212};
213
214/**
215 * Sets the logger verbosity for gRPC module logging. The options are members
216 * of the grpc.logVerbosity map.
217 * @memberof grpc
218 * @alias grpc.setLogVerbosity
219 * @param {Number} verbosity The minimum severity to log
220 */
221exports.setLogVerbosity = function setLogVerbosity(verbosity) {
222 common.logVerbosity = verbosity;
223 grpc.setLogVerbosity(verbosity);
224};
225
226exports.Server = server.Server;
227
228exports.Metadata = Metadata;
229
230exports.status = constants.status;
231
232exports.propagate = constants.propagate;
233
234exports.callError = constants.callError;
235
236exports.writeFlags = constants.writeFlags;
237
238exports.logVerbosity = constants.logVerbosity;
239
240exports.methodTypes = constants.methodTypes;
241
242exports.connectivityState = constants.connectivityState;
243
244exports.credentials = require('./src/credentials.js');
245
246/**
247 * ServerCredentials factories
248 * @constructor ServerCredentials
249 * @memberof grpc
250 */
251exports.ServerCredentials = grpc.ServerCredentials;
252
253/**
254 * Create insecure server credentials
255 * @name grpc.ServerCredentials.createInsecure
256 * @kind function
257 * @return {grpc.ServerCredentials}
258 */
259
260/**
261 * A private key and certificate pair
262 * @typedef {Object} grpc.ServerCredentials~keyCertPair
263 * @property {Buffer} private_key The server's private key
264 * @property {Buffer} cert_chain The server's certificate chain
265 */
266
267/**
268 * Create SSL server credentials
269 * @name grpc.ServerCredentials.createSsl
270 * @kind function
271 * @param {?Buffer} rootCerts Root CA certificates for validating client
272 * certificates
273 * @param {Array<grpc.ServerCredentials~keyCertPair>} keyCertPairs A list of
274 * private key and certificate chain pairs to be used for authenticating
275 * the server
276 * @param {boolean} [checkClientCertificate=false] Indicates that the server
277 * should request and verify the client's certificates
278 * @return {grpc.ServerCredentials}
279 */
280
281exports.makeGenericClientConstructor = client.makeClientConstructor;
282
283exports.getClientChannel = client.getClientChannel;
284
285exports.waitForClientReady = client.waitForClientReady;
286
287exports.StatusBuilder = client.StatusBuilder;
288exports.ListenerBuilder = client.ListenerBuilder;
289exports.RequesterBuilder = client.RequesterBuilder;
290exports.InterceptingCall = client.InterceptingCall;
291
292/**
293 * @memberof grpc
294 * @alias grpc.closeClient
295 * @param {grpc.Client} client_obj The client to close
296 */
297exports.closeClient = function closeClient(client_obj) {
298 client.Client.prototype.close.apply(client_obj);
299};
300
301exports.Client = client.Client;
302
303/**
304 * @typedef {Object.<string, string | number>} grpc~ChannelOptions
305 */
306
307/**
308 * This constructor API is almost identical to the Client constructor,
309 * except that some of the options for the Client constructor are not valid
310 * here.
311 * @constructor Channel
312 * @memberof grpc
313 * @param {string} target The address of the server to connect to
314 * @param {grpc.ChannelCredentials} credentials Channel credentials to use when connecting
315 * @param {grpc~ChannelOptions} options A map of channel options that will be passed to the core
316 */
317exports.Channel = grpc.Channel;
318
319/**
320 * Close the channel. This has the same functionality as the existing grpc.Client#close
321 * @name grpc.Channel#close
322 * @kind function
323 */
324
325/**
326 * Return the target that this channel connects to
327 * @name grpc.Channel#getTarget
328 * @kind function
329 * @return {string} The target
330 */
331
332/**
333 * Get the channel's current connectivity state.
334 * @name grpc.Channel#getConnectivityState
335 * @kind function
336 * @param {boolean} tryToConnect If true, the channel will start connecting if it is
337 * idle. Otherwise, idle channels will only start connecting when a
338 * call starts.
339 * @return {grpc.connectivityState} The current connectivity state
340 */
341
342/**
343 * @callback grpc.Channel~watchConnectivityStateCallback
344 * @param {Error?} error
345 */
346
347/**
348 * Watch for connectivity state changes.
349 * @name grpc.Channel#watchConnectivityState
350 * @kind function
351 * @param {grpc.ConnectivityState} currentState The state to watch for
352 * transitions from. This should always be populated by calling
353 * getConnectivityState immediately before.
354 * @param {grpc~Deadline} deadline A deadline for waiting for a state change
355 * @param {grpc.Channel~watchConnectivityStateCallback} callback Called with no
356 * error when the state changes, or with an error if the deadline passes
357 * without a state change
358 */
359
360/**
361 * @name grpc~Call
362 * @kind class
363 */
364
365/**
366 * Create a call object. Call is an opaque type used by the {@link grpc.Client}
367 * and {@link grpc.Server} classes. This function is called by the gRPC library
368 * when starting a request. Implementers should return an instance of Call that
369 * is returned from calling createCall on an instance of the provided Channel
370 * class.
371 * @name grpc.Channel#createCall
372 * @kind function
373 * @param {string} method The full method string to request
374 * @param {grpc~Deadline} deadline The call deadline
375 * @param {string|null} host A host string override for making the request
376 * @param {grpc~Call|null} parentCall A server call to propagate some
377 * information from
378 * @param {number|null} propagateFlags A bitwise combination of elements of
379 * {@link grpc.propagate} that indicates what information to propagate
380 * from parentCall
381 * @return {grpc~Call}
382 */