surface_client.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /*
  2. *
  3. * Copyright 2014, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. var _ = require('underscore');
  34. var client = require('./client.js');
  35. var EventEmitter = require('events').EventEmitter;
  36. var stream = require('stream');
  37. var Readable = stream.Readable;
  38. var Writable = stream.Writable;
  39. var Duplex = stream.Duplex;
  40. var util = require('util');
  41. function forwardEvent(fromEmitter, toEmitter, event) {
  42. fromEmitter.on(event, function forward() {
  43. _.partial(toEmitter.emit, event).apply(toEmitter, arguments);
  44. });
  45. }
  46. util.inherits(ClientReadableObjectStream, Readable);
  47. /**
  48. * Class for representing a gRPC server streaming call as a Node stream on the
  49. * client side. Extends from stream.Readable.
  50. * @constructor
  51. * @param {stream} stream Underlying binary Duplex stream for the call
  52. * @param {function(Buffer)} deserialize Function for deserializing binary data
  53. * @param {object} options Stream options
  54. */
  55. function ClientReadableObjectStream(stream, deserialize, options) {
  56. options = _.extend(options, {objectMode: true});
  57. Readable.call(this, options);
  58. this._stream = stream;
  59. var self = this;
  60. forwardEvent(stream, this, 'status');
  61. forwardEvent(stream, this, 'metadata');
  62. this._stream.on('data', function forwardData(chunk) {
  63. if (!self.push(deserialize(chunk))) {
  64. self._stream.pause();
  65. }
  66. });
  67. this._stream.pause();
  68. }
  69. util.inherits(ClientWritableObjectStream, Writable);
  70. /**
  71. * Class for representing a gRPC client streaming call as a Node stream on the
  72. * client side. Extends from stream.Writable.
  73. * @constructor
  74. * @param {stream} stream Underlying binary Duplex stream for the call
  75. * @param {function(*):Buffer} serialize Function for serializing objects
  76. * @param {object} options Stream options
  77. */
  78. function ClientWritableObjectStream(stream, serialize, options) {
  79. options = _.extend(options, {objectMode: true});
  80. Writable.call(this, options);
  81. this._stream = stream;
  82. this._serialize = serialize;
  83. forwardEvent(stream, this, 'status');
  84. forwardEvent(stream, this, 'metadata');
  85. this.on('finish', function() {
  86. this._stream.end();
  87. });
  88. }
  89. util.inherits(ClientBidiObjectStream, Duplex);
  90. /**
  91. * Class for representing a gRPC bidi streaming call as a Node stream on the
  92. * client side. Extends from stream.Duplex.
  93. * @constructor
  94. * @param {stream} stream Underlying binary Duplex stream for the call
  95. * @param {function(*):Buffer} serialize Function for serializing objects
  96. * @param {function(Buffer)} deserialize Function for deserializing binary data
  97. * @param {object} options Stream options
  98. */
  99. function ClientBidiObjectStream(stream, serialize, deserialize, options) {
  100. options = _.extend(options, {objectMode: true});
  101. Duplex.call(this, options);
  102. this._stream = stream;
  103. this._serialize = serialize;
  104. var self = this;
  105. forwardEvent(stream, this, 'status');
  106. forwardEvent(stream, this, 'metadata');
  107. this._stream.on('data', function forwardData(chunk) {
  108. if (!self.push(deserialize(chunk))) {
  109. self._stream.pause();
  110. }
  111. });
  112. this._stream.pause();
  113. this.on('finish', function() {
  114. this._stream.end();
  115. });
  116. }
  117. /**
  118. * _read implementation for both types of streams that allow reading.
  119. * @this {ClientReadableObjectStream|ClientBidiObjectStream}
  120. * @param {number} size Ignored
  121. */
  122. function _read(size) {
  123. this._stream.resume();
  124. }
  125. /**
  126. * See docs for _read
  127. */
  128. ClientReadableObjectStream.prototype._read = _read;
  129. /**
  130. * See docs for _read
  131. */
  132. ClientBidiObjectStream.prototype._read = _read;
  133. /**
  134. * _write implementation for both types of streams that allow writing
  135. * @this {ClientWritableObjectStream|ClientBidiObjectStream}
  136. * @param {*} chunk The value to write to the stream
  137. * @param {string} encoding Ignored
  138. * @param {function(Error)} callback Callback to call when finished writing
  139. */
  140. function _write(chunk, encoding, callback) {
  141. this._stream.write(this._serialize(chunk), encoding, callback);
  142. }
  143. /**
  144. * See docs for _write
  145. */
  146. ClientWritableObjectStream.prototype._write = _write;
  147. /**
  148. * See docs for _write
  149. */
  150. ClientBidiObjectStream.prototype._write = _write;
  151. /**
  152. * Get a function that can make unary requests to the specified method.
  153. * @param {string} method The name of the method to request
  154. * @param {function(*):Buffer} serialize The serialization function for inputs
  155. * @param {function(Buffer)} deserialize The deserialization function for
  156. * outputs
  157. * @return {Function} makeUnaryRequest
  158. */
  159. function makeUnaryRequestFunction(method, serialize, deserialize) {
  160. /**
  161. * Make a unary request with this method on the given channel with the given
  162. * argument, callback, etc.
  163. * @this {SurfaceClient} Client object. Must have a channel member.
  164. * @param {*} argument The argument to the call. Should be serializable with
  165. * serialize
  166. * @param {function(?Error, value=)} callback The callback to for when the
  167. * response is received
  168. * @param {array=} metadata Array of metadata key/value pairs to add to the
  169. * call
  170. * @param {(number|Date)=} deadline The deadline for processing this request.
  171. * Defaults to infinite future
  172. * @return {EventEmitter} An event emitter for stream related events
  173. */
  174. function makeUnaryRequest(argument, callback, metadata, deadline) {
  175. var stream = client.makeRequest(this.channel, method, metadata, deadline);
  176. var emitter = new EventEmitter();
  177. forwardEvent(stream, emitter, 'status');
  178. forwardEvent(stream, emitter, 'metadata');
  179. stream.write(serialize(argument));
  180. stream.end();
  181. stream.on('data', function forwardData(chunk) {
  182. try {
  183. callback(null, deserialize(chunk));
  184. } catch (e) {
  185. callback(e);
  186. }
  187. });
  188. return emitter;
  189. }
  190. return makeUnaryRequest;
  191. }
  192. /**
  193. * Get a function that can make client stream requests to the specified method.
  194. * @param {string} method The name of the method to request
  195. * @param {function(*):Buffer} serialize The serialization function for inputs
  196. * @param {function(Buffer)} deserialize The deserialization function for
  197. * outputs
  198. * @return {Function} makeClientStreamRequest
  199. */
  200. function makeClientStreamRequestFunction(method, serialize, deserialize) {
  201. /**
  202. * Make a client stream request with this method on the given channel with the
  203. * given callback, etc.
  204. * @this {SurfaceClient} Client object. Must have a channel member.
  205. * @param {function(?Error, value=)} callback The callback to for when the
  206. * response is received
  207. * @param {array=} metadata Array of metadata key/value pairs to add to the
  208. * call
  209. * @param {(number|Date)=} deadline The deadline for processing this request.
  210. * Defaults to infinite future
  211. * @return {EventEmitter} An event emitter for stream related events
  212. */
  213. function makeClientStreamRequest(callback, metadata, deadline) {
  214. var stream = client.makeRequest(this.channel, method, metadata, deadline);
  215. var obj_stream = new ClientWritableObjectStream(stream, serialize, {});
  216. stream.on('data', function forwardData(chunk) {
  217. try {
  218. callback(null, deserialize(chunk));
  219. } catch (e) {
  220. callback(e);
  221. }
  222. });
  223. return obj_stream;
  224. }
  225. return makeClientStreamRequest;
  226. }
  227. /**
  228. * Get a function that can make server stream requests to the specified method.
  229. * @param {string} method The name of the method to request
  230. * @param {function(*):Buffer} serialize The serialization function for inputs
  231. * @param {function(Buffer)} deserialize The deserialization function for
  232. * outputs
  233. * @return {Function} makeServerStreamRequest
  234. */
  235. function makeServerStreamRequestFunction(method, serialize, deserialize) {
  236. /**
  237. * Make a server stream request with this method on the given channel with the
  238. * given argument, etc.
  239. * @this {SurfaceClient} Client object. Must have a channel member.
  240. * @param {*} argument The argument to the call. Should be serializable with
  241. * serialize
  242. * @param {array=} metadata Array of metadata key/value pairs to add to the
  243. * call
  244. * @param {(number|Date)=} deadline The deadline for processing this request.
  245. * Defaults to infinite future
  246. * @return {EventEmitter} An event emitter for stream related events
  247. */
  248. function makeServerStreamRequest(argument, metadata, deadline) {
  249. var stream = client.makeRequest(this.channel, method, metadata, deadline);
  250. var obj_stream = new ClientReadableObjectStream(stream, deserialize, {});
  251. stream.write(serialize(argument));
  252. stream.end();
  253. return obj_stream;
  254. }
  255. return makeServerStreamRequest;
  256. }
  257. /**
  258. * Get a function that can make bidirectional stream requests to the specified
  259. * method.
  260. * @param {string} method The name of the method to request
  261. * @param {function(*):Buffer} serialize The serialization function for inputs
  262. * @param {function(Buffer)} deserialize The deserialization function for
  263. * outputs
  264. * @return {Function} makeBidiStreamRequest
  265. */
  266. function makeBidiStreamRequestFunction(method, serialize, deserialize) {
  267. /**
  268. * Make a bidirectional stream request with this method on the given channel.
  269. * @this {SurfaceClient} Client object. Must have a channel member.
  270. * @param {array=} metadata Array of metadata key/value pairs to add to the
  271. * call
  272. * @param {(number|Date)=} deadline The deadline for processing this request.
  273. * Defaults to infinite future
  274. * @return {EventEmitter} An event emitter for stream related events
  275. */
  276. function makeBidiStreamRequest(metadata, deadline) {
  277. var stream = client.makeRequest(this.channel, method, metadata, deadline);
  278. var obj_stream = new ClientBidiObjectStream(stream,
  279. serialize,
  280. deserialize,
  281. {});
  282. return obj_stream;
  283. }
  284. return makeBidiStreamRequest;
  285. }
  286. /**
  287. * Map with short names for each of the requester maker functions. Used in
  288. * makeClientConstructor
  289. */
  290. var requester_makers = {
  291. unary: makeUnaryRequestFunction,
  292. server_stream: makeServerStreamRequestFunction,
  293. client_stream: makeClientStreamRequestFunction,
  294. bidi: makeBidiStreamRequestFunction
  295. }
  296. /**
  297. * Creates a constructor for clients with a service defined by the methods
  298. * object. The methods object has string keys and values of this form:
  299. * {serialize: function, deserialize: function, client_stream: bool,
  300. * server_stream: bool}
  301. * @param {!Object<string, Object>} methods Method descriptor for each method
  302. * the client should expose
  303. * @param {string} prefix The prefix to prepend to each method name
  304. * @return {function(string, Object)} New client constructor
  305. */
  306. function makeClientConstructor(methods, prefix) {
  307. /**
  308. * Create a client with the given methods
  309. * @constructor
  310. * @param {string} address The address of the server to connect to
  311. * @param {Object} options Options to pass to the underlying channel
  312. */
  313. function SurfaceClient(address, options) {
  314. this.channel = new client.Channel(address, options);
  315. }
  316. _.each(methods, function(method, name) {
  317. var method_type;
  318. if (method.client_stream) {
  319. if (method.server_stream) {
  320. method_type = 'bidi';
  321. } else {
  322. method_type = 'client_stream';
  323. }
  324. } else {
  325. if (method.server_stream) {
  326. method_type = 'server_stream';
  327. } else {
  328. method_type = 'unary';
  329. }
  330. }
  331. SurfaceClient.prototype[name] = requester_makers[method_type](
  332. prefix + name,
  333. method.serialize,
  334. method.deserialize);
  335. });
  336. return SurfaceClient;
  337. }
  338. exports.makeClientConstructor = makeClientConstructor;
  339. /**
  340. * See docs for client.status
  341. */
  342. exports.status = client.status;
  343. /**
  344. * See docs for client.callError
  345. */
  346. exports.callError = client.callError;