aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/ruby/bin/math_server.rb
blob: 72a1f6b3987873b5d3e4597ec82d88e7e1d7ea0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# Copyright 2014, 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.

#!/usr/bin/env ruby
#
# Sample gRPC Ruby server that implements the Math::Calc service and helps
# validate GRPC::RpcServer as GRPC implementation using proto2 serialization.
#
# Usage: $ path/to/math_server.rb

this_dir = File.expand_path(File.dirname(__FILE__))
lib_dir = File.join(File.dirname(this_dir), 'lib')
$LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
$LOAD_PATH.unshift(this_dir) unless $LOAD_PATH.include?(this_dir)

require 'forwardable'
require 'grpc'
require 'grpc/generic/service'
require 'grpc/generic/rpc_server'
require 'math.pb'

# Holds state for a fibonacci series
class Fibber

  def initialize(limit)
    raise "bad limit: got #{limit}, want limit > 0" if limit < 1
    @limit = limit
  end

  def generator
    return enum_for(:generator) unless block_given?
    idx, current, previous = 0, 1, 1
    until idx == @limit
      if idx == 0 || idx == 1
        yield Math::Num.new(:num => 1)
        idx += 1
        next
      end
      tmp = current
      current = previous + current
      previous = tmp
      yield Math::Num.new(:num => current)
      idx += 1
    end
  end
end

# A EnumeratorQueue wraps a Queue to yield the items added to it.
class EnumeratorQueue
  extend Forwardable
  def_delegators :@q, :push

  def initialize(sentinel)
    @q = Queue.new
    @sentinel = sentinel
  end

  def each_item
    return enum_for(:each_item) unless block_given?
    loop do
      r = @q.pop
      break if r.equal?(@sentinel)
      raise r if r.is_a?Exception
      yield r
    end
  end

end

# The Math::Math:: module occurs because the service has the same name as its
# package. That practice should be avoided by defining real services.
class Calculator < Math::Math::Service

  def div(div_args, call)
    if div_args.divisor == 0
      # To send non-OK status handlers raise a StatusError with the code and
      # and detail they want sent as a Status.
      raise 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

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

  def fib(fib_args, call)
    if fib_args.limit < 1
      raise 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

  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|
          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
        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

end

def main
  host_port = 'localhost:7070'
  if ARGV.size > 0
    host_port = ARGV[0]
  end

  s = GRPC::RpcServer.new()
  s.add_http2_port(host_port)
  s.handle(Calculator)
  s.run
end

main