src_client.js.html 32 KB

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