Top Level Namespace

Includes:
GRPC::Core, GRPC::Core::CallOps, GRPC::Core::StatusCodes, GRPC::Core::TimeConsts

Defined Under Namespace

Modules: GRPC, Google, Grpc, Math, RubyLogger, Tech Classes: Args, AssertionError, BlockingEnumerator, Calculator, DebugIsTruncated, EchoMsg, EchoService, EmptyService, EncodeDecodeMsg, EnumeratorQueue, FailingService, Fibber, FullDuplexEnumerator, GoodMsg, NamedActions, NamedTests, NoProto, NoProtoMsg, NoProtoService, NoRpcImplementation, PingPongPlayer, SlowService, Struct, TestTarget, WriteFlagSettingStreamingInputEnumerable

Constant Summary collapse

AUTH_ENV =
Google::Auth::CredentialsLoader::ENV_VAR
LIBDIR =
RbConfig::CONFIG['libdir']
INCLUDEDIR =
RbConfig::CONFIG['includedir']
HEADER_DIRS =
[
  # Search /opt/local (Mac source install)
  '/opt/local/include',

  # Search /usr/local (Source install)
  '/usr/local/include',

  # Check the ruby install locations
  INCLUDEDIR
]
LIB_DIRS =
[
  # Search /opt/local (Mac source install)
  '/opt/local/lib',

  # Search /usr/local (Source install)
  '/usr/local/lib',

  # Check the ruby install locations
  LIBDIR
]
Server =
GRPC::Core::Server
NoProtoStub =
NoProtoService.rpc_stub_class
TimeConsts =
GRPC::Core::TimeConsts
StatusCodes =
GRPC::Core::StatusCodes
GenericService =
GRPC::GenericService
Dsl =
GenericService::Dsl
EchoStub =
EchoService.rpc_stub_class
FailingStub =
FailingService.rpc_stub_class
SlowStub =
SlowService.rpc_stub_class

Instance Method Summary collapse

Methods included from GRPC::Core::TimeConsts

from_relative_time

Instance Method Details

#_check_args(args) ⇒ Object



761
762
763
764
765
766
767
768
# File 'src/ruby/pb/test/client.rb', line 761

def _check_args(args)
  %w(host port test_case).each do |a|
    if args[a].nil?
      fail(OptionParser::MissingArgument, "please specify --#{a}")
    end
  end
  args
end

#assert(msg = 'unknown cause') ⇒ Object

Fails with AssertionError if the block does evaluate to true



81
82
83
84
# File 'src/ruby/pb/test/client.rb', line 81

def assert(msg = 'unknown cause')
  fail 'No assertion block provided' unless block_given?
  fail AssertionError, msg unless yield
end

#auth_proc(opts) ⇒ Object

Builds the metadata authentication update proc.



63
64
65
66
# File 'src/ruby/bin/apis/pubsub_demo.rb', line 63

def auth_proc(opts)
  auth_creds = Google::Auth.get_application_default
  return auth_creds.updater_proc
end

#can_run_codegen_checkObject



36
37
38
# File 'src/ruby/spec/pb/health/checker_spec.rb', line 36

def can_run_codegen_check
  system('which grpc_ruby_plugin') && system('which protoc')
end

#check_md(wanted_md, received_md) ⇒ Object



38
39
40
41
42
43
44
# File 'src/ruby/spec/generic/rpc_server_spec.rb', line 38

def check_md(wanted_md, received_md)
  wanted_md.zip(received_md).each do |w, r|
    w.each do |key, value|
      expect(r[key]).to eq(value)
    end
  end
end

#create_stub(opts) ⇒ Object

creates a test stub that accesses host:port securely.



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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'src/ruby/pb/test/client.rb', line 112

