Built motion from commit 44377920.|2.6.11
[motion2.git] / legacy-libs / grpc-cloned / index.js
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
21 var path = require('path');
22 var fs = require('fs');
23 var util = require('util');
24
25 var SSL_ROOTS_PATH = path.resolve(__dirname, 'deps', 'grpc', 'etc', 'roots.pem');
26
27 var client = require('./src/client.js');
28
29 var server = require('./src/server.js');
30
31 var common = require('./src/common.js');
32
33 var Metadata = require('./src/metadata.js');
34
35 var grpc = require('./src/grpc_extension');
36
37 var protobuf_js_5_common = require('./src/protobuf_js_5_common');
38 var protobuf_js_6_common = require('./src/protobuf_js_6_common');
39
40 var constants = require('./src/constants.js');
41
42 grpc.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  */
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;
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
96 var 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  */
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;
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  */
159 exports.loadPackageDefinition = function loadPackageDefintion(packageDef) {
160   const result = {};
161   for (const serviceFqn in packageDef) {
162     const service = packageDef[serviceFqn];
163     const nameComponents = serviceFqn.split('.');
164     if (nameComponents.some(comp => common.isPrototypePolluted(comp))) {
165       continue;
166     }
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] = {};
172       }
173       current = current[packageName];
174     }
175     if (service.hasOwnProperty('format')) {
176       current[serviceName] = service;
177     } else {
178       current[serviceName] = client.makeClientConstructor(service, serviceName, {});
179     }
180   }
181   return result;
182 };
183
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}`;
191 };
192
193 /**
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.
199  * @memberof grpc
200  * @alias grpc.setLogger
201  * @param {Console} logger A Console-like object.
202  */
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),
209       line: line,
210       severity: severity,
211       message: message,
212       timestamp: timestamp.toISOString()
213     }));
214   });
215 };
216
217 /**
218  * Sets the logger verbosity for gRPC module logging. The options are members
219  * of the grpc.logVerbosity map.
220  * @memberof grpc
221  * @alias grpc.setLogVerbosity
222  * @param {Number} verbosity The minimum severity to log
223  */
224 exports.setLogVerbosity = function setLogVerbosity(verbosity) {
225   common.logVerbosity = verbosity;
226   grpc.setLogVerbosity(verbosity);
227 };
228
229 exports.Server = server.Server;
230
231 exports.Metadata = Metadata;
232
233 exports.status = constants.status;
234
235 exports.propagate = constants.propagate;
236
237 exports.callError = constants.callError;
238
239 exports.writeFlags = constants.writeFlags;
240
241 exports.logVerbosity = constants.logVerbosity;
242
243 exports.methodTypes = constants.methodTypes;
244
245 exports.connectivityState = constants.connectivityState;
246
247 exports.credentials = require('./src/credentials.js');
248
249 /**
250  * ServerCredentials factories
251  * @constructor ServerCredentials
252  * @memberof grpc
253  */
254 exports.ServerCredentials = grpc.ServerCredentials;
255
256 /**
257  * Create insecure server credentials
258  * @name grpc.ServerCredentials.createInsecure
259  * @kind function
260  * @return {grpc.ServerCredentials}
261  */
262
263 /**
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
268  */
269
270 /**
271  * Create SSL server credentials
272  * @name grpc.ServerCredentials.createSsl
273  * @kind function
274  * @param {?Buffer} rootCerts Root CA certificates for validating client
275  *     certificates
276  * @param {Array<grpc.ServerCredentials~keyCertPair>} keyCertPairs A list of
277  *     private key and certificate chain pairs to be used for authenticating
278  *     the server
279  * @param {boolean} [checkClientCertificate=false] Indicates that the server
280  *     should request and verify the client's certificates
281  * @return {grpc.ServerCredentials}
282  */
283
284 exports.makeGenericClientConstructor = client.makeClientConstructor;
285
286 exports.getClientChannel = client.getClientChannel;
287
288 exports.waitForClientReady = client.waitForClientReady;
289
290 exports.StatusBuilder = client.StatusBuilder;
291 exports.ListenerBuilder = client.ListenerBuilder;
292 exports.RequesterBuilder = client.RequesterBuilder;
293 exports.InterceptingCall = client.InterceptingCall;
294
295 /**
296  * @memberof grpc
297  * @alias grpc.closeClient
298  * @param {grpc.Client} client_obj The client to close
299  */
300 exports.closeClient = function closeClient(client_obj) {
301   client.Client.prototype.close.apply(client_obj);
302 };
303
304 exports.Client = client.Client;
305
306 /**
307  * @typedef {Object.<string, string | number>} grpc~ChannelOptions
308  */
309
310 /**
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
313  * here.
314  * @constructor Channel
315  * @memberof grpc
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}.
321  */
322 exports.Channel = grpc.Channel;
323
324 /**
325  * Close the channel. This has the same functionality as the existing grpc.Client#close
326  * @name grpc.Channel#close
327  * @kind function
328  */
329
330 /**
331  * Return the target that this channel connects to
332  * @name grpc.Channel#getTarget
333  * @kind function
334  * @return {string} The target
335  */
336
337 /**
338  * Get the channel's current connectivity state.
339  * @name grpc.Channel#getConnectivityState
340  * @kind function
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
343  *     call starts.
344  * @return {grpc.connectivityState} The current connectivity state
345  */
346
347 /**
348  * @callback grpc.Channel~watchConnectivityStateCallback
349  * @param {Error?} error
350  */
351
352 /**
353  * Watch for connectivity state changes.
354  * @name grpc.Channel#watchConnectivityState
355  * @kind function
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
363  */
364
365 /**
366  * @name grpc~Call
367  * @kind class
368  */
369
370 /**
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
375  * class.
376  * @name grpc.Channel#createCall
377  * @kind function
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
382  *     information from
383  * @param {number|null} propagateFlags A bitwise combination of elements of
384  *     {@link grpc.propagate} that indicates what information to propagate
385  *     from parentCall
386  * @return {grpc~Call}
387  */