math_server.rb 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/env ruby
  2. # Copyright 2015 gRPC authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # Sample gRPC Ruby server that implements the Math::Calc service and helps
  16. # validate GRPC::RpcServer as GRPC implementation using proto2 serialization.
  17. #
  18. # Usage: $ path/to/math_server.rb
  19. this_dir = File.expand_path(File.dirname(__FILE__))
  20. lib_dir = File.join(File.dirname(this_dir), 'lib')
  21. $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
  22. $LOAD_PATH.unshift(this_dir) unless $LOAD_PATH.include?(this_dir)
  23. require 'forwardable'
  24. require 'grpc'
  25. require 'logger'
  26. require 'math_services_pb'
  27. require 'optparse'
  28. # RubyLogger defines a logger for gRPC based on the standard ruby logger.
  29. module RubyLogger
  30. def logger
  31. LOGGER
  32. end
  33. LOGGER = Logger.new(STDOUT)
  34. end
  35. # GRPC is the general RPC module
  36. module GRPC
  37. # Inject the noop #logger if no module-level logger method has been injected.
  38. extend RubyLogger
  39. end
  40. # Holds state for a fibonacci series
  41. class Fibber
  42. def initialize(limit)
  43. fail "bad limit: got #{limit}, want limit > 0" if limit < 1
  44. @limit = limit
  45. end
  46. def generator
  47. return enum_for(:generator) unless block_given?
  48. idx, current, previous = 0, 1, 1
  49. until idx == @limit
  50. if idx.zero? || idx == 1
  51. yield Math::Num.new(num: 1)
  52. idx += 1
  53. next
  54. end
  55. tmp = current
  56. current = previous + current
  57. previous = tmp
  58. yield Math::Num.new(num: current)
  59. idx += 1
  60. end
  61. end
  62. end
  63. # A EnumeratorQueue wraps a Queue to yield the items added to it.
  64. class EnumeratorQueue
  65. extend Forwardable
  66. def_delegators :@q, :push
  67. def initialize(sentinel)
  68. @q = Queue.new
  69. @sentinel = sentinel
  70. end
  71. def each_item
  72. return enum_for(:each_item) unless block_given?
  73. loop do
  74. r = @q.pop
  75. break if r.equal?(@sentinel)
  76. fail r if r.is_a? Exception
  77. yield r
  78. end
  79. end
  80. end
  81. # The Math::Math:: module occurs because the service has the same name as its
  82. # package. That practice should be avoided by defining real services.
  83. class Calculator < Math::Math::Service
  84. def div(div_args, _call)
  85. if div_args.divisor.zero?
  86. # To send non-OK status handlers raise a StatusError with the code and
  87. # and detail they want sent as a Status.
  88. fail GRPC::StatusError.new(GRPC::Status::INVALID_ARGUMENT,
  89. 'divisor cannot be 0')
  90. end
  91. Math::DivReply.new(quotient: div_args.dividend / div_args.divisor,
  92. remainder: div_args.dividend % div_args.divisor)
  93. end
  94. def sum(call)
  95. # the requests are accesible as the Enumerator call#each_request
  96. nums = call.each_remote_read.collect(&:num)
  97. sum = nums.inject { |s, x| s + x }
  98. Math::Num.new(num: sum)
  99. end
  100. def fib(fib_args, _call)
  101. if fib_args.limit < 1
  102. fail StatusError.new(Status::INVALID_ARGUMENT, 'limit must be >= 0')
  103. end
  104. # return an Enumerator of Nums
  105. Fibber.new(fib_args.limit).generator
  106. # just return the generator, GRPC::GenericServer sends each actual response
  107. end
  108. def div_many(requests)
  109. # requests is an lazy Enumerator of the requests sent by the client.
  110. q = EnumeratorQueue.new(self)
  111. t = Thread.new do
  112. begin
  113. requests.each do |req|
  114. GRPC.logger.info("read #{req.inspect}")
  115. resp = Math::DivReply.new(quotient: req.dividend / req.divisor,
  116. remainder: req.dividend % req.divisor)
  117. q.push(resp)
  118. Thread.pass # let the internal Bidi threads run
  119. end
  120. GRPC.logger.info('finished reads')
  121. q.push(self)
  122. rescue StandardError => e
  123. q.push(e) # share the exception with the enumerator
  124. raise e
  125. end
  126. end
  127. t.priority = -2 # hint that the div_many thread should not be favoured
  128. q.each_item
  129. end
  130. end
  131. def load_test_certs
  132. this_dir = File.expand_path(File.dirname(__FILE__))
  133. data_dir = File.join(File.dirname(this_dir), 'spec/testdata')
  134. files = ['ca.pem', 'server1.key', 'server1.pem']
  135. files.map { |f| File.open(File.join(data_dir, f)).read }
  136. end
  137. def test_server_creds
  138. certs = load_test_certs
  139. GRPC::Core::ServerCredentials.new(
  140. nil, [{ private_key: certs[1], cert_chain: certs[2] }], false)
  141. end
  142. def main
  143. options = {
  144. 'host' => 'localhost:7071',
  145. 'secure' => false
  146. }
  147. OptionParser.new do |opts|
  148. opts.banner = 'Usage: [--host <hostname>:<port>] [--secure|-s]'
  149. opts.on('--host HOST', '<hostname>:<port>') do |v|
  150. options['host'] = v
  151. end
  152. opts.on('-s', '--secure', 'access using test creds') do |v|
  153. options['secure'] = v
  154. end
  155. end.parse!
  156. s = GRPC::RpcServer.new
  157. if options['secure']
  158. s.add_http2_port(options['host'], test_server_creds)
  159. GRPC.logger.info("... running securely on #{options['host']}")
  160. else
  161. s.add_http2_port(options['host'], :this_port_is_insecure)
  162. GRPC.logger.info("... running insecurely on #{options['host']}")
  163. end
  164. s.handle(Calculator)
  165. s.run_till_terminated
  166. end
  167. main