Class: Calculator

Inherits:
Math::Math::Service show all
Defined in:
src/ruby/bin/math_server.rb

Overview

The Math::Math

module occurs because the service has the same name as its

package. That practice should be avoided by defining real services.

Instance Method Summary collapse

Methods included from GRPC::GenericService

included, underscore

Instance Method Details

#div(div_args, _call) ⇒ Object


112
113
114
115
116
117
118
119
120
121
122
# File 'src/ruby/bin/math_server.rb', line 112

def div(div_args, _call)
  if div_args.divisor.zero?
    # To send non-OK status handlers raise a StatusError with the code and
    # and detail they want sent as a Status.
    fail GRPC::StatusError.new(GRPC::Status::INVALID_ARGUMENT,
                               'divisor cannot be 0')
  end

  Math::DivReply.new(quotient: div_args.dividend / div_args.divisor,
                     remainder: div_args.dividend % div_args.divisor)
end

#div_many(requests) ⇒ Object


141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'src/ruby/bin/math_server.rb', line 141

def div_many(requests)
  # requests is an lazy Enumerator of the requests sent by the client.
  q = EnumeratorQueue.new(self)
  t = Thread.new do
    begin
      requests.each do |req|
        GRPC.logger.info("read #{req.inspect}")
        resp = Math::DivReply.new(quotient: req.dividend / req.divisor,
                                  remainder: req.dividend % req.divisor)
        q.push(resp)
        Thread.pass  # let the internal Bidi threads run
      end
      GRPC.logger.info('finished reads')
      q.push(self)
    rescue StandardError => e
      q.push(e)  # share the exception with the enumerator
      raise e
    end
  end
  t.priority = -2  # hint that the div_many thread should not be favoured
  q.each_item
end

#fib(fib_args, _call) ⇒ Object


131
132
133
134
135
136
137
138
139
# File 'src/ruby/bin/math_server.rb', line 131

def fib(fib_args, _call)
  if fib_args.limit < 1
    fail StatusError.new(Status::INVALID_ARGUMENT, 'limit must be >= 0')
  end

  # return an Enumerator of Nums
  Fibber.new(fib_args.limit).generator
  # just return the generator, GRPC::GenericServer sends each actual response
end

#sum(call) ⇒ Object


124
125
126
127
128
129
# File 'src/ruby/bin/math_server.rb', line 124

def sum(call)
  # the requests are accesible as the Enumerator call#each_request
  nums = call.each_remote_read.collect(&:num)
  sum = nums.inject { |s, x| s + x }
  Math::Num.new(num: sum)
end