src_client.js.html 33 KB

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