3 * Copyright 2015 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 var path = require('path');
22 var fs = require('fs');
23 var util = require('util');
25 var SSL_ROOTS_PATH = path.resolve(__dirname, 'deps', 'grpc', 'etc', 'roots.pem');
27 var client = require('./src/client.js');
29 var server = require('./src/server.js');
31 var common = require('./src/common.js');
33 var Metadata = require('./src/metadata.js');
35 var grpc = require('./src/grpc_extension');
37 var protobuf_js_5_common = require('./src/protobuf_js_5_common');
38 var protobuf_js_6_common = require('./src/protobuf_js_6_common');
40 var constants = require('./src/constants.js');
42 grpc.setDefaultRootsPem(fs.readFileSync(SSL_ROOTS_PATH, 'ascii'));
49 * Load a ProtoBuf.js object as a gRPC object.
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.
70 exports.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;
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);
85 protobufjsVersion = options.protobufjsVersion;
87 switch (protobufjsVersion) {
88 case 6: return protobuf_js_6_common.loadObject(value, options);
90 return protobuf_js_5_common.loadObject(value, options);
92 throw new Error('Unrecognized protobufjsVersion', protobufjsVersion);
96 var loadObject = exports.loadObject;
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.
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
120 exports.load = util.deprecate(function load(filename, format, options) {
121 const ProtoBuf = require('protobufjs');
122 options = Object.assign({}, common.defaultGrpcOptions, options);
123 options.protobufjsVersion = 5;
127 var convertFieldsToCamelCaseOriginal = ProtoBuf.convertFieldsToCamelCase;
128 if(options && options.hasOwnProperty('convertFieldsToCamelCase')) {
129 ProtoBuf.convertFieldsToCamelCase = options.convertFieldsToCamelCase;
135 builder = ProtoBuf.loadProtoFile(filename);
138 builder = ProtoBuf.loadJsonFile(filename);
141 throw new Error('Unrecognized format "' + format + '"');
144 ProtoBuf.convertFieldsToCamelCase = convertFieldsToCamelCaseOriginal;
148 throw new Error('Could not load file "' + filename + '"');
151 return loadObject(builder.ns, options);
152 }, 'grpc.load: Use the @grpc/proto-loader module with grpc.loadPackageDefinition instead');
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
159 exports.loadPackageDefinition = function loadPackageDefintion(packageDef) {
161 for (const serviceFqn in packageDef) {
162 const service = packageDef[serviceFqn];
163 const nameComponents = serviceFqn.split('.');
164 if (nameComponents.some(comp => common.isPrototypePolluted(comp))) {
167 const serviceName = nameComponents[nameComponents.length-1];
168 let current = result;
169 for (const packageName of nameComponents.slice(0, -1)) {
170 if (!current[packageName]) {
171 current[packageName] = {};
173 current = current[packageName];
175 if (service.hasOwnProperty('format')) {
176 current[serviceName] = service;
178 current[serviceName] = client.makeClientConstructor(service, serviceName, {});
184 var log_template = function(args) {
185 var file = args.file;
186 var line = args.line;
187 var severity = args.severity;
188 var message = args.message;
189 var timestamp = args.timestamp;
190 return `${severity} ${timestamp}\t${file}:${line}]\t${message}`;
194 * Sets the logger function for the gRPC module. For debugging purposes, the C
195 * core will log synchronously directly to stdout unless this function is
196 * called. Note: the output format here is intended to be informational, and
197 * is not guaranteed to stay the same in the future.
198 * Logs will be directed to logger.error.
200 * @alias grpc.setLogger
201 * @param {Console} logger A Console-like object.
203 exports.setLogger = function setLogger(logger) {
204 common.logger = logger;
205 grpc.setDefaultLoggerCallback(function(file, line, severity,
206 message, timestamp) {
207 logger.error(log_template({
208 file: path.basename(file),
212 timestamp: timestamp.toISOString()
218 * Sets the logger verbosity for gRPC module logging. The options are members
219 * of the grpc.logVerbosity map.
221 * @alias grpc.setLogVerbosity
222 * @param {Number} verbosity The minimum severity to log
224 exports.setLogVerbosity = function setLogVerbosity(verbosity) {
225 common.logVerbosity = verbosity;
226 grpc.setLogVerbosity(verbosity);
229 exports.Server = server.Server;
231 exports.Metadata = Metadata;
233 exports.status = constants.status;
235 exports.propagate = constants.propagate;
237 exports.callError = constants.callError;
239 exports.writeFlags = constants.writeFlags;
241 exports.logVerbosity = constants.logVerbosity;
243 exports.methodTypes = constants.methodTypes;
245 exports.connectivityState = constants.connectivityState;
247 exports.credentials = require('./src/credentials.js');
250 * ServerCredentials factories
251 * @constructor ServerCredentials
254 exports.ServerCredentials = grpc.ServerCredentials;
257 * Create insecure server credentials
258 * @name grpc.ServerCredentials.createInsecure
260 * @return {grpc.ServerCredentials}
264 * A private key and certificate pair
265 * @typedef {Object} grpc.ServerCredentials~keyCertPair
266 * @property {Buffer} private_key The server's private key
267 * @property {Buffer} cert_chain The server's certificate chain
271 * Create SSL server credentials
272 * @name grpc.ServerCredentials.createSsl
274 * @param {?Buffer} rootCerts Root CA certificates for validating client
276 * @param {Array<grpc.ServerCredentials~keyCertPair>} keyCertPairs A list of
277 * private key and certificate chain pairs to be used for authenticating
279 * @param {boolean} [checkClientCertificate=false] Indicates that the server
280 * should request and verify the client's certificates
281 * @return {grpc.ServerCredentials}
284 exports.makeGenericClientConstructor = client.makeClientConstructor;
286 exports.getClientChannel = client.getClientChannel;
288 exports.waitForClientReady = client.waitForClientReady;
290 exports.StatusBuilder = client.StatusBuilder;
291 exports.ListenerBuilder = client.ListenerBuilder;
292 exports.RequesterBuilder = client.RequesterBuilder;
293 exports.InterceptingCall = client.InterceptingCall;
297 * @alias grpc.closeClient
298 * @param {grpc.Client} client_obj The client to close
300 exports.closeClient = function closeClient(client_obj) {
301 client.Client.prototype.close.apply(client_obj);
304 exports.Client = client.Client;
307 * @typedef {Object.<string, string | number>} grpc~ChannelOptions
311 * This constructor API is almost identical to the Client constructor,
312 * except that some of the options for the Client constructor are not valid
314 * @constructor Channel
316 * @param {string} target The address of the server to connect to
317 * @param {grpc.ChannelCredentials} credentials Channel credentials to use when connecting
318 * @param {grpc~ChannelOptions} options A map of channel options that will be passed to the core.
319 * The available options are listed in
320 * [this document]{@link https://grpc.github.io/grpc/core/group__grpc__arg__keys.html}.
322 exports.Channel = grpc.Channel;
325 * Close the channel. This has the same functionality as the existing grpc.Client#close
326 * @name grpc.Channel#close
331 * Return the target that this channel connects to
332 * @name grpc.Channel#getTarget
334 * @return {string} The target
338 * Get the channel's current connectivity state.
339 * @name grpc.Channel#getConnectivityState
341 * @param {boolean} tryToConnect If true, the channel will start connecting if it is
342 * idle. Otherwise, idle channels will only start connecting when a
344 * @return {grpc.connectivityState} The current connectivity state
348 * @callback grpc.Channel~watchConnectivityStateCallback
349 * @param {Error?} error
353 * Watch for connectivity state changes.
354 * @name grpc.Channel#watchConnectivityState
356 * @param {grpc.ConnectivityState} currentState The state to watch for
357 * transitions from. This should always be populated by calling
358 * getConnectivityState immediately before.
359 * @param {grpc~Deadline} deadline A deadline for waiting for a state change
360 * @param {grpc.Channel~watchConnectivityStateCallback} callback Called with no
361 * error when the state changes, or with an error if the deadline passes
362 * without a state change
371 * Create a call object. Call is an opaque type used by the {@link grpc.Client}
372 * and {@link grpc.Server} classes. This function is called by the gRPC library
373 * when starting a request. Implementers should return an instance of Call that
374 * is returned from calling createCall on an instance of the provided Channel
376 * @name grpc.Channel#createCall
378 * @param {string} method The full method string to request
379 * @param {grpc~Deadline} deadline The call deadline
380 * @param {string|null} host A host string override for making the request
381 * @param {grpc~Call|null} parentCall A server call to propagate some
383 * @param {number|null} propagateFlags A bitwise combination of elements of
384 * {@link grpc.propagate} that indicates what information to propagate
386 * @return {grpc~Call}