interop_server.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. *
  3. * Copyright 2015, 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. 'use strict';
  34. var fs = require('fs');
  35. var path = require('path');
  36. var _ = require('lodash');
  37. var grpc = require('..');
  38. var testProto = grpc.load({
  39. root: __dirname + '/../../..',
  40. file: 'test/proto/test.proto'}).grpc.testing;
  41. var ECHO_INITIAL_KEY = 'x-grpc-test-echo-initial';
  42. var ECHO_TRAILING_KEY = 'x-grpc-test-echo-trailing-bin';
  43. var incompressible_data = fs.readFileSync(
  44. __dirname + '/../../../test/cpp/interop/rnd.dat');
  45. /**
  46. * Create a buffer filled with size zeroes
  47. * @param {number} size The length of the buffer
  48. * @return {Buffer} The new buffer
  49. */
  50. function zeroBuffer(size) {
  51. var zeros = new Buffer(size);
  52. zeros.fill(0);
  53. return zeros;
  54. }
  55. /**
  56. * Echos a header metadata item as specified in the interop spec.
  57. * @param {Call} call The call to echo metadata on
  58. */
  59. function echoHeader(call) {
  60. var echo_initial = call.metadata.get(ECHO_INITIAL_KEY);
  61. if (echo_initial.length > 0) {
  62. var response_metadata = new grpc.Metadata();
  63. response_metadata.set(ECHO_INITIAL_KEY, echo_initial[0]);
  64. call.sendMetadata(response_metadata);
  65. }
  66. }
  67. /**
  68. * Gets the trailer metadata that should be echoed when the call is done,
  69. * as specified in the interop spec.
  70. * @param {Call} call The call to get metadata from
  71. * @return {grpc.Metadata} The metadata to send as a trailer
  72. */
  73. function getEchoTrailer(call) {
  74. var echo_trailer = call.metadata.get(ECHO_TRAILING_KEY);
  75. var response_trailer = new grpc.Metadata();
  76. if (echo_trailer.length > 0) {
  77. response_trailer.set(ECHO_TRAILING_KEY, echo_trailer[0]);
  78. }
  79. return response_trailer;
  80. }
  81. function getPayload(payload_type, size) {
  82. if (payload_type === 'RANDOM') {
  83. payload_type = ['COMPRESSABLE',
  84. 'UNCOMPRESSABLE'][Math.random() < 0.5 ? 0 : 1];
  85. }
  86. var body;
  87. switch (payload_type) {
  88. case 'COMPRESSABLE': body = zeroBuffer(size); break;
  89. case 'UNCOMPRESSABLE': incompressible_data.slice(size); break;
  90. }
  91. return {type: payload_type, body: body};
  92. }
  93. /**
  94. * Respond to an empty parameter with an empty response.
  95. * NOTE: this currently does not work due to issue #137
  96. * @param {Call} call Call to handle
  97. * @param {function(Error, Object)} callback Callback to call with result
  98. * or error
  99. */
  100. function handleEmpty(call, callback) {
  101. echoHeader(call);
  102. callback(null, {}, getEchoTrailer(call));
  103. }
  104. /**
  105. * Handle a unary request by sending the requested payload
  106. * @param {Call} call Call to handle
  107. * @param {function(Error, Object)} callback Callback to call with result or
  108. * error
  109. */
  110. function handleUnary(call, callback) {
  111. echoHeader(call);
  112. var req = call.request;
  113. if (req.response_status) {
  114. var status = req.response_status;
  115. status.metadata = getEchoTrailer(call);
  116. callback(status);
  117. return;
  118. }
  119. var payload = getPayload(req.response_type, req.response_size);
  120. callback(null, {payload: payload},
  121. getEchoTrailer(call));
  122. }
  123. /**
  124. * Respond to a streaming call with the total size of all payloads
  125. * @param {Call} call Call to handle
  126. * @param {function(Error, Object)} callback Callback to call with result or
  127. * error
  128. */
  129. function handleStreamingInput(call, callback) {
  130. echoHeader(call);
  131. var aggregate_size = 0;
  132. call.on('data', function(value) {
  133. aggregate_size += value.payload.body.length;
  134. });
  135. call.on('end', function() {
  136. callback(null, {aggregated_payload_size: aggregate_size},
  137. getEchoTrailer(call));
  138. });
  139. }
  140. /**
  141. * Respond to a payload request with a stream of the requested payloads
  142. * @param {Call} call Call to handle
  143. */
  144. function handleStreamingOutput(call) {
  145. echoHeader(call);
  146. var req = call.request;
  147. if (req.response_status) {
  148. var status = req.response_status;
  149. status.metadata = getEchoTrailer(call);
  150. call.emit('error', status);
  151. return;
  152. }
  153. _.each(req.response_parameters, function(resp_param) {
  154. call.write({payload: getPayload(req.response_type, resp_param.size)});
  155. });
  156. call.end(getEchoTrailer(call));
  157. }
  158. /**
  159. * Respond to a stream of payload requests with a stream of payload responses as
  160. * they arrive.
  161. * @param {Call} call Call to handle
  162. */
  163. function handleFullDuplex(call) {
  164. echoHeader(call);
  165. call.on('data', function(value) {
  166. if (value.response_status) {
  167. var status = value.response_status;
  168. status.metadata = getEchoTrailer(call);
  169. call.emit('error', status);
  170. return;
  171. }
  172. _.each(value.response_parameters, function(resp_param) {
  173. call.write({payload: getPayload(value.response_type, resp_param.size)});
  174. });
  175. });
  176. call.on('end', function() {
  177. call.end(getEchoTrailer(call));
  178. });
  179. }
  180. /**
  181. * Respond to a stream of payload requests with a stream of payload responses
  182. * after all requests have arrived
  183. * @param {Call} call Call to handle
  184. */
  185. function handleHalfDuplex(call) {
  186. call.emit('error', Error('HalfDuplexCall not yet implemented'));
  187. }
  188. /**
  189. * Get a server object bound to the given port
  190. * @param {string} port Port to which to bind
  191. * @param {boolean} tls Indicates that the bound port should use TLS
  192. * @return {{server: Server, port: number}} Server object bound to the support,
  193. * and port number that the server is bound to
  194. */
  195. function getServer(port, tls) {
  196. // TODO(mlumish): enable TLS functionality
  197. var options = {};
  198. var server_creds;
  199. if (tls) {
  200. var key_path = path.join(__dirname, '../test/data/server1.key');
  201. var pem_path = path.join(__dirname, '../test/data/server1.pem');
  202. var key_data = fs.readFileSync(key_path);
  203. var pem_data = fs.readFileSync(pem_path);
  204. server_creds = grpc.ServerCredentials.createSsl(null,
  205. [{private_key: key_data,
  206. cert_chain: pem_data}]);
  207. } else {
  208. server_creds = grpc.ServerCredentials.createInsecure();
  209. }
  210. var server = new grpc.Server(options);
  211. server.addProtoService(testProto.TestService.service, {
  212. emptyCall: handleEmpty,
  213. unaryCall: handleUnary,
  214. streamingOutputCall: handleStreamingOutput,
  215. streamingInputCall: handleStreamingInput,
  216. fullDuplexCall: handleFullDuplex,
  217. halfDuplexCall: handleHalfDuplex
  218. });
  219. var port_num = server.bind('0.0.0.0:' + port, server_creds);
  220. return {server: server, port: port_num};
  221. }
  222. if (require.main === module) {
  223. var parseArgs = require('minimist');
  224. var argv = parseArgs(process.argv, {
  225. string: ['port', 'use_tls']
  226. });
  227. var server_obj = getServer(argv.port, argv.use_tls === 'true');
  228. console.log('Server attaching to port ' + argv.port);
  229. server_obj.server.start();
  230. }
  231. /**
  232. * See docs for getServer
  233. */
  234. exports.getServer = getServer;