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, Calculator, DebugIsTruncated, EchoMsg, EchoService, EmptyService, EncodeDecodeMsg, EnumeratorQueue, FailingService, Fibber, GoodMsg, NamedActions, NamedTests, NoProto, NoProtoMsg, NoProtoService, NoRpcImplementation, PingPongPlayer, SlowService, Struct, TestTarget

Constant Summary collapse

AUTH_ENV =
Google::Auth::CredentialsLoader::ENV_VAR
Server =
GRPC::Core::Server
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
]
NoProtoStub =
NoProtoService.rpc_stub_class
TimeConsts =
GRPC::Core::TimeConsts
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


454
455
456
457
458
459
460
461
# File 'src/ruby/pb/test/client.rb', line 454

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
# File 'src/ruby/pb/test/client.rb', line 112

def create_stub(opts)
  address = "#{opts.host}:#{opts.port}"
  if opts.secure
    creds = ssl_creds(opts.use_test_ca)
    stub_opts = {
      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}")
    Grpc::Testing::TestService::Stub.new(address, creds, **stub_opts)
  else
    GRPC.logger.info("... connecting insecurely to #{address}")
    Grpc::Testing::TestService::Stub.new(address, :this_channel_is_insecure)
  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 used to access the test server securely.


112
113
114
115
116
117
# File 'src/ruby/pb/test/server.rb', line 112

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


238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'src/ruby/pb/test/server.rb', line 238

def main
  opts = parse_options
  host = "0.0.0.0:#{opts['port']}"
  s = GRPC::RpcServer.new
  if opts['secure']
    s.add_http2_port(host, test_server_creds)
    GRPC.logger.info("... running securely on #{host}")
  else
    s.add_http2_port(host, :this_port_is_insecure)
    GRPC.logger.info("... running insecurely on #{host}")
  end
  s.handle(TestTarget)
  s.run_till_terminated
end

#nulls(l) ⇒ Object

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


127
128
129
130
# File 'src/ruby/pb/test/server.rb', line 127

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.


419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'src/ruby/pb/test/client.rb', line 419

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


216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'src/ruby/pb/test/server.rb', line 216

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


32
33
34
35
36
37
38
39
# File 'src/ruby/spec/generic/client_stub_spec.rb', line 32

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