src_client.js.html 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>JSDoc: Source: src/client.js</title>
  6. <script src="scripts/prettify/prettify.js"> </script>
  7. <script src="scripts/prettify/lang-css.js"> </script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
  13. </head>
  14. <body>
  15. <div id="main">
  16. <h1 class="page-title">Source: src/client.js</h1>
  17. <section>
  18. <article>
  19. <pre class="prettyprint source linenums"><code>/*
  20. *
  21. * Copyright 2015, Google Inc.
  22. * All rights reserved.
  23. *
  24. * Redistribution and use in source and binary forms, with or without
  25. * modification, are permitted provided that the following conditions are
  26. * met:
  27. *
  28. * * Redistributions of source code must retain the above copyright
  29. * notice, this list of conditions and the following disclaimer.
  30. * * Redistributions in binary form must reproduce the above
  31. * copyright notice, this list of conditions and the following disclaimer
  32. * in the documentation and/or other materials provided with the
  33. * distribution.
  34. * * Neither the name of Google Inc. nor the names of its
  35. * contributors may be used to endorse or promote products derived from
  36. * this software without specific prior written permission.
  37. *
  38. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  39. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  40. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  41. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  42. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  43. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  44. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  45. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  46. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  47. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  48. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  49. *
  50. */
  51. /**
  52. * Client module
  53. *
  54. * This module contains the factory method for creating Client classes, and the
  55. * method calling code for all types of methods.
  56. *
  57. * For example, to create a client and call a method on it:
  58. *
  59. * var proto_obj = grpc.load(proto_file_path);
  60. * var Client = proto_obj.package.subpackage.ServiceName;
  61. * var client = new Client(server_address, client_credentials);
  62. * var call = client.unaryMethod(arguments, callback);
  63. *
  64. * @module
  65. */
  66. 'use strict';
  67. var _ = require('lodash');
  68. var grpc = require('bindings')('grpc_node');
  69. var common = require('./common');
  70. var Metadata = require('./metadata');
  71. var EventEmitter = require('events').EventEmitter;
  72. var stream = require('stream');
  73. var Readable = stream.Readable;
  74. var Writable = stream.Writable;
  75. var Duplex = stream.Duplex;
  76. var util = require('util');
  77. var version = require('../../../package.json').version;
  78. util.inherits(ClientWritableStream, Writable);
  79. /**
  80. * A stream that the client can write to. Used for calls that are streaming from
  81. * the client side.
  82. * @constructor
  83. * @param {grpc.Call} call The call object to send data with
  84. * @param {function(*):Buffer=} serialize Serialization function for writes.
  85. */
  86. function ClientWritableStream(call, serialize) {
  87. Writable.call(this, {objectMode: true});
  88. this.call = call;
  89. this.serialize = common.wrapIgnoreNull(serialize);
  90. this.on('finish', function() {
  91. var batch = {};
  92. batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
  93. call.startBatch(batch, function() {});
  94. });
  95. }
  96. /**
  97. * Attempt to write the given chunk. Calls the callback when done. This is an
  98. * implementation of a method needed for implementing stream.Writable.
  99. * @access private
  100. * @param {Buffer} chunk The chunk to write
  101. * @param {string} encoding Used to pass write flags
  102. * @param {function(Error=)} callback Called when the write is complete
  103. */
  104. function _write(chunk, encoding, callback) {
  105. /* jshint validthis: true */
  106. var batch = {};
  107. var message = this.serialize(chunk);
  108. if (_.isFinite(encoding)) {
  109. /* Attach the encoding if it is a finite number. This is the closest we
  110. * can get to checking that it is valid flags */
  111. message.grpcWriteFlags = encoding;
  112. }
  113. batch[grpc.opType.SEND_MESSAGE] = message;
  114. this.call.startBatch(batch, function(err, event) {
  115. if (err) {
  116. // Something has gone wrong. Stop writing by failing to call callback
  117. return;
  118. }
  119. callback();
  120. });
  121. }
  122. ClientWritableStream.prototype._write = _write;
  123. util.inherits(ClientReadableStream, Readable);
  124. /**
  125. * A stream that the client can read from. Used for calls that are streaming
  126. * from the server side.
  127. * @constructor
  128. * @param {grpc.Call} call The call object to read data with
  129. * @param {function(Buffer):*=} deserialize Deserialization function for reads
  130. */
  131. function ClientReadableStream(call, deserialize) {
  132. Readable.call(this, {objectMode: true});
  133. this.call = call;
  134. this.finished = false;
  135. this.reading = false;
  136. this.deserialize = common.wrapIgnoreNull(deserialize);
  137. }
  138. /**
  139. * Read the next object from the stream.
  140. * @access private
  141. * @param {*} size Ignored because we use objectMode=true
  142. */
  143. function _read(size) {
  144. /* jshint validthis: true */
  145. var self = this;
  146. /**
  147. * Callback to be called when a READ event is received. Pushes the data onto
  148. * the read queue and starts reading again if applicable
  149. * @param {grpc.Event} event READ event object
  150. */
  151. function readCallback(err, event) {
  152. if (err) {
  153. // Something has gone wrong. Stop reading and wait for status
  154. self.finished = true;
  155. return;
  156. }
  157. var data = event.read;
  158. var deserialized;
  159. try {
  160. deserialized = self.deserialize(data);
  161. } catch (e) {
  162. self.call.cancelWithStatus(grpc.status.INTERNAL,
  163. 'Failed to parse server response');
  164. }
  165. if (self.push(deserialized) &amp;&amp; data !== null) {
  166. var read_batch = {};
  167. read_batch[grpc.opType.RECV_MESSAGE] = true;
  168. self.call.startBatch(read_batch, readCallback);
  169. } else {
  170. self.reading = false;
  171. }
  172. }
  173. if (self.finished) {
  174. self.push(null);
  175. } else {
  176. if (!self.reading) {
  177. self.reading = true;
  178. var read_batch = {};
  179. read_batch[grpc.opType.RECV_MESSAGE] = true;
  180. self.call.startBatch(read_batch, readCallback);
  181. }
  182. }
  183. }
  184. ClientReadableStream.prototype._read = _read;
  185. util.inherits(ClientDuplexStream, Duplex);
  186. /**
  187. * A stream that the client can read from or write to. Used for calls with
  188. * duplex streaming.
  189. * @constructor
  190. * @param {grpc.Call} call Call object to proxy
  191. * @param {function(*):Buffer=} serialize Serialization function for requests
  192. * @param {function(Buffer):*=} deserialize Deserialization function for
  193. * responses
  194. */
  195. function ClientDuplexStream(call, serialize, deserialize) {
  196. Duplex.call(this, {objectMode: true});
  197. this.serialize = common.wrapIgnoreNull(serialize);
  198. this.deserialize = common.wrapIgnoreNull(deserialize);
  199. this.call = call;
  200. this.on('finish', function() {
  201. var batch = {};
  202. batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
  203. call.startBatch(batch, function() {});
  204. });
  205. }
  206. ClientDuplexStream.prototype._read = _read;
  207. ClientDuplexStream.prototype._write = _write;
  208. /**
  209. * Cancel the ongoing call
  210. */
  211. function cancel() {
  212. /* jshint validthis: true */
  213. this.call.cancel();
  214. }
  215. ClientReadableStream.prototype.cancel = cancel;
  216. ClientWritableStream.prototype.cancel = cancel;
  217. ClientDuplexStream.prototype.cancel = cancel;
  218. /**
  219. * Get the endpoint this call/stream is connected to.
  220. * @return {string} The URI of the endpoint
  221. */
  222. function getPeer() {
  223. /* jshint validthis: true */
  224. return this.call.getPeer();
  225. }
  226. ClientReadableStream.prototype.getPeer = getPeer;
  227. ClientWritableStream.prototype.getPeer = getPeer;
  228. ClientDuplexStream.prototype.getPeer = getPeer;
  229. /**
  230. * Get a call object built with the provided options. Keys for options are
  231. * 'deadline', which takes a date or number, and 'host', which takes a string
  232. * and overrides the hostname to connect to.
  233. * @param {Object} options Options map.
  234. */
  235. function getCall(channel, method, options) {
  236. var deadline;
  237. var host;
  238. var parent;
  239. var propagate_flags;
  240. var credentials;
  241. if (options) {
  242. deadline = options.deadline;
  243. host = options.host;
  244. parent = _.get(options, 'parent.call');
  245. propagate_flags = options.propagate_flags;
  246. credentials = options.credentials;
  247. }
  248. if (deadline === undefined) {
  249. deadline = Infinity;
  250. }
  251. var call = new grpc.Call(channel, method, deadline, host,
  252. parent, propagate_flags);
  253. if (credentials) {
  254. call.setCredentials(credentials);
  255. }
  256. return call;
  257. }
  258. /**
  259. * Get a function that can make unary requests to the specified method.
  260. * @param {string} method The name of the method to request
  261. * @param {function(*):Buffer} serialize The serialization function for inputs
  262. * @param {function(Buffer)} deserialize The deserialization function for
  263. * outputs
  264. * @return {Function} makeUnaryRequest
  265. */
  266. function makeUnaryRequestFunction(method, serialize, deserialize) {
  267. /**
  268. * Make a unary request with this method on the given channel with the given
  269. * argument, callback, etc.
  270. * @this {Client} Client object. Must have a channel member.
  271. * @param {*} argument The argument to the call. Should be serializable with
  272. * serialize
  273. * @param {function(?Error, value=)} callback The callback to for when the
  274. * response is received
  275. * @param {Metadata=} metadata Metadata to add to the call
  276. * @param {Object=} options Options map
  277. * @return {EventEmitter} An event emitter for stream related events
  278. */
  279. function makeUnaryRequest(argument, callback, metadata, options) {
  280. /* jshint validthis: true */
  281. var emitter = new EventEmitter();
  282. var call = getCall(this.$channel, method, options);
  283. if (metadata === null || metadata === undefined) {
  284. metadata = new Metadata();
  285. } else {
  286. metadata = metadata.clone();
  287. }
  288. emitter.cancel = function cancel() {
  289. call.cancel();
  290. };
  291. emitter.getPeer = function getPeer() {
  292. return call.getPeer();
  293. };
  294. var client_batch = {};
  295. var message = serialize(argument);
  296. if (options) {
  297. message.grpcWriteFlags = options.flags;
  298. }
  299. client_batch[grpc.opType.SEND_INITIAL_METADATA] =
  300. metadata._getCoreRepresentation();
  301. client_batch[grpc.opType.SEND_MESSAGE] = message;
  302. client_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
  303. client_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
  304. client_batch[grpc.opType.RECV_MESSAGE] = true;
  305. client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
  306. call.startBatch(client_batch, function(err, response) {
  307. response.status.metadata = Metadata._fromCoreRepresentation(
  308. response.status.metadata);
  309. var status = response.status;
  310. var error;
  311. var deserialized;
  312. if (status.code === grpc.status.OK) {
  313. if (err) {
  314. // Got a batch error, but OK status. Something went wrong
  315. callback(err);
  316. return;
  317. } else {
  318. try {
  319. deserialized = deserialize(response.read);
  320. } catch (e) {
  321. /* Change status to indicate bad server response. This will result
  322. * in passing an error to the callback */
  323. status = {
  324. code: grpc.status.INTERNAL,
  325. details: 'Failed to parse server response'
  326. };
  327. }
  328. }
  329. }
  330. if (status.code !== grpc.status.OK) {
  331. error = new Error(response.status.details);
  332. error.code = status.code;
  333. error.metadata = status.metadata;
  334. callback(error);
  335. } else {
  336. callback(null, deserialized);
  337. }
  338. emitter.emit('status', status);
  339. emitter.emit('metadata', Metadata._fromCoreRepresentation(
  340. response.metadata));
  341. });
  342. return emitter;
  343. }
  344. return makeUnaryRequest;
  345. }
  346. /**
  347. * Get a function that can make client stream requests to the specified method.
  348. * @param {string} method The name of the method to request
  349. * @param {function(*):Buffer} serialize The serialization function for inputs
  350. * @param {function(Buffer)} deserialize The deserialization function for
  351. * outputs
  352. * @return {Function} makeClientStreamRequest
  353. */
  354. function makeClientStreamRequestFunction(method, serialize, deserialize) {
  355. /**
  356. * Make a client stream request with this method on the given channel with the
  357. * given callback, etc.
  358. * @this {Client} Client object. Must have a channel member.
  359. * @param {function(?Error, value=)} callback The callback to for when the
  360. * response is received
  361. * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
  362. * call
  363. * @param {Object=} options Options map
  364. * @return {EventEmitter} An event emitter for stream related events
  365. */
  366. function makeClientStreamRequest(callback, metadata, options) {
  367. /* jshint validthis: true */
  368. var call = getCall(this.$channel, method, options);
  369. if (metadata === null || metadata === undefined) {
  370. metadata = new Metadata();
  371. } else {
  372. metadata = metadata.clone();
  373. }
  374. var stream = new ClientWritableStream(call, serialize);
  375. var metadata_batch = {};
  376. metadata_batch[grpc.opType.SEND_INITIAL_METADATA] =
  377. metadata._getCoreRepresentation();
  378. metadata_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
  379. call.startBatch(metadata_batch, function(err, response) {
  380. if (err) {
  381. // The call has stopped for some reason. A non-OK status will arrive
  382. // in the other batch.
  383. return;
  384. }
  385. stream.emit('metadata', Metadata._fromCoreRepresentation(
  386. response.metadata));
  387. });
  388. var client_batch = {};
  389. client_batch[grpc.opType.RECV_MESSAGE] = true;
  390. client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
  391. call.startBatch(client_batch, function(err, response) {
  392. response.status.metadata = Metadata._fromCoreRepresentation(
  393. response.status.metadata);
  394. var status = response.status;
  395. var error;
  396. var deserialized;
  397. if (status.code === grpc.status.OK) {
  398. if (err) {
  399. // Got a batch error, but OK status. Something went wrong
  400. callback(err);
  401. return;
  402. } else {
  403. try {
  404. deserialized = deserialize(response.read);
  405. } catch (e) {
  406. /* Change status to indicate bad server response. This will result
  407. * in passing an error to the callback */
  408. status = {
  409. code: grpc.status.INTERNAL,
  410. details: 'Failed to parse server response'
  411. };
  412. }
  413. }
  414. }
  415. if (status.code !== grpc.status.OK) {
  416. error = new Error(response.status.details);
  417. error.code = status.code;
  418. error.metadata = status.metadata;
  419. callback(error);
  420. } else {
  421. callback(null, deserialized);
  422. }
  423. stream.emit('status', status);
  424. });
  425. return stream;
  426. }
  427. return makeClientStreamRequest;
  428. }
  429. /**
  430. * Get a function that can make server stream requests to the specified method.
  431. * @param {string} method The name of the method to request
  432. * @param {function(*):Buffer} serialize The serialization function for inputs
  433. * @param {function(Buffer)} deserialize The deserialization function for
  434. * outputs
  435. * @return {Function} makeServerStreamRequest
  436. */
  437. function makeServerStreamRequestFunction(method, serialize, deserialize) {
  438. /**
  439. * Make a server stream request with this method on the given channel with the
  440. * given argument, etc.
  441. * @this {SurfaceClient} Client object. Must have a channel member.
  442. * @param {*} argument The argument to the call. Should be serializable with
  443. * serialize
  444. * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
  445. * call
  446. * @param {Object} options Options map
  447. * @return {EventEmitter} An event emitter for stream related events
  448. */
  449. function makeServerStreamRequest(argument, metadata, options) {
  450. /* jshint validthis: true */
  451. var call = getCall(this.$channel, method, options);
  452. if (metadata === null || metadata === undefined) {
  453. metadata = new Metadata();
  454. } else {
  455. metadata = metadata.clone();
  456. }
  457. var stream = new ClientReadableStream(call, deserialize);
  458. var start_batch = {};
  459. var message = serialize(argument);
  460. if (options) {
  461. message.grpcWriteFlags = options.flags;
  462. }
  463. start_batch[grpc.opType.SEND_INITIAL_METADATA] =
  464. metadata._getCoreRepresentation();
  465. start_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
  466. start_batch[grpc.opType.SEND_MESSAGE] = message;
  467. start_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
  468. call.startBatch(start_batch, function(err, response) {
  469. if (err) {
  470. // The call has stopped for some reason. A non-OK status will arrive
  471. // in the other batch.
  472. return;
  473. }
  474. stream.emit('metadata', Metadata._fromCoreRepresentation(
  475. response.metadata));
  476. });
  477. var status_batch = {};
  478. status_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
  479. call.startBatch(status_batch, function(err, response) {
  480. response.status.metadata = Metadata._fromCoreRepresentation(
  481. response.status.metadata);
  482. stream.emit('status', response.status);
  483. if (response.status.code !== grpc.status.OK) {
  484. var error = new Error(response.status.details);
  485. error.code = response.status.code;
  486. error.metadata = response.status.metadata;
  487. stream.emit('error', error);
  488. return;
  489. } else {
  490. if (err) {
  491. // Got a batch error, but OK status. Something went wrong
  492. stream.emit('error', err);
  493. return;
  494. }
  495. }
  496. });
  497. return stream;
  498. }
  499. return makeServerStreamRequest;
  500. }
  501. /**
  502. * Get a function that can make bidirectional stream requests to the specified
  503. * method.
  504. * @param {string} method The name of the method to request
  505. * @param {function(*):Buffer} serialize The serialization function for inputs
  506. * @param {function(Buffer)} deserialize The deserialization function for
  507. * outputs
  508. * @return {Function} makeBidiStreamRequest
  509. */
  510. function makeBidiStreamRequestFunction(method, serialize, deserialize) {
  511. /**
  512. * Make a bidirectional stream request with this method on the given channel.
  513. * @this {SurfaceClient} Client object. Must have a channel member.
  514. * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
  515. * call
  516. * @param {Options} options Options map
  517. * @return {EventEmitter} An event emitter for stream related events
  518. */
  519. function makeBidiStreamRequest(metadata, options) {
  520. /* jshint validthis: true */
  521. var call = getCall(this.$channel, method, options);
  522. if (metadata === null || metadata === undefined) {
  523. metadata = new Metadata();
  524. } else {
  525. metadata = metadata.clone();
  526. }
  527. var stream = new ClientDuplexStream(call, serialize, deserialize);
  528. var start_batch = {};
  529. start_batch[grpc.opType.SEND_INITIAL_METADATA] =
  530. metadata._getCoreRepresentation();
  531. start_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
  532. call.startBatch(start_batch, function(err, response) {
  533. if (err) {
  534. // The call has stopped for some reason. A non-OK status will arrive
  535. // in the other batch.
  536. return;
  537. }
  538. stream.emit('metadata', Metadata._fromCoreRepresentation(
  539. response.metadata));
  540. });
  541. var status_batch = {};
  542. status_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
  543. call.startBatch(status_batch, function(err, response) {
  544. response.status.metadata = Metadata._fromCoreRepresentation(
  545. response.status.metadata);
  546. stream.emit('status', response.status);
  547. if (response.status.code !== grpc.status.OK) {
  548. var error = new Error(response.status.details);
  549. error.code = response.status.code;
  550. error.metadata = response.status.metadata;
  551. stream.emit('error', error);
  552. return;
  553. } else {
  554. if (err) {
  555. // Got a batch error, but OK status. Something went wrong
  556. stream.emit('error', err);
  557. return;
  558. }
  559. }
  560. });
  561. return stream;
  562. }
  563. return makeBidiStreamRequest;
  564. }
  565. /**
  566. * Map with short names for each of the requester maker functions. Used in
  567. * makeClientConstructor
  568. */
  569. var requester_makers = {
  570. unary: makeUnaryRequestFunction,
  571. server_stream: makeServerStreamRequestFunction,
  572. client_stream: makeClientStreamRequestFunction,
  573. bidi: makeBidiStreamRequestFunction
  574. };
  575. /**
  576. * Creates a constructor for a client with the given methods. The methods object
  577. * maps method name to an object with the following keys:
  578. * path: The path on the server for accessing the method. For example, for
  579. * protocol buffers, we use "/service_name/method_name"
  580. * requestStream: bool indicating whether the client sends a stream
  581. * resonseStream: bool indicating whether the server sends a stream
  582. * requestSerialize: function to serialize request objects
  583. * responseDeserialize: function to deserialize response objects
  584. * @param {Object} methods An object mapping method names to method attributes
  585. * @param {string} serviceName The fully qualified name of the service
  586. * @return {function(string, Object)} New client constructor
  587. */
  588. exports.makeClientConstructor = function(methods, serviceName) {
  589. /**
  590. * Create a client with the given methods
  591. * @constructor
  592. * @param {string} address The address of the server to connect to
  593. * @param {grpc.Credentials} credentials Credentials to use to connect
  594. * to the server
  595. * @param {Object} options Options to pass to the underlying channel
  596. */
  597. function Client(address, credentials, options) {
  598. if (!options) {
  599. options = {};
  600. }
  601. /* Append the grpc-node user agent string after the application user agent
  602. * string, and put the combination at the beginning of the user agent string
  603. */
  604. if (options['grpc.primary_user_agent']) {
  605. options['grpc.primary_user_agent'] += ' ';
  606. } else {
  607. options['grpc.primary_user_agent'] = '';
  608. }
  609. options['grpc.primary_user_agent'] += 'grpc-node/' + version;
  610. /* Private fields use $ as a prefix instead of _ because it is an invalid
  611. * prefix of a method name */
  612. this.$channel = new grpc.Channel(address, credentials, options);
  613. }
  614. _.each(methods, function(attrs, name) {
  615. var method_type;
  616. if (_.startsWith(name, '$')) {
  617. throw new Error('Method names cannot start with $');
  618. }
  619. if (attrs.requestStream) {
  620. if (attrs.responseStream) {
  621. method_type = 'bidi';
  622. } else {
  623. method_type = 'client_stream';
  624. }
  625. } else {
  626. if (attrs.responseStream) {
  627. method_type = 'server_stream';
  628. } else {
  629. method_type = 'unary';
  630. }
  631. }
  632. var serialize = attrs.requestSerialize;
  633. var deserialize = attrs.responseDeserialize;
  634. Client.prototype[name] = requester_makers[method_type](
  635. attrs.path, serialize, deserialize);
  636. Client.prototype[name].serialize = serialize;
  637. Client.prototype[name].deserialize = deserialize;
  638. });
  639. return Client;
  640. };
  641. /**
  642. * Return the underlying channel object for the specified client
  643. * @param {Client} client
  644. * @return {Channel} The channel
  645. */
  646. exports.getClientChannel = function(client) {
  647. return client.$channel;
  648. };
  649. /**
  650. * Wait for the client to be ready. The callback will be called when the
  651. * client has successfully connected to the server, and it will be called
  652. * with an error if the attempt to connect to the server has unrecoverablly
  653. * failed or if the deadline expires. This function will make the channel
  654. * start connecting if it has not already done so.
  655. * @param {Client} client The client to wait on
  656. * @param {(Date|Number)} deadline When to stop waiting for a connection. Pass
  657. * Infinity to wait forever.
  658. * @param {function(Error)} callback The callback to call when done attempting
  659. * to connect.
  660. */
  661. exports.waitForClientReady = function(client, deadline, callback) {
  662. var checkState = function(err) {
  663. if (err) {
  664. callback(new Error('Failed to connect before the deadline'));
  665. return;
  666. }
  667. var new_state = client.$channel.getConnectivityState(true);
  668. if (new_state === grpc.connectivityState.READY) {
  669. callback();
  670. } else if (new_state === grpc.connectivityState.FATAL_FAILURE) {
  671. callback(new Error('Failed to connect to server'));
  672. } else {
  673. client.$channel.watchConnectivityState(new_state, deadline, checkState);
  674. }
  675. };
  676. checkState();
  677. };
  678. /**
  679. * Creates a constructor for clients for the given service
  680. * @param {ProtoBuf.Reflect.Service} service The service to generate a client
  681. * for
  682. * @return {function(string, Object)} New client constructor
  683. */
  684. exports.makeProtobufClientConstructor = function(service) {
  685. var method_attrs = common.getProtobufServiceAttrs(service, service.name);
  686. var Client = exports.makeClientConstructor(
  687. method_attrs, common.fullyQualifiedName(service));
  688. Client.service = service;
  689. return Client;
  690. };
  691. /**
  692. * Map of status code names to status codes
  693. */
  694. exports.status = grpc.status;
  695. /**
  696. * See docs for client.callError
  697. */
  698. exports.callError = grpc.callError;
  699. </code></pre>
  700. </article>
  701. </section>
  702. </div>
  703. <nav>
  704. <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-src_client.html">src/client</a></li><li><a href="module-src_common.html">src/common</a></li><li><a href="module-src_credentials.html">src/credentials</a></li><li><a href="module-src_metadata.html">src/metadata</a></li><li><a href="module-src_server.html">src/server</a></li></ul><h3>Classes</h3><ul><li><a href="module-src_client.makeClientConstructor-Client.html">Client</a></li><li><a href="module-src_client-ClientDuplexStream.html">ClientDuplexStream</a></li><li><a href="module-src_client-ClientReadableStream.html">ClientReadableStream</a></li><li><a href="module-src_client-ClientWritableStream.html">ClientWritableStream</a></li><li><a href="module-src_metadata-Metadata.html">Metadata</a></li><li><a href="module-src_server-Server.html">Server</a></li><li><a href="module-src_server-ServerDuplexStream.html">ServerDuplexStream</a></li><li><a href="module-src_server-ServerReadableStream.html">ServerReadableStream</a></li><li><a href="module-src_server-ServerWritableStream.html">ServerWritableStream</a></li></ul><h3>Global</h3><ul><li><a href="global.html#callError">callError</a></li><li><a href="global.html#credentials">credentials</a></li><li><a href="global.html#getClientChannel">getClientChannel</a></li><li><a href="global.html#load">load</a></li><li><a href="global.html#loadObject">loadObject</a></li><li><a href="global.html#makeGenericClientConstructor">makeGenericClientConstructor</a></li><li><a href="global.html#Metadata">Metadata</a></li><li><a href="global.html#propagate">propagate</a></li><li><a href="global.html#Server">Server</a></li><li><a href="global.html#ServerCredentials">ServerCredentials</a></li><li><a href="global.html#status">status</a></li><li><a href="global.html#waitForClientReady">waitForClientReady</a></li><li><a href="global.html#writeFlags">writeFlags</a></li></ul>
  705. </nav>
  706. <br class="clear">
  707. <footer>
  708. Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.4.0</a> on Thu Jan 14 2016 16:17:15 GMT-0800 (PST)
  709. </footer>
  710. <script> prettyPrint(); </script>
  711. <script src="scripts/linenumber.js"> </script>
  712. </body>
  713. </html>