Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc-cloned / src / common.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 constants = require('./constants');
22
23 /**
24  * Wrap a function to pass null-like values through without calling it. If no
25  * function is given, just uses the identity.
26  * @private
27  * @param {?function} func The function to wrap
28  * @return {function} The wrapped function
29  */
30 exports.wrapIgnoreNull = function wrapIgnoreNull(func) {
31   if (!func) {
32     return x => x;
33   }
34   return function(arg) {
35     if (arg === null || arg === undefined) {
36       return null;
37     }
38     return func(arg);
39   };
40 };
41
42 /**
43  * The logger object for the gRPC module. Defaults to console.
44  * @private
45  */
46 exports.logger = console;
47
48 /**
49  * The current logging verbosity. 0 corresponds to logging everything
50  * @private
51  */
52 exports.logVerbosity = 0;
53
54 /**
55  * Log a message if the severity is at least as high as the current verbosity
56  * @private
57  * @param {Number} severity A value of the grpc.logVerbosity map
58  * @param {String} message The message to log
59  */
60 exports.log = function log(severity, message) {
61   if (severity >= exports.logVerbosity) {
62     exports.logger.error(message);
63   }
64 };
65
66 /**
67  * Default options for loading proto files into gRPC
68  * @alias grpc~defaultLoadOptions
69  */
70 exports.defaultGrpcOptions = {
71   convertFieldsToCamelCase: false,
72   binaryAsBase64: false,
73   longsAsStrings: true,
74   enumsAsStrings: true,
75   deprecatedArgumentOrder: false
76 };
77
78 /**
79  * Create an Error object from a status object
80  * @param {grpc~StatusObject} status The status object
81  * @return {Error} The resulting Error
82  */
83 exports.createStatusError = function(status) {
84   let inverted = Object.keys(constants.status)
85     .reduce((acc, key) => {
86       acc[constants.status[key]] = key;
87       return acc;
88     }, {});
89   let statusName = inverted[status.code];
90   let message = `${status.code} ${statusName}: ${status.details}`;
91   let error = new Error(message);
92   error.code = status.code;
93   error.metadata = status.metadata;
94   error.details = status.details;
95   return error;
96 };
97
98 /**
99  * Get a method's type from its definition
100  * @param {grpc~MethodDefinition} method_definition
101  * @return {number}
102  */
103 exports.getMethodType = function(method_definition) {
104   if (method_definition.requestStream) {
105     if (method_definition.responseStream) {
106       return constants.methodTypes.BIDI_STREAMING;
107     } else {
108       return constants.methodTypes.CLIENT_STREAMING;
109     }
110   } else {
111     if (method_definition.responseStream) {
112       return constants.methodTypes.SERVER_STREAMING;
113     } else {
114       return constants.methodTypes.UNARY;
115     }
116   }
117 };
118
119 /**
120  * Iterate over a collection of items, and run the given handler.
121  * Return the results as a flattened array of values.
122  *
123  * @private
124  *
125  * @param {Array} collection Array of items to process
126  * @param {Function} handler The function to call on each element in the array
127  * @return {Array} A flattened array of results.
128  */
129 exports.flatMap = function(collection, handler) {
130   const mapped = collection.map(handler);
131   return mapped.reduce((acc, curr) => acc.concat(curr), []);
132 }
133
134 /**
135  * Given an array of property names and an array of values,
136  * combine the two into an object map.
137  * Equivalent to _.zipObject.
138  *
139  * @private
140  *
141  * @param props {Array<String>} Array of property names
142  * @param values {Array} Array of property values
143  * @return {Object} An object with the combined values
144  */
145 exports.zipObject = function(props, values) {
146   return props.reduce((acc, curr, idx) => {
147     return Object.assign(acc, { [curr]: values[idx] });
148   }, {});
149 }
150
151 /**
152  * Returns true, if given key is included in the blacklisted
153  * keys.
154  * @param key {String} key for check, string.
155  * @return {Boolean}
156  */
157 exports.isPrototypePolluted = function(key) {
158   return ['__proto__', 'prototype', 'constructor'].indexOf(key) >= 0;
159 }
160
161 // JSDoc definitions that are used in multiple other modules
162
163 /**
164  * Represents the status of a completed request. If `code` is
165  * {@link grpc.status}.OK, then the request has completed successfully.
166  * Otherwise, the request has failed, `details` will contain a description of
167  * the error. Either way, `metadata` contains the trailing response metadata
168  * sent by the server when it finishes processing the call.
169  * @typedef {object} grpc~StatusObject
170  * @property {number} code The error code, a key of {@link grpc.status}
171  * @property {string} details Human-readable description of the status
172  * @property {grpc.Metadata} metadata Trailing metadata sent with the status,
173  *     if applicable
174  */
175
176 /**
177  * Describes how a request has failed. The member `message` will be the same as
178  * `details` in {@link grpc~StatusObject}, and `code` and `metadata` are the
179  * same as in that object.
180  * @typedef {Error} grpc~ServiceError
181  * @property {number} code The error code, a key of {@link grpc.status} that is
182  *     not `grpc.status.OK`
183  * @property {grpc.Metadata} metadata Trailing metadata sent with the status,
184  *     if applicable
185  */
186
187 /**
188  * The EventEmitter class in the event standard module
189  * @external EventEmitter
190  * @see https://nodejs.org/api/events.html#events_class_eventemitter
191  */
192
193 /**
194  * The Readable class in the stream standard module
195  * @external Readable
196  * @see https://nodejs.org/api/stream.html#stream_readable_streams
197  */
198
199 /**
200  * The Writable class in the stream standard module
201  * @external Writable
202  * @see https://nodejs.org/api/stream.html#stream_writable_streams
203  */
204
205 /**
206  * The Duplex class in the stream standard module
207  * @external Duplex
208  * @see https://nodejs.org/api/stream.html#stream_class_stream_duplex
209  */
210
211 /**
212  * A serialization function
213  * @callback grpc~serialize
214  * @param {*} value The value to serialize
215  * @return {Buffer} The value serialized as a byte sequence
216  */
217
218 /**
219  * A deserialization function
220  * @callback grpc~deserialize
221  * @param {Buffer} data The byte sequence to deserialize
222  * @return {*} The data deserialized as a value
223  */
224
225 /**
226  * The deadline of an operation. If it is a date, the deadline is reached at
227  * the date and time specified. If it is a finite number, it is treated as
228  * a number of milliseconds since the Unix Epoch. If it is Infinity, the
229  * deadline will never be reached. If it is -Infinity, the deadline has already
230  * passed.
231  * @typedef {(number|Date)} grpc~Deadline
232  */
233
234 /**
235  * An object that completely defines a service method signature.
236  * @typedef {Object} grpc~MethodDefinition
237  * @property {string} path The method's URL path
238  * @property {boolean} requestStream Indicates whether the method accepts
239  *     a stream of requests
240  * @property {boolean} responseStream Indicates whether the method returns
241  *     a stream of responses
242  * @property {grpc~serialize} requestSerialize Serialization
243  *     function for request values
244  * @property {grpc~serialize} responseSerialize Serialization
245  *     function for response values
246  * @property {grpc~deserialize} requestDeserialize Deserialization
247  *     function for request data
248  * @property {grpc~deserialize} responseDeserialize Deserialization
249  *     function for repsonse data
250  */
251
252 /**
253  * @function MetadataListener
254  * @param {grpc.Metadata} metadata The response metadata.
255  * @param {function} next Passes metadata to the next interceptor.
256  */
257
258 /**
259  * @function MessageListener
260  * @param {jspb.Message} message The response message.
261  * @param {function} next Passes a message to the next interceptor.
262  */
263
264 /**
265  * @function StatusListener
266  * @param {grpc~StatusObject} status The response status.
267  * @param {function} next Passes a status to the next interceptor.
268  */
269
270 /**
271  * A set of interceptor functions triggered by responses
272  * @typedef {object} grpc~Listener
273  * @property {MetadataListener=} onReceiveMetadata A function triggered by
274  *     response metadata.
275  * @property {MessageListener=} onReceiveMessage A function triggered by a
276  *     response message.
277  * @property {StatusListener=} onReceiveStatus A function triggered by a
278  *     response status.
279  */
280
281 /**
282  * @function MetadataRequester
283  * @param {grpc.Metadata} metadata The request metadata.
284  * @param {grpc~Listener} listener A listener wired to the previous layers
285  *     in the interceptor stack.
286  * @param {function} next Passes metadata and a listener to the next
287  *      interceptor.
288  */
289
290 /**
291  * @function MessageRequester
292  * @param {jspb.Message} message The request message.
293  * @param {function} next Passes a message to the next interceptor.
294  */
295
296 /**
297  * @function CloseRequester
298  * @param {function} next Calls the next interceptor.
299  */
300
301 /**
302  * @function CancelRequester
303  * @param {function} next Calls the next interceptor.
304  */
305
306 /**
307  * @function GetPeerRequester
308  * @param {function} next Calls the next interceptor.
309  * @return {string}
310  */
311
312 /**
313  * @typedef {object} grpc~Requester
314  * @param {MetadataRequester=} start A function triggered when the call begins.
315  * @param {MessageRequester=} sendMessage A function triggered by the request
316  *     message.
317  * @param {CloseRequester=} halfClose A function triggered when the client
318  *     closes the call.
319  * @param {CancelRequester=} cancel A function triggered when the call is
320  *     cancelled.
321  * @param {GetPeerRequester=} getPeer A function triggered when the endpoint is
322  *     requested.
323  */
324
325 /**
326  * An object that completely defines a service.
327  * @typedef {Object.<string, grpc~MethodDefinition>} grpc~ServiceDefinition
328  */
329
330  /**
331   * An object that defines a protobuf type
332   * @typedef {object} grpc~ProtobufTypeDefinition
333   * @param {string} format The format of the type definition object
334   * @param {*} type The type definition object
335   * @param {Buffer[]} fileDescriptorProtos Binary protobuf file
336   *     descriptors for all files loaded to construct this type
337   */
338
339 /**
340  * An object that defines a package hierarchy with multiple services
341  * @typedef {Object.<string, grpc~ServiceDefinition|grpc~ProtobufTypeDefinition>} grpc~PackageDefinition
342  */
343
344 /**
345  * A function for dynamically assigning an interceptor to a call.
346  * @function InterceptorProvider
347  * @param {grpc~MethodDefinition} method_definition The method to provide
348  *     an interceptor for.
349  * @return {Interceptor|null} The interceptor to provide or nothing
350  */
351
352 /**
353  * A function which can modify call options and produce methods to intercept
354  * RPC operations.
355  * @function Interceptor
356  * @param {object} options The grpc call options
357  * @param {NextCall} nextCall
358  * @return {InterceptingCall}
359  */
360
361 /**
362  * A function which produces the next InterceptingCall.
363  * @function NextCall
364  * @param {object} options The grpc call options
365  * @return {InterceptingCall|null}
366  */