client.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 grpc = require('bindings')('grpc.node');
  34. var common = require('./common');
  35. var Duplex = require('stream').Duplex;
  36. var util = require('util');
  37. util.inherits(GrpcClientStream, Duplex);
  38. /**
  39. * Class for representing a gRPC client side stream as a Node stream. Extends
  40. * from stream.Duplex.
  41. * @constructor
  42. * @param {grpc.Call} call Call object to proxy
  43. * @param {object} options Stream options
  44. */
  45. function GrpcClientStream(call, options) {
  46. Duplex.call(this, options);
  47. var self = this;
  48. // Indicates that we can start reading and have not received a null read
  49. var can_read = false;
  50. // Indicates that a read is currently pending
  51. var reading = false;
  52. // Indicates that we can call startWrite
  53. var can_write = false;
  54. // Indicates that a write is currently pending
  55. var writing = false;
  56. this._call = call;
  57. /**
  58. * Callback to handle receiving a READ event. Pushes the data from that event
  59. * onto the read queue and starts reading again if applicable.
  60. * @param {grpc.Event} event The READ event object
  61. */
  62. function readCallback(event) {
  63. var data = event.data;
  64. if (self.push(data)) {
  65. if (data == null) {
  66. // Disable starting to read after null read was received
  67. can_read = false;
  68. reading = false;
  69. } else {
  70. call.startRead(readCallback);
  71. }
  72. } else {
  73. // Indicate that reading can be resumed by calling startReading
  74. reading = false;
  75. }
  76. };
  77. /**
  78. * Initiate a read, which continues until self.push returns false (indicating
  79. * that reading should be paused) or data is null (indicating that there is no
  80. * more data to read).
  81. */
  82. function startReading() {
  83. call.startRead(readCallback);
  84. }
  85. // TODO(mlumish): possibly change queue implementation due to shift slowness
  86. var write_queue = [];
  87. /**
  88. * Write the next chunk of data in the write queue if there is one. Otherwise
  89. * indicate that there is no pending write. When the write succeeds, this
  90. * function is called again.
  91. */
  92. function writeNext() {
  93. if (write_queue.length > 0) {
  94. writing = true;
  95. var next = write_queue.shift();
  96. var writeCallback = function(event) {
  97. next.callback();
  98. writeNext();
  99. };
  100. call.startWrite(next.chunk, writeCallback, 0);
  101. } else {
  102. writing = false;
  103. }
  104. }
  105. call.startInvoke(function(event) {
  106. can_read = true;
  107. can_write = true;
  108. startReading();
  109. writeNext();
  110. }, function(event) {
  111. self.emit('metadata', event.data);
  112. }, function(event) {
  113. self.emit('status', event.data);
  114. }, 0);
  115. this.on('finish', function() {
  116. call.writesDone(function() {});
  117. });
  118. /**
  119. * Indicate that reads should start, and start them if the INVOKE_ACCEPTED
  120. * event has been received.
  121. */
  122. this._enableRead = function() {
  123. if (!reading) {
  124. reading = true;
  125. if (can_read) {
  126. startReading();
  127. }
  128. }
  129. };
  130. /**
  131. * Push the chunk onto the write queue, and write from the write queue if
  132. * there is not a pending write
  133. * @param {Buffer} chunk The chunk of data to write
  134. * @param {function(Error=)} callback The callback to call when the write
  135. * completes
  136. */
  137. this._tryWrite = function(chunk, callback) {
  138. write_queue.push({chunk: chunk, callback: callback});
  139. if (can_write && !writing) {
  140. writeNext();
  141. }
  142. };
  143. }
  144. /**
  145. * Start reading. This is an implementation of a method needed for implementing
  146. * stream.Readable.
  147. * @param {number} size Ignored
  148. */
  149. GrpcClientStream.prototype._read = function(size) {
  150. this._enableRead();
  151. };
  152. /**
  153. * Attempt to write the given chunk. Calls the callback when done. This is an
  154. * implementation of a method needed for implementing stream.Writable.
  155. * @param {Buffer} chunk The chunk to write
  156. * @param {string} encoding Ignored
  157. * @param {function(Error=)} callback Ignored
  158. */
  159. GrpcClientStream.prototype._write = function(chunk, encoding, callback) {
  160. this._tryWrite(chunk, callback);
  161. };
  162. /**
  163. * Make a request on the channel to the given method with the given arguments
  164. * @param {grpc.Channel} channel The channel on which to make the request
  165. * @param {string} method The method to request
  166. * @param {array=} metadata Array of metadata key/value pairs to add to the call
  167. * @param {(number|Date)=} deadline The deadline for processing this request.
  168. * Defaults to infinite future.
  169. * @return {stream=} The stream of responses
  170. */
  171. function makeRequest(channel,
  172. method,
  173. metadata,
  174. deadline) {
  175. if (deadline === undefined) {
  176. deadline = Infinity;
  177. }
  178. var call = new grpc.Call(channel, method, deadline);
  179. if (metadata) {
  180. call.addMetadata(metadata);
  181. }
  182. return new GrpcClientStream(call);
  183. }
  184. /**
  185. * See documentation for makeRequest above
  186. */
  187. exports.makeRequest = makeRequest;
  188. /**
  189. * Represents a client side gRPC channel associated with a single host.
  190. */
  191. exports.Channel = grpc.Channel;
  192. /**
  193. * Status name to code number mapping
  194. */
  195. exports.status = grpc.status;
  196. /**
  197. * Call error name to code number mapping
  198. */
  199. exports.callError = grpc.callError;