def create_stub(opts)
  address = "#{opts.host}:#{opts.port}"

  # Provide channel args that request compression by default
  # for compression interop tests
  if ['client_compressed_unary',
      'client_compressed_streaming'].include?(opts.test_case)
    compression_options =
      GRPC::Core::CompressionOptions.new(default_algorithm: :gzip)
    compression_channel_args = compression_options.to_channel_arg_hash
  else
    compression_channel_args = {}
  end

  if opts.secure
    creds = ssl_creds(opts.use_test_ca)
    stub_opts = {
      channel_args: {
        GRPC::Core::Channel::SSL_TARGET => opts.host_override
      }
    }

    # Add service account creds if specified
    wants_creds = %w(all compute_engine_creds service_account_creds)
    if wants_creds.include?(opts.test_case)
      unless opts.oauth_scope.nil?
        auth_creds = Google::Auth.get_application_default(opts.oauth_scope)
        call_creds = GRPC::Core::CallCredentials.new(auth_creds.updater_proc)
        creds = creds.compose call_creds
      end
    end

    if opts.test_case == 'oauth2_auth_token'
      auth_creds = Google::Auth.get_application_default(opts.oauth_scope)
      kw = auth_creds.updater_proc.call({})  # gives as an auth token

      # use a metadata update proc that just adds the auth token.
      call_creds = GRPC::Core::CallCredentials.new(proc { |md| md.merge(kw) })
      creds = creds.compose call_creds
    end

    if opts.test_case == 'jwt_token_creds'  # don't use a scope
      auth_creds = Google::Auth.get_application_default
      call_creds = GRPC::Core::CallCredentials.new(auth_creds.updater_proc)
      creds = creds.compose call_creds
    end

    GRPC.logger.info("... connecting securely to #{address}")
    stub_opts[:channel_args].merge!(compression_channel_args)
    if opts.test_case == "unimplemented_service"
      Grpc::Testing::UnimplementedService::Stub.new(address, creds, **stub_opts)
    else
      Grpc::Testing::TestService::Stub.new(address, creds, **stub_opts)
    end
  else
    GRPC.logger.info("... connecting insecurely to #{address}")
    if opts.test_case == "unimplemented_service"
      Grpc::Testing::UnimplementedService::Stub.new(
        address,
        :this_channel_is_insecure,
        channel_args: compression_channel_args
      )
    else
      Grpc::Testing::TestService::Stub.new(
        address,
        :this_channel_is_insecure,
        channel_args: compression_channel_args
      )
    end
  end
end

#do_div(stub) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'src/ruby/bin/math_client.rb', line 48

def do_div(stub)
  GRPC.logger.info('request_response')
  GRPC.logger.info('----------------')
  req = Math::DivArgs.new(dividend: 7, divisor: 3)
  GRPC.logger.info("div(7/3): req=#{req.inspect}")
  resp = stub.div(req, timeout: INFINITE_FUTURE)
  GRPC.logger.info("Answer: #{resp.inspect}")
  GRPC.logger.info('----------------')
end

#do_div_many(stub) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'src/ruby/bin/math_client.rb', line 81

def do_div_many(stub)
  GRPC.logger.info('bidi_streamer')
  GRPC.logger.info('-------------')
  reqs = []
  reqs << Math::DivArgs.new(dividend: 7, divisor: 3)
  reqs << Math::DivArgs.new(dividend: 5, divisor: 2)
  reqs << Math::DivArgs.new(dividend: 7, divisor: 2)
  GRPC.logger.info("div(7/3), div(5/2), div(7/2): reqs=#{reqs.inspect}")
  resp = stub.div_many(reqs, timeout: INFINITE_FUTURE)
  resp.each do |r|
    GRPC.logger.info("Answer: #{r.inspect}")
  end
  GRPC.logger.info('----------------')
end

#do_fib(stub) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
# File 'src/ruby/bin/math_client.rb', line 69

