diff options
Diffstat (limited to 'src/node/examples')
-rw-r--r-- | src/node/examples/math.proto | 80 | ||||
-rw-r--r-- | src/node/examples/math_server.js | 130 | ||||
-rw-r--r-- | src/node/examples/perf_test.js | 119 | ||||
-rw-r--r-- | src/node/examples/qps_test.js | 137 | ||||
-rw-r--r-- | src/node/examples/stock.proto | 62 | ||||
-rw-r--r-- | src/node/examples/stock_client.js | 47 | ||||
-rw-r--r-- | src/node/examples/stock_server.js | 87 |
7 files changed, 0 insertions, 662 deletions
diff --git a/src/node/examples/math.proto b/src/node/examples/math.proto deleted file mode 100644 index 311e148c02..0000000000 --- a/src/node/examples/math.proto +++ /dev/null @@ -1,80 +0,0 @@ - -// Copyright 2015, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package math; - -message DivArgs { - int64 dividend = 1; - int64 divisor = 2; -} - -message DivReply { - int64 quotient = 1; - int64 remainder = 2; -} - -message FibArgs { - int64 limit = 1; -} - -message Num { - int64 num = 1; -} - -message FibReply { - int64 count = 1; -} - -service Math { - // Div divides args.dividend by args.divisor and returns the quotient and - // remainder. - rpc Div (DivArgs) returns (DivReply) { - } - - // DivMany accepts an arbitrary number of division args from the client stream - // and sends back the results in the reply stream. The stream continues until - // the client closes its end; the server does the same after sending all the - // replies. The stream ends immediately if either end aborts. - rpc DivMany (stream DivArgs) returns (stream DivReply) { - } - - // Fib generates numbers in the Fibonacci sequence. If args.limit > 0, Fib - // generates up to limit numbers; otherwise it continues until the call is - // canceled. Unlike Fib above, Fib has no final FibReply. - rpc Fib (FibArgs) returns (stream Num) { - } - - // Sum sums a stream of numbers, returning the final result once the stream - // is closed. - rpc Sum (stream Num) returns (Num) { - } -} diff --git a/src/node/examples/math_server.js b/src/node/examples/math_server.js deleted file mode 100644 index a4b237aeeb..0000000000 --- a/src/node/examples/math_server.js +++ /dev/null @@ -1,130 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -'use strict'; - -var grpc = require('..'); -var math = grpc.load(__dirname + '/math.proto').math; - -/** - * Server function for division. Provides the /Math/DivMany and /Math/Div - * functions (Div is just DivMany with only one stream element). For each - * DivArgs parameter, responds with a DivReply with the results of the division - * @param {Object} call The object containing request and cancellation info - * @param {function(Error, *)} cb Response callback - */ -function mathDiv(call, cb) { - var req = call.request; - // Unary + is explicit coersion to integer - if (+req.divisor === 0) { - cb(new Error('cannot divide by zero')); - } else { - cb(null, { - quotient: req.dividend / req.divisor, - remainder: req.dividend % req.divisor - }); - } -} - -/** - * Server function for Fibonacci numbers. Provides the /Math/Fib function. Reads - * a single parameter that indicates the number of responses, and then responds - * with a stream of that many Fibonacci numbers. - * @param {stream} stream The stream for sending responses. - */ -function mathFib(stream) { - // Here, call is a standard writable Node object Stream - var previous = 0, current = 1; - for (var i = 0; i < stream.request.limit; i++) { - stream.write({num: current}); - var temp = current; - current += previous; - previous = temp; - } - stream.end(); -} - -/** - * Server function for summation. Provides the /Math/Sum function. Reads a - * stream of number parameters, then responds with their sum. - * @param {stream} call The stream of arguments. - * @param {function(Error, *)} cb Response callback - */ -function mathSum(call, cb) { - // Here, call is a standard readable Node object Stream - var sum = 0; - call.on('data', function(data) { - sum += (+data.num); - }); - call.on('end', function() { - cb(null, {num: sum}); - }); -} - -function mathDivMany(stream) { - stream.on('data', function(div_args) { - if (+div_args.divisor === 0) { - stream.emit('error', new Error('cannot divide by zero')); - } else { - stream.write({ - quotient: div_args.dividend / div_args.divisor, - remainder: div_args.dividend % div_args.divisor - }); - } - }); - stream.on('end', function() { - stream.end(); - }); -} - -function getMathServer() { - var server = new grpc.Server(); - server.addProtoService(math.Math.service, { - div: mathDiv, - fib: mathFib, - sum: mathSum, - divMany: mathDivMany - }); - return server; -} - -if (require.main === module) { - var server = getMathServer(); - server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure()); - server.start(); -} - -/** - * See docs for server - */ -module.exports = getMathServer; diff --git a/src/node/examples/perf_test.js b/src/node/examples/perf_test.js deleted file mode 100644 index ba8fbf88d2..0000000000 --- a/src/node/examples/perf_test.js +++ /dev/null @@ -1,119 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -'use strict'; - -var grpc = require('..'); -var testProto = grpc.load(__dirname + '/../interop/test.proto').grpc.testing; -var _ = require('lodash'); -var interop_server = require('../interop/interop_server.js'); - -function runTest(iterations, callback) { - var testServer = interop_server.getServer(0, false); - testServer.server.start(); - var client = new testProto.TestService('localhost:' + testServer.port, - grpc.Credentials.createInsecure()); - - function runIterations(finish) { - var start = process.hrtime(); - var intervals = []; - function next(i) { - if (i >= iterations) { - testServer.server.shutdown(); - var totalDiff = process.hrtime(start); - finish({ - total: totalDiff[0] * 1000000 + totalDiff[1] / 1000, - intervals: intervals - }); - } else{ - var deadline = new Date(); - deadline.setSeconds(deadline.getSeconds() + 3); - var startTime = process.hrtime(); - client.emptyCall({}, function(err, resp) { - var timeDiff = process.hrtime(startTime); - intervals[i] = timeDiff[0] * 1000000 + timeDiff[1] / 1000; - next(i+1); - }, {}, {deadline: deadline}); - } - } - next(0); - } - - function warmUp(num) { - var pending = num; - function startCall() { - client.emptyCall({}, function(err, resp) { - pending--; - if (pending === 0) { - runIterations(callback); - } - }); - } - for (var i = 0; i < num; i++) { - startCall(); - } - } - warmUp(100); -} - -function percentile(arr, pct) { - if (pct > 99) { - pct = 99; - } - if (pct < 0) { - pct = 0; - } - var index = Math.floor(arr.length * pct / 100); - return arr[index]; -} - -if (require.main === module) { - var count; - if (process.argv.length >= 3) { - count = process.argv[2]; - } else { - count = 100; - } - runTest(count, function(results) { - var sorted_intervals = _.sortBy(results.intervals, _.identity); - console.log('count:', count); - console.log('total time:', results.total, 'us'); - console.log('median:', percentile(sorted_intervals, 50), 'us'); - console.log('90th percentile:', percentile(sorted_intervals, 90), 'us'); - console.log('95th percentile:', percentile(sorted_intervals, 95), 'us'); - console.log('99th percentile:', percentile(sorted_intervals, 99), 'us'); - console.log('QPS:', (count / results.total) * 1000000); - }); -} - -module.exports = runTest; diff --git a/src/node/examples/qps_test.js b/src/node/examples/qps_test.js deleted file mode 100644 index ec968b8540..0000000000 --- a/src/node/examples/qps_test.js +++ /dev/null @@ -1,137 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -/** - * This script runs a QPS test. It sends requests for a specified length of time - * with a specified number pending at any one time. It then outputs the measured - * QPS. Usage: - * node qps_test.js [--concurrent=count] [--time=seconds] - * concurrent defaults to 100 and time defaults to 10 - */ - -'use strict'; - -var async = require('async'); -var parseArgs = require('minimist'); - -var grpc = require('..'); -var testProto = grpc.load(__dirname + '/../interop/test.proto').grpc.testing; -var interop_server = require('../interop/interop_server.js'); - -/** - * Runs the QPS test. Sends requests constantly for the given number of seconds, - * and keeps concurrent_calls requests pending at all times. When the test ends, - * the callback is called with the number of calls that completed within the - * time limit. - * @param {number} concurrent_calls The number of calls to have pending - * simultaneously - * @param {number} seconds The number of seconds to run the test for - * @param {function(Error, number)} callback Callback for test completion - */ -function runTest(concurrent_calls, seconds, callback) { - var testServer = interop_server.getServer(0, false); - testServer.server.start(); - var client = new testProto.TestService('localhost:' + testServer.port, - grpc.Credentials.createInsecure()); - - var warmup_num = 100; - - /** - * Warms up the client to avoid counting startup time in the test result - * @param {function(Error)} callback Called when warmup is complete - */ - function warmUp(callback) { - var pending = warmup_num; - function startCall() { - client.emptyCall({}, function(err, resp) { - if (err) { - callback(err); - return; - } - pending--; - if (pending === 0) { - callback(null); - } - }); - } - for (var i = 0; i < warmup_num; i++) { - startCall(); - } - } - /** - * Run the QPS test. Starts concurrent_calls requests, then starts a new - * request whenever one completes until time runs out. - * @param {function(Error, number)} callback Called when the test is complete. - * The second argument is the number of calls that finished within the - * time limit - */ - function run(callback) { - var running = 0; - var count = 0; - var start = process.hrtime(); - function responseCallback(err, resp) { - if (process.hrtime(start)[0] < seconds) { - count += 1; - client.emptyCall({}, responseCallback); - } else { - running -= 1; - if (running <= 0) { - callback(null, count); - } - } - } - for (var i = 0; i < concurrent_calls; i++) { - running += 1; - client.emptyCall({}, responseCallback); - } - } - async.waterfall([warmUp, run], function(err, count) { - testServer.server.shutdown(); - callback(err, count); - }); -} - -if (require.main === module) { - var argv = parseArgs(process.argv.slice(2), { - default: {'concurrent': 100, - 'time': 10} - }); - runTest(argv.concurrent, argv.time, function(err, count) { - if (err) { - throw err; - } - console.log('Concurrent calls:', argv.concurrent); - console.log('Time:', argv.time, 'seconds'); - console.log('QPS:', (count/argv.time)); - }); -} diff --git a/src/node/examples/stock.proto b/src/node/examples/stock.proto deleted file mode 100644 index 5ee2bcbce6..0000000000 --- a/src/node/examples/stock.proto +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2015, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package examples; - -// Protocol type definitions -message StockRequest { - string symbol = 1; - int32 num_trades_to_watch = 2; -} - -message StockReply { - float price = 1; - string symbol = 2; -} - - -// Interface exported by the server -service Stock { - // Simple blocking RPC - rpc GetLastTradePrice(StockRequest) returns (StockReply) { - } - // Bidirectional streaming RPC - rpc GetLastTradePriceMultiple(stream StockRequest) returns - (stream StockReply) { - } - // Unidirectional server-to-client streaming RPC - rpc WatchFutureTrades(StockRequest) returns (stream StockReply) { - } - // Unidirectional client-to-server streaming RPC - rpc GetHighestTradePrice(stream StockRequest) returns (StockReply) { - } - -} diff --git a/src/node/examples/stock_client.js b/src/node/examples/stock_client.js deleted file mode 100644 index ab9b050e9b..0000000000 --- a/src/node/examples/stock_client.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -var grpc = require('..'); -var examples = grpc.load(__dirname + '/stock.proto').examples; - -/** - * This exports a client constructor for the Stock service. The usage looks like - * - * var StockClient = require('stock_client.js'); - * var stockClient = new StockClient(server_address, - * grpc.Credentials.createInsecure()); - * stockClient.getLastTradePrice({symbol: 'GOOG'}, function(error, response) { - * console.log(error || response); - * }); - */ -module.exports = examples.Stock; diff --git a/src/node/examples/stock_server.js b/src/node/examples/stock_server.js deleted file mode 100644 index 12e5479584..0000000000 --- a/src/node/examples/stock_server.js +++ /dev/null @@ -1,87 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -'use strict'; - -var _ = require('lodash'); -var grpc = require('..'); -var examples = grpc.load(__dirname + '/stock.proto').examples; - -function getLastTradePrice(call, callback) { - callback(null, {symbol: call.request.symbol, price: 88}); -} - -function watchFutureTrades(call) { - for (var i = 0; i < call.request.num_trades_to_watch; i++) { - call.write({price: 88.00 + i * 10.00}); - } - call.end(); -} - -function getHighestTradePrice(call, callback) { - var trades = []; - call.on('data', function(data) { - trades.push({symbol: data.symbol, price: _.random(0, 100)}); - }); - call.on('end', function() { - if(_.isEmpty(trades)) { - callback(null, {}); - } else { - callback(null, _.max(trades, function(trade){return trade.price;})); - } - }); -} - -function getLastTradePriceMultiple(call) { - call.on('data', function(data) { - call.write({price: 88}); - }); - call.on('end', function() { - call.end(); - }); -} - -var stockServer = new grpc.Server(); -stockServer.addProtoService(examples.Stock.service, { - getLastTradePrice: getLastTradePrice, - getLastTradePriceMultiple: getLastTradePriceMultiple, - watchFutureTrades: watchFutureTrades, - getHighestTradePrice: getHighestTradePrice -}); - -if (require.main === module) { - stockServer.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure()); - stockServer.start(); -} - -module.exports = stockServer; |