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.
22 * This module contains the factory method for creating Client classes, and the
23 * method calling code for all types of methods.
25 * @example <caption>Create a client and call a method on it</caption>
27 * var proto_obj = grpc.load(proto_file_path);
28 * var Client = proto_obj.package.subpackage.ServiceName;
29 * var client = new Client(server_address, client_credentials);
30 * var call = client.unaryMethod(arguments, callback);
35 var client_interceptors = require('./client_interceptors');
36 var grpc = require('./grpc_extension');
38 var common = require('./common');
40 var Metadata = require('./metadata');
42 var constants = require('./constants');
44 var EventEmitter = require('events').EventEmitter;
46 var stream = require('stream');
48 var Readable = stream.Readable;
49 var Writable = stream.Writable;
50 var Duplex = stream.Duplex;
51 var methodTypes = constants.methodTypes;
52 var util = require('util');
53 var version = require('../package.json').version;
56 * Initial response metadata sent by the server when it starts processing the
58 * @event grpc~ClientUnaryCall#metadata
59 * @type {grpc.Metadata}
63 * Status of the call when it has completed.
64 * @event grpc~ClientUnaryCall#status
65 * @type grpc~StatusObject
68 util.inherits(ClientUnaryCall, EventEmitter);
71 * An EventEmitter. Used for unary calls.
72 * @constructor grpc~ClientUnaryCall
73 * @extends external:EventEmitter
74 * @param {grpc.internal~Call} call The call object associated with the request
76 function ClientUnaryCall(call) {
77 EventEmitter.call(this);
81 util.inherits(ClientWritableStream, Writable);
84 * A stream that the client can write to. Used for calls that are streaming from
86 * @constructor grpc~ClientWritableStream
87 * @extends external:Writable
88 * @borrows grpc~ClientUnaryCall#cancel as grpc~ClientWritableStream#cancel
89 * @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientWritableStream#getPeer
90 * @borrows grpc~ClientUnaryCall#event:metadata as
91 * grpc~ClientWritableStream#metadata
92 * @borrows grpc~ClientUnaryCall#event:status as
93 * grpc~ClientWritableStream#status
94 * @param {InterceptingCall} call Exposes gRPC request operations, processed by
95 * an interceptor stack.
97 function ClientWritableStream(call) {
98 Writable.call(this, {objectMode: true});
101 this.on('finish', function() {
102 self.call.halfClose();
107 * Write a message to the request stream. If serializing the argument fails,
108 * the call will be cancelled and the stream will end with an error.
109 * @name grpc~ClientWritableStream#write
112 * @param {*} message The message to write. Must be a valid argument to the
113 * serialize function of the corresponding method
114 * @param {grpc.writeFlags} flags Flags to modify how the message is written
115 * @param {Function} callback Callback for when this chunk of data is flushed
116 * @return {boolean} As defined for [Writable]{@link external:Writable}
120 * Attempt to write the given chunk. Calls the callback when done. This is an
121 * implementation of a method needed for implementing stream.Writable.
123 * @param {*} chunk The chunk to write
124 * @param {grpc.writeFlags} encoding Used to pass write flags
125 * @param {function(Error=)} callback Called when the write is complete
127 function _write(chunk, encoding, callback) {
128 /* jshint validthis: true */
130 if (this.writeFailed) {
131 /* Once a write fails, just call the callback immediately to let the caller
132 flush any pending writes. */
133 setImmediate(callback);
136 var outerCallback = function(err, event) {
138 /* Assume that the call is complete and that writing failed because a
139 status was received. In that case, set a flag to discard all future
141 self.writeFailed = true;
147 callback: outerCallback
149 this.call.sendMessageWithContext(context, chunk);
152 ClientWritableStream.prototype._write = _write;
154 util.inherits(ClientReadableStream, Readable);
157 * A stream that the client can read from. Used for calls that are streaming
158 * from the server side.
159 * @constructor grpc~ClientReadableStream
160 * @extends external:Readable
161 * @borrows grpc~ClientUnaryCall#cancel as grpc~ClientReadableStream#cancel
162 * @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientReadableStream#getPeer
163 * @borrows grpc~ClientUnaryCall#event:metadata as
164 * grpc~ClientReadableStream#metadata
165 * @borrows grpc~ClientUnaryCall#event:status as
166 * grpc~ClientReadableStream#status
167 * @param {InterceptingCall} call Exposes gRPC request operations, processed by
168 * an interceptor stack.
170 function ClientReadableStream(call) {
171 Readable.call(this, {objectMode: true});
173 this.finished = false;
174 this.reading = false;
175 /* Status generated from reading messages from the server. Overrides the
176 * status from the server if not OK */
177 this.read_status = null;
178 /* Status received from the server. */
179 this.received_status = null;
183 * Called when all messages from the server have been processed. The status
184 * parameter indicates that the call should end with that status. status
185 * defaults to OK if not provided.
186 * @param {Object!} status The status that the call should end with
189 function _readsDone(status) {
190 /* jshint validthis: true */
192 status = {code: constants.status.OK, details: 'OK'};
194 if (status.code !== constants.status.OK) {
195 this.call.cancelWithStatus(status.code, status.details);
197 this.finished = true;
198 this.read_status = status;
199 this._emitStatusIfDone();
202 ClientReadableStream.prototype._readsDone = _readsDone;
205 * Called to indicate that we have received a status from the server.
208 function _receiveStatus(status) {
209 /* jshint validthis: true */
210 this.received_status = status;
211 this._emitStatusIfDone();
214 ClientReadableStream.prototype._receiveStatus = _receiveStatus;
217 * If we have both processed all incoming messages and received the status from
218 * the server, emit the status. Otherwise, do nothing.
221 function _emitStatusIfDone() {
222 /* jshint validthis: true */
224 if (this.read_status && this.received_status) {
225 if (this.read_status.code !== constants.status.OK) {
226 status = this.read_status;
228 status = this.received_status;
230 if (status.code === constants.status.OK) {
233 var error = common.createStatusError(status);
234 this.emit('error', error);
236 this.emit('status', status);
240 ClientReadableStream.prototype._emitStatusIfDone = _emitStatusIfDone;
243 * Read the next object from the stream.
245 * @param {*} size Ignored because we use objectMode=true
247 function _read(size) {
248 /* jshint validthis: true */
257 this.call.recvMessageWithContext(context);
262 ClientReadableStream.prototype._read = _read;
264 util.inherits(ClientDuplexStream, Duplex);
267 * A stream that the client can read from or write to. Used for calls with
269 * @constructor grpc~ClientDuplexStream
270 * @extends external:Duplex
271 * @borrows grpc~ClientUnaryCall#cancel as grpc~ClientDuplexStream#cancel
272 * @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientDuplexStream#getPeer
273 * @borrows grpc~ClientWritableStream#write as grpc~ClientDuplexStream#write
274 * @borrows grpc~ClientUnaryCall#event:metadata as
275 * grpc~ClientDuplexStream#metadata
276 * @borrows grpc~ClientUnaryCall#event:status as
277 * grpc~ClientDuplexStream#status
278 * @param {InterceptingCall} call Exposes gRPC request operations, processed by
279 * an interceptor stack.
281 function ClientDuplexStream(call) {
282 Duplex.call(this, {objectMode: true});
284 /* Status generated from reading messages from the server. Overrides the
285 * status from the server if not OK */
286 this.read_status = null;
287 /* Status received from the server. */
288 this.received_status = null;
290 this.on('finish', function() {
291 self.call.halfClose();
295 ClientDuplexStream.prototype._readsDone = _readsDone;
296 ClientDuplexStream.prototype._receiveStatus = _receiveStatus;
297 ClientDuplexStream.prototype._emitStatusIfDone = _emitStatusIfDone;
298 ClientDuplexStream.prototype._read = _read;
299 ClientDuplexStream.prototype._write = _write;
302 * Cancel the ongoing call. Results in the call ending with a CANCELLED status,
303 * unless it has already ended with some other status.
304 * @alias grpc~ClientUnaryCall#cancel
307 /* jshint validthis: true */
311 ClientUnaryCall.prototype.cancel = cancel;
312 ClientReadableStream.prototype.cancel = cancel;
313 ClientWritableStream.prototype.cancel = cancel;
314 ClientDuplexStream.prototype.cancel = cancel;
317 * Get the endpoint this call/stream is connected to.
318 * @return {string} The URI of the endpoint
319 * @alias grpc~ClientUnaryCall#getPeer
322 /* jshint validthis: true */
323 return this.call.getPeer();
326 ClientUnaryCall.prototype.getPeer = getPeer;
327 ClientReadableStream.prototype.getPeer = getPeer;
328 ClientWritableStream.prototype.getPeer = getPeer;
329 ClientDuplexStream.prototype.getPeer = getPeer;
332 * Any client call type
333 * @typedef {(grpc~ClientUnaryCall|grpc~ClientReadableStream|
334 * grpc~ClientWritableStream|grpc~ClientDuplexStream)}
339 * Options that can be set on a call.
340 * @typedef {Object} grpc.Client~CallOptions
341 * @property {grpc~Deadline} deadline The deadline for the entire call to
343 * @property {string} host Server hostname to set on the call. Only meaningful
344 * if different from the server address used to construct the client.
345 * @property {grpc.Client~Call} parent Parent call. Used in servers when
346 * making a call as part of the process of handling a call. Used to
347 * propagate some information automatically, as specified by
349 * @property {number} propagate_flags Indicates which properties of a parent
350 * call should propagate to this call. Bitwise combination of flags in
351 * {@link grpc.propagate}.
352 * @property {grpc.credentials~CallCredentials} credentials The credentials that
353 * should be used to make this particular call.
357 * Properties of a call, for use with a {@link grpc.Client~callInvocationTransformer}.
358 * @typedef {Object} grpc.Client~CallProperties
359 * @property {*} argument The call argument. Only preset if the method is unary or server streaming.
360 * @property {grpc.Metadata} metadata The request metadata
361 * @property {grpc~Call} call The call object that will be returned by the client method
362 * @property {grpc.Channel} channel The channel that will be used to make a request
363 * @property {grpc~MethodDefinition} methodDefinition The MethodDefinition object that describes this method
364 * @property {grpc.Client~CallOptions} options The call options passed when making this request
365 * @property {grpc.Client~requestCallback} callback The callback that will handle the response.
366 * Only present if this method is unary or client streaming.
370 * Call invocation transformer. Has access to the full call properties before a
371 * call is processed and can modify most of those properties. Some modifications
372 * will have no effect or may cause problems.
373 * @name grpc.Client~callInvocationTransformer
375 * @param {grpc.Client~CallProperties} callProperties The original call properties
376 * @return {grpc.Client~CallProperties} The modified call properties.
380 * A function that functionally replaces the Channel constructor.
381 * @name grpc.Client~channelFactory
383 * @param {string} target The address of the server to connect to
384 * @param {grpc.ChannelCredentials} credentials Channel credentials to use when connecting
385 * @param {grpc~ChannelOptions} options A map of channel options that will be passed to the core.
386 * The available options are listed in
387 * [this document]{@link https://grpc.github.io/grpc/core/group__grpc__arg__keys.html}.
388 * @returns {grpc.Channel} This can either be an actual channel object, or an object with the
393 * A generic gRPC client. Primarily useful as a base class for generated clients
396 * @param {string} address Server address to connect to
397 * @param {grpc.credentials~ChannelCredentials} credentials Credentials to use
398 * to connect to the server
399 * @param {Object} options Options to apply to channel creation. Any of
400 * [the channel arguments]{@link https://grpc.github.io/grpc/core/group__grpc__arg__keys.html}
401 * can be used here in addition to specific client options.
402 * @param {grpc~Interceptor[]} [options.interceptors] Interceptors to apply to each request
403 * @param {grpc~InterceptorProvider[]} [options.interceptor_providers] Interceptor providers
404 * to apply interceptors to each request depending on the method definition. At most
405 * one of the interceptors and interceptor_providers options may be set.
406 * @param {grpc.Client~callInvocationTransformer=} options.callInvocationTransformer
407 * @param {grpc.Channel=} options.channelOverride Channel to use instead of constructing a new one.
408 * If set, the address, credentials, channel arguments options, and channelFactoryOverride
409 * option will all be ignored.
410 * @param {grpc.Client~channelFactory} options.channelFactoryOverride Function to use instead of
411 * the Channel constructor when creating the Client's channel.
413 function Client(address, credentials, options) {
419 // Resolve interceptor options and assign interceptors to each method
420 if (Array.isArray(options.interceptor_providers) && Array.isArray(options.interceptors)) {
421 throw new client_interceptors.InterceptorConfigurationError(
422 'Both interceptors and interceptor_providers were passed as options ' +
423 'to the client constructor. Only one of these is allowed.');
425 self.$interceptors = options.interceptors || [];
426 self.$interceptor_providers = options.interceptor_providers || [];
427 if (self.$method_definitions) {
428 Object.keys(self.$method_definitions).forEach(method_name => {
429 const method_definition = self.$method_definitions[method_name];
430 self[method_name].interceptors = client_interceptors
431 .resolveInterceptorProviders(self.$interceptor_providers, method_definition)
432 .concat(self.$interceptors);
436 this.$callInvocationTransformer = options.callInvocationTransformer;
438 let channelOverride = options.channelOverride;
439 let channelFactoryOverride = options.channelFactoryOverride;
440 // Exclude channel options which have already been consumed
441 const ignoredKeys = [
442 'interceptors', 'interceptor_providers', 'channelOverride',
443 'channelFactoryOverride', 'callInvocationTransformer'
445 var channel_options = Object.getOwnPropertyNames(options)
446 .reduce((acc, key) => {
447 if (ignoredKeys.indexOf(key) === -1) {
448 acc[key] = options[key];
452 /* Private fields use $ as a prefix instead of _ because it is an invalid
453 * prefix of a method name */
454 if (channelOverride) {
455 this.$channel = options.channelOverride;
457 if (channelFactoryOverride) {
458 this.$channel = channelFactoryOverride(address, credentials, channel_options);
460 this.$channel = new grpc.Channel(address, credentials, channel_options);
465 exports.Client = Client;
467 Client.prototype.resolveCallInterceptors = function(method_definition, interceptors, interceptor_providers) {
468 if (Array.isArray(interceptors) && Array.isArray(interceptor_providers)) {
469 throw new client_interceptors.InterceptorConfigurationError(
470 'Both interceptors and interceptor_providers were passed as call ' +
471 'options. Only one of these is allowed.');
473 if (Array.isArray(interceptors) || Array.isArray(interceptor_providers)) {
474 interceptors = interceptors || [];
475 interceptor_providers = interceptor_providers || [];
476 return client_interceptors.resolveInterceptorProviders(interceptor_providers, method_definition).concat(interceptors);
478 return client_interceptors.resolveInterceptorProviders(this.$interceptor_providers, method_definition).concat(this.$interceptors);
483 * @callback grpc.Client~requestCallback
484 * @param {?grpc~ServiceError} error The error, if the call
486 * @param {*} value The response value, if the call succeeded
490 * Make a unary request to the given method, using the given serialize
491 * and deserialize functions, with the given argument.
492 * @param {string} path The path of the method to request
493 * @param {grpc~serialize} serialize The serialization function for
495 * @param {grpc~deserialize} deserialize The deserialization
496 * function for outputs
497 * @param {*} argument The argument to the call. Should be serializable with
499 * @param {grpc.Metadata=} metadata Metadata to add to the call
500 * @param {grpc.Client~CallOptions=} options Options map
501 * @param {grpc.Client~requestCallback} callback The callback
502 * for when the response is received
503 * @return {grpc~ClientUnaryCall} An event emitter for stream related events
505 Client.prototype.makeUnaryRequest = function(path, serialize, deserialize,
506 argument, metadata, options,
508 if (typeof options === 'function') {
510 if (metadata instanceof Metadata) {
514 metadata = new Metadata();
516 } else if (typeof metadata === 'function') {
518 metadata = new Metadata();
522 metadata = new Metadata();
527 if (!((metadata instanceof Metadata) &&
528 (options instanceof Object) &&
529 (typeof callback === 'function'))) {
530 throw new Error('Argument mismatch in makeUnaryRequest');
533 var method_definition = options.method_definition = {
535 requestStream: false,
536 responseStream: false,
537 requestSerialize: serialize,
538 responseDeserialize: deserialize
541 metadata = metadata.clone();
543 var callProperties = {
546 call: new ClientUnaryCall(),
547 channel: this.$channel,
548 methodDefinition: method_definition,
549 callOptions: options,
553 // Transform call properties if specified.
554 if (this.$callInvocationTransformer) {
555 callProperties = this.$callInvocationTransformer(callProperties);
558 var callOptions = callProperties.callOptions;
559 var methodDefinition = callProperties.methodDefinition;
561 var interceptors = Client.prototype.resolveCallInterceptors.call(
564 callOptions.interceptors,
565 callOptions.interceptor_providers
568 var intercepting_call = client_interceptors.getInterceptingCall(
572 callProperties.channel,
573 callProperties.callback
576 var emitter = callProperties.call;
577 emitter.call = intercepting_call;
579 var last_listener = client_interceptors.getLastListener(
582 callProperties.callback
585 intercepting_call.start(callProperties.metadata, last_listener);
586 intercepting_call.sendMessage(callProperties.argument);
587 intercepting_call.halfClose();
593 * Make a client stream request to the given method, using the given serialize
594 * and deserialize functions, with the given argument.
595 * @param {string} path The path of the method to request
596 * @param {grpc~serialize} serialize The serialization function for
598 * @param {grpc~deserialize} deserialize The deserialization
599 * function for outputs
600 * @param {grpc.Metadata=} metadata Array of metadata key/value pairs to add to
602 * @param {grpc.Client~CallOptions=} options Options map
603 * @param {grpc.Client~requestCallback} callback The callback for when the
604 * response is received
605 * @return {grpc~ClientWritableStream} An event emitter for stream related
608 Client.prototype.makeClientStreamRequest = function(path, serialize,
609 deserialize, metadata,
611 if (typeof options === 'function') {
613 if (metadata instanceof Metadata) {
617 metadata = new Metadata();
619 } else if (typeof metadata === 'function') {
621 metadata = new Metadata();
625 metadata = new Metadata();
630 if (!((metadata instanceof Metadata) &&
631 (options instanceof Object) &&
632 (typeof callback === 'function'))) {
633 throw new Error('Argument mismatch in makeClientStreamRequest');
636 var method_definition = options.method_definition = {
639 responseStream: false,
640 requestSerialize: serialize,
641 responseDeserialize: deserialize
644 metadata = metadata.clone();
646 var callProperties = {
648 call: new ClientWritableStream(),
649 channel: this.$channel,
650 methodDefinition: method_definition,
651 callOptions: options,
655 // Transform call properties if specified.
656 if (this.$callInvocationTransformer) {
657 callProperties = this.$callInvocationTransformer(callProperties);
660 var callOptions = callProperties.callOptions;
661 var methodDefinition = callProperties.methodDefinition;
663 var interceptors = Client.prototype.resolveCallInterceptors.call(
666 callOptions.interceptors,
667 callOptions.interceptor_providers
670 var intercepting_call = client_interceptors.getInterceptingCall(
674 callProperties.channel,
675 callProperties.callback
678 var emitter = callProperties.call;
679 emitter.call = intercepting_call;
681 var last_listener = client_interceptors.getLastListener(
684 callProperties.callback
687 intercepting_call.start(callProperties.metadata, last_listener);
693 * Make a server stream request to the given method, with the given serialize
694 * and deserialize function, using the given argument
695 * @param {string} path The path of the method to request
696 * @param {grpc~serialize} serialize The serialization function for inputs
697 * @param {grpc~deserialize} deserialize The deserialization
698 * function for outputs
699 * @param {*} argument The argument to the call. Should be serializable with
701 * @param {grpc.Metadata=} metadata Array of metadata key/value pairs to add to
703 * @param {grpc.Client~CallOptions=} options Options map
704 * @return {grpc~ClientReadableStream} An event emitter for stream related
707 Client.prototype.makeServerStreamRequest = function(path, serialize,
708 deserialize, argument,
710 if (!(metadata instanceof Metadata)) {
712 metadata = new Metadata();
714 if (!(options instanceof Object)) {
717 if (!((metadata instanceof Metadata) && (options instanceof Object))) {
718 throw new Error('Argument mismatch in makeServerStreamRequest');
721 var method_definition = options.method_definition = {
723 requestStream: false,
724 responseStream: true,
725 requestSerialize: serialize,
726 responseDeserialize: deserialize
729 metadata = metadata.clone();
731 var callProperties = {
734 call: new ClientReadableStream(),
735 channel: this.$channel,
736 methodDefinition: method_definition,
737 callOptions: options,
740 // Transform call properties if specified.
741 if (this.$callInvocationTransformer) {
742 callProperties = this.$callInvocationTransformer(callProperties);
745 var callOptions = callProperties.callOptions;
746 var methodDefinition = callProperties.methodDefinition;
748 var interceptors = Client.prototype.resolveCallInterceptors.call(
751 callOptions.interceptors,
752 callOptions.interceptor_providers
755 var emitter = callProperties.call;
756 var intercepting_call = client_interceptors.getInterceptingCall(
760 callProperties.channel,
763 emitter.call = intercepting_call;
764 var last_listener = client_interceptors.getLastListener(
769 intercepting_call.start(callProperties.metadata, last_listener);
770 intercepting_call.sendMessage(callProperties.argument);
771 intercepting_call.halfClose();
777 * Make a bidirectional stream request with this method on the given channel.
778 * @param {string} path The path of the method to request
779 * @param {grpc~serialize} serialize The serialization function for inputs
780 * @param {grpc~deserialize} deserialize The deserialization
781 * function for outputs
782 * @param {grpc.Metadata=} metadata Array of metadata key/value
783 * pairs to add to the call
784 * @param {grpc.Client~CallOptions=} options Options map
785 * @return {grpc~ClientDuplexStream} An event emitter for stream related events
787 Client.prototype.makeBidiStreamRequest = function(path, serialize,
788 deserialize, metadata,
790 if (!(metadata instanceof Metadata)) {
792 metadata = new Metadata();
794 if (!(options instanceof Object)) {
797 if (!((metadata instanceof Metadata) && (options instanceof Object))) {
798 throw new Error('Argument mismatch in makeBidiStreamRequest');
801 var method_definition = options.method_definition = {
804 responseStream: true,
805 requestSerialize: serialize,
806 responseDeserialize: deserialize
809 metadata = metadata.clone();
811 var callProperties = {
813 call: new ClientDuplexStream(),
814 channel: this.$channel,
815 methodDefinition: method_definition,
816 callOptions: options,
819 // Transform call properties if specified.
820 if (this.$callInvocationTransformer) {
821 callProperties = this.$callInvocationTransformer(callProperties);
824 var callOptions = callProperties.callOptions;
825 var methodDefinition = callProperties.methodDefinition;
827 var interceptors = Client.prototype.resolveCallInterceptors.call(
830 callOptions.interceptors,
831 callOptions.interceptor_providers
835 var emitter = callProperties.call;
836 var intercepting_call = client_interceptors.getInterceptingCall(
840 callProperties.channel,
843 emitter.call = intercepting_call;
844 var last_listener = client_interceptors.getLastListener(
849 intercepting_call.start(callProperties.metadata, last_listener);
857 Client.prototype.close = function() {
858 this.$channel.close();
862 * Return the underlying channel object for the specified client
863 * @return {Channel} The channel
865 Client.prototype.getChannel = function() {
866 return this.$channel;
870 * Wait for the client to be ready. The callback will be called when the
871 * client has successfully connected to the server, and it will be called
872 * with an error if the attempt to connect to the server has unrecoverablly
873 * failed or if the deadline expires. This function will make the channel
874 * start connecting if it has not already done so.
875 * @param {grpc~Deadline} deadline When to stop waiting for a connection.
876 * @param {function(Error)} callback The callback to call when done attempting
879 Client.prototype.waitForReady = function(deadline, callback) {
881 var checkState = function(err) {
883 callback(new Error('Failed to connect before the deadline'));
888 new_state = self.$channel.getConnectivityState(true);
890 callback(new Error('The channel has been closed'));
893 if (new_state === grpc.connectivityState.READY) {
895 } else if (new_state === grpc.connectivityState.FATAL_FAILURE) {
896 callback(new Error('Failed to connect to server'));
899 self.$channel.watchConnectivityState(new_state, deadline, checkState);
901 callback(new Error('The channel has been closed'));
905 /* Force a single round of polling to ensure that the channel state is up
908 setImmediate(checkState);
912 * Map with short names for each of the requester maker functions. Used in
913 * makeClientConstructor
916 var requester_funcs = {
917 [methodTypes.UNARY]: Client.prototype.makeUnaryRequest,
918 [methodTypes.CLIENT_STREAMING]: Client.prototype.makeClientStreamRequest,
919 [methodTypes.SERVER_STREAMING]: Client.prototype.makeServerStreamRequest,
920 [methodTypes.BIDI_STREAMING]: Client.prototype.makeBidiStreamRequest
923 function getDefaultValues(metadata, options) {
925 res.metadata = metadata || new Metadata();
926 res.options = options || {};
931 * Map with wrappers for each type of requester function to make it use the old
932 * argument order with optional arguments after the callback.
935 var deprecated_request_wrap = {
936 [methodTypes.UNARY]: function(makeUnaryRequest) {
937 return function makeWrappedUnaryRequest(argument, callback,
939 /* jshint validthis: true */
940 var opt_args = getDefaultValues(metadata, options);
941 return makeUnaryRequest.call(this, argument, opt_args.metadata,
942 opt_args.options, callback);
945 [methodTypes.CLIENT_STREAMING]: function(makeServerStreamRequest) {
946 return function makeWrappedClientStreamRequest(callback, metadata,
948 /* jshint validthis: true */
949 var opt_args = getDefaultValues(metadata, options);
950 return makeServerStreamRequest.call(this, opt_args.metadata,
951 opt_args.options, callback);
954 [methodTypes.SERVER_STREAMING]: x => x,
955 [methodTypes.BIDI_STREAMING]: x => x
959 * Creates a constructor for a client with the given methods, as specified in
960 * the methods argument. The resulting class will have an instance method for
961 * each method in the service, which is a partial application of one of the
962 * [Client]{@link grpc.Client} request methods, depending on `requestSerialize`
963 * and `responseSerialize`, with the `method`, `serialize`, and `deserialize`
964 * arguments predefined.
966 * @alias grpc~makeGenericClientConstructor
967 * @param {grpc~ServiceDefinition} methods An object mapping method names to
969 * @param {string} serviceName The fully qualified name of the service
970 * @param {Object} class_options An options object.
971 * @param {boolean=} [class_options.deprecatedArgumentOrder=false] Indicates
972 * that the old argument order should be used for methods, with optional
973 * arguments at the end instead of the callback at the end. This option
974 * is only a temporary stopgap measure to smooth an API breakage.
975 * It is deprecated, and new code should not use it.
976 * @return {function} New client constructor, which is a subclass of
977 * {@link grpc.Client}, and has the same arguments as that constructor.
979 exports.makeClientConstructor = function(methods, serviceName,
981 if (!class_options) {
985 function ServiceClient(address, credentials, options) {
986 Client.call(this, address, credentials, options);
989 util.inherits(ServiceClient, Client);
990 ServiceClient.prototype.$method_definitions = methods;
991 ServiceClient.prototype.$method_names = {};
993 Object.keys(methods).forEach(name => {
994 const attrs = methods[name];
995 if (common.isPrototypePolluted(name)) {
998 if (name.indexOf('$') === 0) {
999 throw new Error('Method names cannot start with $');
1001 var method_type = common.getMethodType(attrs);
1002 var method_func = function() {
1003 return requester_funcs[method_type].apply(this,
1004 [ attrs.path, attrs.requestSerialize, attrs.responseDeserialize ]
1005 .concat([].slice.call(arguments))
1008 if (class_options.deprecatedArgumentOrder) {
1009 ServiceClient.prototype[name] =
1010 deprecated_request_wrap[method_type](method_func);
1012 ServiceClient.prototype[name] = method_func;
1014 ServiceClient.prototype.$method_names[attrs.path] = name;
1015 // Associate all provided attributes with the method
1016 Object.assign(ServiceClient.prototype[name], attrs);
1017 if (attrs.originalName && !common.isPrototypePolluted(attrs.originalName)) {
1018 ServiceClient.prototype[attrs.originalName] =
1019 ServiceClient.prototype[name];
1023 ServiceClient.service = methods;
1025 return ServiceClient;
1029 * Return the underlying channel object for the specified client
1031 * @alias grpc~getClientChannel
1032 * @param {grpc.Client} client The client
1033 * @return {Channel} The channel
1034 * @see grpc.Client#getChannel
1036 exports.getClientChannel = function(client) {
1037 return Client.prototype.getChannel.call(client);
1041 * Gets a map of client method names to interceptor stacks.
1042 * @param {grpc.Client} client
1043 * @returns {Object.<string, Interceptor[]>}
1045 exports.getClientInterceptors = function(client) {
1046 return Object.keys(client.$method_definitions)
1047 .reduce((acc, key) => {
1048 if (typeof key === 'string') {
1049 acc[key] = client[key].interceptors;
1056 * Wait for the client to be ready. The callback will be called when the
1057 * client has successfully connected to the server, and it will be called
1058 * with an error if the attempt to connect to the server has unrecoverablly
1059 * failed or if the deadline expires. This function will make the channel
1060 * start connecting if it has not already done so.
1062 * @alias grpc~waitForClientReady
1063 * @param {grpc.Client} client The client to wait on
1064 * @param {grpc~Deadline} deadline When to stop waiting for a connection. Pass
1065 * Infinity to wait forever.
1066 * @param {function(Error)} callback The callback to call when done attempting
1068 * @see grpc.Client#waitForReady
1070 exports.waitForClientReady = function(client, deadline, callback) {
1071 Client.prototype.waitForReady.call(client, deadline, callback);
1074 exports.StatusBuilder = client_interceptors.StatusBuilder;
1075 exports.ListenerBuilder = client_interceptors.ListenerBuilder;
1076 exports.RequesterBuilder = client_interceptors.RequesterBuilder;
1077 exports.InterceptingCall = client_interceptors.InterceptingCall;