def do_fib(stub)
  GRPC.logger.info('server_streamer')
  GRPC.logger.info('----------------')
  req = Math::FibArgs.new(limit: 11)
  GRPC.logger.info("fib(11): req=#{req.inspect}")
  resp = stub.fib(req, timeout: INFINITE_FUTURE)
  resp.each do |r|
    GRPC.logger.info("Answer: #{r.inspect}")
  end
  GRPC.logger.info('----------------')
end

#do_sum(stub) ⇒ Object



58
59
60
61
62
63
64
65
66
67
# File 'src/ruby/bin/math_client.rb', line 58

def do_sum(stub)
  # to make client streaming requests, pass an enumerable of the inputs
  GRPC.logger.info('client_streamer')
  GRPC.logger.info('---------------')
  reqs = [1, 2, 3, 4, 5].map { |x| Math::Num.new(num: x) }
  GRPC.logger.info("sum(1, 2, 3, 4, 5): reqs=#{reqs.inspect}")
  resp = stub.sum(reqs)  # reqs.is_a?(Enumerable)
  GRPC.logger.info("Answer: #{resp.inspect}")
  GRPC.logger.info('---------------')
end

#load_test_certsObject

loads the certificates by the test server.



87
88
89
90
91
92
# File 'src/ruby/pb/test/client.rb', line 87

def load_test_certs
  this_dir = File.expand_path(File.dirname(__FILE__))
  data_dir = File.join(File.dirname(File.dirname(this_dir)), 'spec/testdata')
  files = ['ca.pem', 'server1.key', 'server1.pem']
  files.map { |f| File.open(File.join(data_dir, f)).read }
end

#mainObject



770
771
772
773
774
775
# File 'src/ruby/pb/test/client.rb', line 770

def main
  opts = parse_args
  stub = create_stub(opts)
  NamedTests.new(stub, opts).method(opts['test_case']).call
  p "OK: #{opts['test_case']}"
end

#maybe_echo_metadata(_call) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'src/ruby/pb/test/server.rb', line 132

def (_call)
  
  # these are consistent for all interop tests
   = "x-grpc-test-echo-initial"
   = "x-grpc-test-echo-trailing-bin"

  if _call..has_key?()
    _call.[] = _call.[]
  end
  if _call..has_key?()
    _call.[] = _call.[]
  end
end

#maybe_echo_status_and_message(req) ⇒ Object



146
147
148
149
150
151
# File 'src/ruby/pb/test/server.rb', line 146

def maybe_echo_status_and_message(req)
  unless req.response_status.nil?
    fail GRPC::BadStatus.new_status_exception(
        req.response_status.code, req.response_status.message)
  end
end

#nulls(l) ⇒ Object

produces a string of null chars (0) of length l.



185
186
187
188
# File 'src/ruby/pb/test/client.rb', line 185

def nulls(l)
  fail 'requires #{l} to be +ve' if l < 0
  [].pack('x' * l).force_encoding('ascii-8bit')
end

#parse_argsObject

validates the the command line options, returning them as an Arg.



726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
# File 'src/ruby/pb/test/client.rb', line 726

def parse_args
  args = Args.new
  args.host_override = 'foo.test.google.fr'
  OptionParser.new do |opts|
    opts.on('--oauth_scope scope',
            'Scope for OAuth tokens') { |v| args['oauth_scope'] = v }
    opts.on('--server_host SERVER_HOST', 'server hostname') do |v|
      args['host'] = v
    end
    opts.on('--default_service_account email_address',
            'email address of the default service account') do |v|
      args['default_service_account'] = v
    end
    opts.on('--server_host_override HOST_OVERRIDE',
            'override host via a HTTP header') do |v|
      args['host_override'] = v
    end
    opts.on('--server_port SERVER_PORT', 'server port') { |v| args['port'] = v }
    # instance_methods(false) gives only the methods defined in that class
    test_cases = NamedTests.instance_methods(false).map(&:to_s)
    test_case_list = test_cases.join(',')
    opts.on('--test_case CODE', test_cases, {}, 'select a test_case',
            "  (#{test_case_list})") { |v| args['test_case'] = v }
    opts.on('--use_tls USE_TLS', ['false', 'true'],
            'require a secure connection?') do |v|
      args['secure'] = v == 'true'
