src_client.js.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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. * @module
  54. */
  55. 'use strict';
  56. var _ = require('lodash');
  57. var grpc = require('bindings')('grpc.node');
  58. var common = require('./common');
  59. var Metadata = require('./metadata');
  60. var EventEmitter = require('events').EventEmitter;
  61. var stream = require('stream');
  62. var Readable = stream.Readable;
  63. var Writable = stream.Writable;
  64. var Duplex = stream.Duplex;
  65. var util = require('util');
  66. var version = require('../package.json').version;
  67. util.inherits(ClientWritableStream, Writable);
  68. /**
  69. * A stream that the client can write to. Used for calls that are streaming from
  70. * the client side.
  71. * @constructor
  72. * @param {grpc.Call} call The call object to send data with
  73. * @param {function(*):Buffer=} serialize Serialization function for writes.
  74. */
  75. function ClientWritableStream(call, serialize) {
  76. Writable.call(this, {objectMode: true});
  77. this.call = call;
  78. this.serialize = common.wrapIgnoreNull(serialize);
  79. this.on('finish', function() {
  80. var batch = {};
  81. batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
  82. call.startBatch(batch, function() {});
  83. });
  84. }
  85. /**
  86. * Attempt to write the given chunk. Calls the callback when done. This is an
  87. * implementation of a method needed for implementing stream.Writable.
  88. * @access private
  89. * @param {Buffer} chunk The chunk to write
  90. * @param {string} encoding Used to pass write flags
  91. * @param {function(Error=)} callback Called when the write is complete
  92. */
  93. function _write(chunk, encoding, callback) {
  94. /* jshint validthis: true */
  95. var batch = {};
  96. var message = this.serialize(chunk);
  97. if (_.isFinite(encoding)) {
  98. /* Attach the encoding if it is a finite number. This is the closest we
  99. * can get to checking that it is valid flags */
  100. message.grpcWriteFlags = encoding;
  101. }
  102. batch[grpc.opType.SEND_MESSAGE] = message;
  103. this.call.startBatch(batch, function(err, event) {
  104. if (err) {
  105. // Something has gone wrong. Stop writing by failing to call callback
  106. return;
  107. }
  108. callback();
  109. });
  110. }
  111. ClientWritableStream.prototype._write = _write;
  112. util.inherits(ClientReadableStream, Readable);
  113. /**
  114. * A stream that the client can read from. Used for calls that are streaming
  115. * from the server side.
  116. * @constructor
  117. * @param {grpc.Call} call The call object to read data with
  118. * @param {function(Buffer):*=} deserialize Deserialization function for reads
  119. */
  120. function ClientReadableStream(call, deserialize) {
  121. Readable.call(this, {objectMode: true});
  122. this.call = call;
  123. this.finished = false;
  124. this.reading = false;
  125. this.deserialize = common.wrapIgnoreNull(deserialize);
  126. }
  127. /**
  128. * Read the next object from the stream.
  129. * @access private
  130. * @param {*} size Ignored because we use objectMode=true
  131. */
  132. function _read(size) {
  133. /* jshint validthis: true */
  134. var self = this;
  135. /**
  136. * Callback to be called when a READ event is received. Pushes the data onto
  137. * the read queue and starts reading again if applicable
  138. * @param {grpc.Event} event READ event object
  139. */
  140. function readCallback(err, event) {
  141. if (err) {
  142. // Something has gone wrong. Stop reading and wait for status
  143. self.finished = true;
  144. return;
  145. }
  146. var data = event.read;
  147. var deserialized;
  148. try {
  149. deserialized = self.deserialize(data);
  150. } catch (e) {
  151. self.call.cancelWithStatus(grpc.status.INTERNAL,
  152. 'Failed to parse server response');
  153. }
  154. if (self.push(deserialized) &amp;&amp; data !== null) {
  155. var read_batch = {};
  156. read_batch[grpc.opType.RECV_MESSAGE] = true;
  157. self.call.startBatch(read_batch, readCallback);
  158. } else {
  159. self.reading = false;
  160. }
  161. }
  162. if (self.finished) {
  163. self.push(null);
  164. } else {
  165. if (!self.reading) {
  166. self.reading = true;
  167. var read_batch = {};
  168. read_batch[grpc.opType.RECV_MESSAGE] = true;
  169. self.call.startBatch(read_batch, readCallback);
  170. }
  171. }
  172. }
  173. ClientReadableStream.prototype._read = _read;
  174. util.inherits(ClientDuplexStream, Duplex);
  175. /**
  176. * A stream that the client can read from or write to. Used for calls with
  177. * duplex streaming.
  178. * @constructor
  179. * @param {grpc.Call} call Call object to proxy
  180. * @param {function(*):Buffer=} serialize Serialization function for requests
  181. * @param {function(Buffer):*=} deserialize Deserialization function for
  182. * responses
  183. */
  184. function ClientDuplexStream(call, serialize, deserialize) {
  185. Duplex.call(this, {objectMode: true});
  186. this.serialize = common.wrapIgnoreNull(serialize);
  187. this.deserialize = common.wrapIgnoreNull(deserialize);
  188. this.call = call;
  189. this.on('finish', function() {
  190. var batch = {};
  191. batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
  192. call.startBatch(batch, function() {});
  193. });
  194. }
  195. ClientDuplexStream.prototype._read = _read;
  196. ClientDuplexStream.prototype._write = _write;
  197. /**
  198. * Cancel the ongoing call
  199. */
  200. function cancel() {
  201. /* jshint validthis: true */
  202. this.call.cancel();
  203. }
  204. ClientReadableStream.prototype.cancel = cancel;
  205. ClientWritableStream.prototype.cancel = cancel;
  206. ClientDuplexStream.prototype.cancel = cancel;
  207. /**
  208. * Get the endpoint this call/stream is connected to.
  209. * @return {string} The URI of the endpoint
  210. */
  211. function getPeer() {
  212. /* jshint validthis: true */
  213. return this.call.getPeer();
  214. }
  215. ClientReadableStream.prototype.getPeer = getPeer;
  216. ClientWritableStream.prototype.getPeer = getPeer;
  217. ClientDuplexStream.prototype.getPeer = getPeer;
  218. /**
  219. * Get a call object built with the provided options. Keys for options are
  220. * 'deadline', which takes a date or number, and 'host', which takes a string
  221. * and overrides the hostname to connect to.
  222. * @param {Object} options Options map.
  223. */
  224. function getCall(channel, method, options) {
  225. var deadline;
  226. var host;
  227. var parent;
  228. var propagate_flags;
  229. if (options) {
  230. deadline = options.deadline;
  231. host = options.host;
  232. parent = _.get(options, 'parent.call');
  233. propagate_flags = options.propagate_flags;
  234. }
  235. if (deadline === undefined) {
  236. deadline = Infinity;
  237. }
  238. return new grpc.Call(channel, method, deadline, host,
  239. parent, propagate_flags);
  240. }
  241. /**
  242. * Get a function that can make unary requests to the specified method.
  243. * @param {string} method The name of the method to request
  244. * @param {function(*):Buffer} serialize The serialization function for inputs
  245. * @param {function(Buffer)} deserialize The deserialization function for
  246. * outputs
  247. * @return {Function} makeUnaryRequest
  248. */
  249. function makeUnaryRequestFunction(method, serialize, deserialize) {
  250. /**
  251. * Make a unary request with this method on the given channel with the given
  252. * argument, callback, etc.
  253. * @this {Client} Client object. Must have a channel member.
  254. * @param {*} argument The argument to the call. Should be serializable with
  255. * serialize
  256. * @param {function(?Error, value=)} callback The callback to for when the
  257. * response is received
  258. * @param {Metadata=} metadata Metadata to add to the call
  259. * @param {Object=} options Options map
  260. * @return {EventEmitter} An event emitter for stream related events
  261. */
  262. function makeUnaryRequest(argument, callback, metadata, options) {
  263. /* jshint validthis: true */
  264. var emitter = new EventEmitter();
  265. var call = getCall(this.$channel, method, options);
  266. if (metadata === null || metadata === undefined) {
  267. metadata = new Metadata();
  268. } else {
  269. metadata = metadata.clone();
  270. }
  271. emitter.cancel = function cancel() {
  272. call.cancel();
  273. };
  274. emitter.getPeer = function getPeer() {
  275. return call.getPeer();
  276. };
  277. this.$updateMetadata(this.$auth_uri, metadata, function(error, metadata) {
  278. if (error) {
  279. call.cancel();
  280. callback(error);
  281. return;
  282. }
  283. var client_batch = {};
  284. var message = serialize(argument);
  285. if (options) {
  286. message.grpcWriteFlags = options.flags;
  287. }
  288. client_batch[grpc.opType.SEND_INITIAL_METADATA] =
  289. metadata._getCoreRepresentation();
  290. client_batch[grpc.opType.SEND_MESSAGE] = message;
  291. client_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
  292. client_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
  293. client_batch[grpc.opType.RECV_MESSAGE] = true;
  294. client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
  295. call.startBatch(client_batch, function(err, response) {
  296. response.status.metadata = Metadata._fromCoreRepresentation(
  297. response.status.metadata);
  298. var status = response.status;
  299. var error;
  300. var deserialized;
  301. if (status.code === grpc.status.OK) {
  302. if (err) {
  303. // Got a batch error, but OK status. Something went wrong
  304. callback(err);
  305. return;
  306. } else {
  307. try {
  308. deserialized = deserialize(response.read);
  309. } catch (e) {
  310. /* Change status to indicate bad server response. This will result
  311. * in passing an error to the callback */
  312. status = {
  313. code: grpc.status.INTERNAL,
  314. details: 'Failed to parse server response'
  315. };
  316. }
  317. }
  318. }
  319. if (status.code !== grpc.status.OK) {
  320. error = new Error(response.status.details);
  321. error.code = status.code;
  322. error.metadata = status.metadata;
  323. callback(error);
  324. } else {
  325. callback(null, deserialized);
  326. }
  327. emitter.emit('status', status);
  328. emitter.emit('metadata', Metadata._fromCoreRepresentation(
  329. response.metadata));
  330. });
  331. });
  332. return emitter;
  333. }
  334. return makeUnaryRequest;
  335. }
  336. /**
  337. * Get a function that can make client stream requests to the specified method.
  338. * @param {string} method The name of the method to request
  339. * @param {function(*):Buffer} serialize The serialization function for inputs
  340. * @param {function(Buffer)} deserialize The deserialization function for
  341. * outputs
  342. * @return {Function} makeClientStreamRequest
  343. */
  344. function makeClientStreamRequestFunction(method, serialize, deserialize) {
  345. /**
  346. * Make a client stream request with this method on the given channel with the
  347. * given callback, etc.
  348. * @this {Client} Client object. Must have a channel member.
  349. * @param {function(?Error, value=)} callback The callback to for when the
  350. * response is received
  351. * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
  352. * call
  353. * @param {Object=} options Options map
  354. * @return {EventEmitter} An event emitter for stream related events
  355. */
  356. function makeClientStreamRequest(callback, metadata, options) {
  357. /* jshint validthis: true */
  358. var call = getCall(this.$channel, method, options);
  359. if (metadata === null || metadata === undefined) {
  360. metadata = new Metadata();
  361. } else {
  362. metadata = metadata.clone();
  363. }
  364. var stream = new ClientWritableStream(call, serialize);
  365. this.$updateMetadata(this.$auth_uri, metadata, function(error, metadata) {
  366. if (error) {
  367. call.cancel();
  368. callback(error);
  369. return;
  370. }
  371. var metadata_batch = {};
  372. metadata_batch[grpc.opType.SEND_INITIAL_METADATA] =
  373. metadata._getCoreRepresentation();
  374. metadata_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
  375. call.startBatch(metadata_batch, function(err, response) {
  376. if (err) {
  377. // The call has stopped for some reason. A non-OK status will arrive
  378. // in the other batch.
  379. return;
  380. }
  381. stream.emit('metadata', Metadata._fromCoreRepresentation(
  382. response.metadata));
  383. });
  384. var client_batch = {};
  385. client_batch[grpc.opType.RECV_MESSAGE] = true;
  386. client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
  387. call.startBatch(client_batch, function(err, response) {
  388. response.status.metadata = Metadata._fromCoreRepresentation(
  389. response.status.metadata);
  390. var status = response.status;
  391. var error;
  392. var deserialized;
  393. if (status.code === grpc.status.OK) {
  394. if (err) {
  395. // Got a batch error, but OK status. Something went wrong
  396. callback(err);
  397. return;
  398. } else {
  399. try {
  400. deserialized = deserialize(response.read);
  401. } catch (e) {
  402. /* Change status to indicate bad server response. This will result
  403. * in passing an error to the callback */
  404. status = {
  405. code: grpc.status.INTERNAL,
  406. details: 'Failed to parse server response'
  407. };
  408. }
  409. }
  410. }
  411. if (status.code !== grpc.status.OK) {
  412. error = new Error(response.status.details);
  413. error.code = status.code;
  414. error.metadata = status.metadata;
  415. callback(error);
  416. } else {
  417. callback(null, deserialized);
  418. }
  419. stream.emit('status', status);
  420. });
  421. });
  422. return stream;
  423. }
  424. return makeClientStreamRequest;
  425. }
  426. /**
  427. * Get a function that can make server stream requests to the specified method.
  428. * @param {string} method The name of the method to request
  429. * @param {function(*):Buffer} serialize The serialization function for inputs
  430. * @param {function(Buffer)} deserialize The deserialization function for
  431. * outputs
  432. * @return {Function} makeServerStreamRequest
  433. */
  434. function makeServerStreamRequestFunction(method, serialize, deserialize) {
  435. /**
  436. * Make a server stream request with this method on the given channel with the
  437. * given argument, etc.
  438. * @this {SurfaceClient} Client object. Must have a channel member.
  439. * @param {*} argument The argument to the call. Should be serializable with
  440. * serialize
  441. * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
  442. * call
  443. * @param {Object} options Options map
  444. * @return {EventEmitter} An event emitter for stream related events
  445. */
  446. function makeServerStreamRequest(argument, metadata, options) {
  447. /* jshint validthis: true */
  448. var call = getCall(this.$channel, method, options);
  449. if (metadata === null || metadata === undefined) {
  450. metadata = new Metadata();
  451. } else {
  452. metadata = metadata.clone();
  453. }
  454. var stream = new ClientReadableStream(call, deserialize);
  455. this.$updateMetadata(this.$auth_uri, metadata, function(error, metadata) {
  456. if (error) {
  457. call.cancel();
  458. stream.emit('error', error);
  459. return;
  460. }
  461. var start_batch = {};
  462. var message = serialize(argument);
  463. if (options) {
  464. message.grpcWriteFlags = options.flags;
  465. }
  466. start_batch[grpc.opType.SEND_INITIAL_METADATA] =
  467. metadata._getCoreRepresentation();
  468. start_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
  469. start_batch[grpc.opType.SEND_MESSAGE] = message;
  470. start_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true;
  471. call.startBatch(start_batch, function(err, response) {
  472. if (err) {
  473. // The call has stopped for some reason. A non-OK status will arrive
  474. // in the other batch.
  475. return;
  476. }
  477. stream.emit('metadata', Metadata._fromCoreRepresentation(
  478. response.metadata));
  479. });
  480. var status_batch = {};
  481. status_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
  482. call.startBatch(status_batch, function(err, response) {
  483. response.status.metadata = Metadata._fromCoreRepresentation(
  484. response.status.metadata);
  485. stream.emit('status', response.status);
  486. if (response.status.code !== grpc.status.OK) {
  487. var error = new Error(response.status.details);
  488. error.code = response.status.code;
  489. error.metadata = response.status.metadata;
  490. stream.emit('error', error);
  491. return;
  492. } else {
  493. if (err) {
  494. // Got a batch error, but OK status. Something went wrong
  495. stream.emit('error', err);
  496. return;
  497. }
  498. }
  499. });
  500. });
  501. return stream;
  502. }
  503. return makeServerStreamRequest;
  504. }
  505. /**
  506. * Get a function that can make bidirectional stream requests to the specified
  507. * method.
  508. * @param {string} method The name of the method to request
  509. * @param {function(*):Buffer} serialize The serialization function for inputs
  510. * @param {function(Buffer)} deserialize The deserialization function for
  511. * outputs
  512. * @return {Function} makeBidiStreamRequest
  513. */
  514. function makeBidiStreamRequestFunction(method, serialize, deserialize) {
  515. /**
  516. * Make a bidirectional stream request with this method on the given channel.
  517. * @this {SurfaceClient} Client object. Must have a channel member.
  518. * @param {Metadata=} metadata Array of metadata key/value pairs to add to the
  519. * call
  520. * @param {Options} options Options map
  521. * @return {EventEmitter} An event emitter for stream related events
  522. */
  523. function makeBidiStreamRequest(metadata, options) {
  524. /* jshint validthis: true */
  525. var call = getCall(this.$channel, method, options);
  526. if (metadata === null || metadata === undefined) {
  527. metadata = new Metadata();
  528. } else {
  529. metadata = metadata.clone();
  530. }
  531. var stream = new ClientDuplexStream(call, serialize, deserialize);
  532. this.$updateMetadata(this.$auth_uri, metadata, function(error, metadata) {
  533. if (error) {
  534. call.cancel();
  535. stream.emit('error', error);
  536. return;
  537. }
  538. var start_batch = {};
  539. start_batch[grpc.opType.SEND_INITIAL_METADATA] =
  540. metadata._getCoreRepresentation();
  541. start_batch[grpc.opType.RECV_INITIAL_METADATA] = true;
  542. call.startBatch(start_batch, function(err, response) {
  543. if (err) {
  544. // The call has stopped for some reason. A non-OK status will arrive
  545. // in the other batch.
  546. return;
  547. }
  548. stream.emit('metadata', Metadata._fromCoreRepresentation(
  549. response.metadata));
  550. });
  551. var status_batch = {};
  552. status_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
  553. call.startBatch(status_batch, function(err, response) {
  554. response.status.metadata = Metadata._fromCoreRepresentation(
  555. response.status.metadata);
  556. stream.emit('status', response.status);
  557. if (response.status.code !== grpc.status.OK) {
  558. var error = new Error(response.status.details);
  559. error.code = response.status.code;
  560. error.metadata = response.status.metadata;
  561. stream.emit('error', error);
  562. return;
  563. } else {
  564. if (err) {
  565. // Got a batch error, but OK status. Something went wrong
  566. stream.emit('error', err);
  567. return;
  568. }
  569. }
  570. });
  571. });
  572. return stream;
  573. }
  574. return makeBidiStreamRequest;
  575. }
  576. /**
  577. * Map with short names for each of the requester maker functions. Used in
  578. * makeClientConstructor
  579. */
  580. var requester_makers = {
  581. unary: makeUnaryRequestFunction,
  582. server_stream: makeServerStreamRequestFunction,
  583. client_stream: makeClientStreamRequestFunction,
  584. bidi: makeBidiStreamRequestFunction
  585. };
  586. /**
  587. * Creates a constructor for a client with the given methods. The methods object
  588. * maps method name to an object with the following keys:
  589. * path: The path on the server for accessing the method. For example, for
  590. * protocol buffers, we use "/service_name/method_name"
  591. * requestStream: bool indicating whether the client sends a stream
  592. * resonseStream: bool indicating whether the server sends a stream
  593. * requestSerialize: function to serialize request objects
  594. * responseDeserialize: function to deserialize response objects
  595. * @param {Object} methods An object mapping method names to method attributes
  596. * @param {string} serviceName The fully qualified name of the service
  597. * @return {function(string, Object)} New client constructor
  598. */
  599. exports.makeClientConstructor = function(methods, serviceName) {
  600. /**
  601. * Create a client with the given methods
  602. * @constructor
  603. * @param {string} address The address of the server to connect to
  604. * @param {grpc.Credentials} credentials Credentials to use to connect
  605. * to the server
  606. * @param {Object} options Options to pass to the underlying channel
  607. * @param {function(string, Object, function)=} updateMetadata function to
  608. * update the metadata for each request
  609. */
  610. function Client(address, credentials, options, updateMetadata) {
  611. if (!updateMetadata) {
  612. updateMetadata = function(uri, metadata, callback) {
  613. callback(null, metadata);
  614. };
  615. }
  616. if (!options) {
  617. options = {};
  618. }
  619. options['grpc.primary_user_agent'] = 'grpc-node/' + version;
  620. /* Private fields use $ as a prefix instead of _ because it is an invalid
  621. * prefix of a method name */
  622. this.$channel = new grpc.Channel(address, credentials, options);
  623. // Remove the optional DNS scheme, trailing port, and trailing backslash
  624. address = address.replace(/^(dns:\/{3})?([^:\/]+)(:\d+)?\/?$/, '$2');
  625. this.$server_address = address;
  626. this.$auth_uri = 'https://' + this.$server_address + '/' + serviceName;
  627. this.$updateMetadata = updateMetadata;
  628. }
  629. _.each(methods, function(attrs, name) {
  630. var method_type;
  631. if (_.startsWith(name, '$')) {
  632. throw new Error('Method names cannot start with $');
  633. }
  634. if (attrs.requestStream) {
  635. if (attrs.responseStream) {
  636. method_type = 'bidi';
  637. } else {
  638. method_type = 'client_stream';
  639. }
  640. } else {
  641. if (attrs.responseStream) {
  642. method_type = 'server_stream';
  643. } else {
  644. method_type = 'unary';
  645. }
  646. }
  647. var serialize = attrs.requestSerialize;
  648. var deserialize = attrs.responseDeserialize;
  649. Client.prototype[name] = requester_makers[method_type](
  650. attrs.path, serialize, deserialize);
  651. Client.prototype[name].serialize = serialize;
  652. Client.prototype[name].deserialize = deserialize;
  653. });
  654. return Client;
  655. };
  656. /**
  657. * Return the underlying channel object for the specified client
  658. * @param {Client} client
  659. * @return {Channel} The channel
  660. */
  661. exports.getClientChannel = function(client) {
  662. return client.$channel;
  663. };
  664. /**
  665. * Wait for the client to be ready. The callback will be called when the
  666. * client has successfully connected to the server, and it will be called
  667. * with an error if the attempt to connect to the server has unrecoverablly
  668. * failed or if the deadline expires. This function will make the channel
  669. * start connecting if it has not already done so.
  670. * @param {Client} client The client to wait on
  671. * @param {(Date|Number)} deadline When to stop waiting for a connection. Pass
  672. * Infinity to wait forever.
  673. * @param {function(Error)} callback The callback to call when done attempting
  674. * to connect.
  675. */
  676. exports.waitForClientReady = function(client, deadline, callback) {
  677. var checkState = function(err) {
  678. if (err) {
  679. callback(new Error('Failed to connect before the deadline'));
  680. }
  681. var new_state = client.$channel.getConnectivityState(true);
  682. if (new_state === grpc.connectivityState.READY) {
  683. callback();
  684. } else if (new_state === grpc.connectivityState.FATAL_FAILURE) {
  685. callback(new Error('Failed to connect to server'));
  686. } else {
  687. client.$channel.watchConnectivityState(new_state, deadline, checkState);
  688. }
  689. };
  690. checkState();
  691. };
  692. /**
  693. * Creates a constructor for clients for the given service
  694. * @param {ProtoBuf.Reflect.Service} service The service to generate a client
  695. * for
  696. * @return {function(string, Object)} New client constructor
  697. */
  698. exports.makeProtobufClientConstructor = function(service) {
  699. var method_attrs = common.getProtobufServiceAttrs(service, service.name);
  700. var Client = exports.makeClientConstructor(
  701. method_attrs, common.fullyQualifiedName(service));
  702. Client.service = service;
  703. return Client;
  704. };
  705. /**
  706. * Map of status code names to status codes
  707. */
  708. exports.status = grpc.status;
  709. /**
  710. * See docs for client.callError
  711. */
  712. exports.callError = grpc.callError;
  713. </code></pre>
  714. </article>
  715. </section>
  716. </div>
  717. <nav>
  718. <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_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#getGoogleAuthDelegate">getGoogleAuthDelegate</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>
  719. </nav>
  720. <br class="clear">
  721. <footer>
  722. Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.3</a> on Thu Oct 29 2015 13:07:25 GMT-0700 (PDT)
  723. </footer>
  724. <script> prettyPrint(); </script>
  725. <script src="scripts/linenumber.js"> </script>
  726. </body>
  727. </html>