p    end
    opts.on('--use_test_ca USE_TEST_CA', ['false', 'true'],
            'if secure, use the test certificate?') do |v|
      args['use_test_ca'] = v == 'true'
    end
  end.parse!
  _check_args(args)
end

#parse_optionsObject

validates the the command line options, returning them as a Hash.



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'src/ruby/pb/test/server.rb', line 230

def parse_options
  options = {
    'port' => nil,
    'secure' => false
  }
  OptionParser.new do |opts|
    opts.banner = 'Usage: --port port'
    opts.on('--port PORT', 'server port') do |v|
      options['port'] = v
    end
    opts.on('--use_tls USE_TLS', ['false', 'true'],
            'require a secure connection?') do |v|
      options['secure'] = v == 'true'
    end
  end.parse!

  if options['port'].nil?
    fail(OptionParser::MissingArgument, 'please specify --port')
  end
  options
end

#prod_credsObject

creates SSL Credentials from the production certificates.



101
102
103
# File 'src/ruby/pb/test/client.rb', line 101

def prod_creds
  GRPC::Core::ChannelCredentials.new()
end

#publisher_stub(opts) ⇒ Object

Creates a stub for accessing the publisher service.



69
70
71
72
73
74
75
76
77
# File 'src/ruby/bin/apis/pubsub_demo.rb', line 69

def publisher_stub(opts)
  address = "#{opts.host}:#{opts.port}"
  stub_clz = Tech::Pubsub::PublisherService::Stub # shorter
  GRPC.logger.info("... access PublisherService at #{address}")
  call_creds = GRPC::Core::CallCredentials.new(auth_proc(opts))
  combined_creds = ssl_creds.compose(call_creds)
  stub_clz.new(address, creds: combined_creds,
               GRPC::Core::Channel::SSL_TARGET => opts.host)
end

#ssl_credsObject

creates a SSL Credentials from the production certificates.



106
107
108
109
# File 'src/ruby/pb/test/client.rb', line 106

def ssl_creds(use_test_ca)
  return test_creds if use_test_ca
  prod_creds
end

#subscriber_stub(opts) ⇒ Object

Creates a stub for accessing the subscriber service.



80
81
82
83
84
85
86
87
88
# File 'src/ruby/bin/apis/pubsub_demo.rb', line 80

def subscriber_stub(opts)
  address = "#{opts.host}:#{opts.port}"
  stub_clz = Tech::Pubsub::SubscriberService::Stub # shorter
  GRPC.logger.info("... access SubscriberService at #{address}")
  call_creds = GRPC::Core::CallCredentials.new(auth_proc(opts))
  combined_creds = ssl_creds.compose(call_creds)
  stub_clz.new(address, creds: combined_creds,
               GRPC::Core::Channel::SSL_TARGET => opts.host)
end

#test_credsObject

creates SSL Credentials from the test certificates.



95
96
97
98
# File 'src/ruby/pb/test/client.rb', line 95

def test_creds
  certs = load_test_certs
  GRPC::Core::ChannelCredentials.new(certs[0])
end

#test_server_credsObject

creates a ServerCredentials from the test certificates.



120
121
122
123
124
# File 'src/ruby/pb/test/server.rb', line 120

def test_server_creds
  certs = load_test_certs
  GRPC::Core::ServerCredentials.new(
      nil, [{private_key: certs[1], cert_chain: certs[2]}], false)
end

#wakey_thread(&blk) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'src/ruby/spec/generic/client_stub_spec.rb', line 34

def wakey_thread(&blk)
  n = GRPC::Notifier.new
  t = Thread.new do
    blk.call(n)
  end
  t.abort_on_exception = true
  n.wait
  t
end