Top Level Namespace

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

Defined Under Namespace

Modules: GRPC, Google, Grpc, Math, RubyLogger, Tech Classes: Args, AssertionError, BidiService, BlockingEnumerator, Calculator, CheckCallAfterFinishedService, DebugIsTruncated, EchoMsg, EchoService, EmptyService, EncodeDecodeMsg, EnumeratorQueue, FailingService, Fibber, FullDuplexEnumerator, GoodMsg, GoogleRpcStatusTestService, NamedActions, NamedTests, NoProto, NoProtoMsg, NoProtoService, NoRpcImplementation, NoStatusDetailsBinTestService, PingPongPlayer, SlowService, SslTestService, Struct, SynchronizedCancellationService, 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
SslTestServiceStub =
SslTestService.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
SynchronizedCancellationStub =
SynchronizedCancellationService.rpc_stub_class
CheckCallAfterFinishedServiceStub =
CheckCallAfterFinishedService.rpc_stub_class
BidiStub =
BidiService.rpc_stub_class
GoogleRpcStatusTestStub =
GoogleRpcStatusTestService.rpc_stub_class
NoStatusDetailsBinTestServiceStub =
NoStatusDetailsBinTestService.rpc_stub_class

Instance Method Summary collapse

Methods included from GRPC::Core::TimeConsts

from_relative_time

Instance Method Details

#_check_args(args) ⇒ Object



746
747
748
749
750
751
752
753
# File 'src/ruby/pb/test/client.rb', line 746

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



66
67
68
69
# File 'src/ruby/pb/test/client.rb', line 66

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.



48
49
50
51
# File 'src/ruby/bin/apis/pubsub_demo.rb', line 48

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

#can_run_codegen_checkObject



21
22
23
# File 'src/ruby/spec/pb/health/checker_spec.rb', line 21

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

#check_md(wanted_md, received_md) ⇒ Object



23
24
25
26
27
28
29
# File 'src/ruby/spec/generic/rpc_server_spec.rb', line 23

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

#check_op_view_of_finished_client_call(op_view, expected_metadata, expected_trailing_metadata) ⇒ Object

check that methods on a finished/closed call t crash



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'src/ruby/spec/generic/client_stub_spec.rb', line 40

def check_op_view_of_finished_client_call(op_view,
                                          ,
                                          )
  # use read_response_stream to try to iterate through
  # possible response stream
  fail('need something to attempt reads') unless block_given?
  expect do
    resp = op_view.execute
    yield resp
  end.to raise_error(GRPC::Core::CallError)

  expect { op_view.start_call }.to raise_error(RuntimeError)

  sanity_check_values_of_accessors(op_view,
                                   ,
                                   )

  expect do
    op_view.wait
    op_view.cancel
    op_view.write_flag = 1
  end.to_not raise_error
end

#client_certObject



24
25
26
27
28
29
# File 'src/ruby/spec/client_auth_spec.rb', line 24

def client_cert
  test_root = File.join(File.dirname(__FILE__), 'testdata')
  cert = File.open(File.join(test_root, 'client.pem')).read
  fail unless cert.is_a?(String)
  cert
end

#create_channel_credsObject



17
18
19
20
21
22
# File 'src/ruby/spec/client_auth_spec.rb', line 17

def create_channel_creds
  test_root = File.join(File.dirname(__FILE__), 'testdata')
  files = ['ca.pem', 'client.key', 'client.pem']
  creds = files.map { |f| File.open(File.join(test_root, f)).read }
  GRPC::Core::ChannelCredentials.new(creds[0], creds[1], creds[2])
end

#create_server_credsObject



31
32
33
34
35
36
37
38
39
40
# File 'src/ruby/spec/client_auth_spec.rb', line 31

def create_server_creds
  test_root = File.join(File.dirname(__FILE__), 'testdata')
  p "test root: #{test_root}"
  files = ['ca.pem', 'server1.key', 'server1.pem']
  creds = files.map { |f| File.open(File.join(test_root, f)).read }
  GRPC::Core::ServerCredentials.new(
    creds[0],
    [{ private_key: creds[1], cert_chain: creds[2] }],
    true) # force client auth
end

#create_stub(opts) ⇒ Object

creates a test stub that accesses host:port securely.



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

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



33
34
35
36
37
38
39
40
41
# File 'src/ruby/bin/math_client.rb', line 33

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



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

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



54
55
56
57
58
59
60
61
62
63
64
# File 'src/ruby/bin/math_client.rb', line 54

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



43
44
45
46
47
48
49
50
51
52
# File 'src/ruby/bin/math_client.rb', line 43

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.



72
73
74
75
76
77
# File 'src/ruby/pb/test/client.rb', line 72

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



755
756
757
758
759
760
# File 'src/ruby/pb/test/client.rb', line 755

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



117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'src/ruby/pb/test/server.rb', line 117

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



131
132
133
134
135
136
# File 'src/ruby/pb/test/server.rb', line 131

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.



170
171
172
173
# File 'src/ruby/pb/test/client.rb', line 170

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.



711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'src/ruby/pb/test/client.rb', line 711

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.



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

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.



86
87
88
# File 'src/ruby/pb/test/client.rb', line 86

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

#publisher_stub(opts) ⇒ Object

Creates a stub for accessing the publisher service.



54
55
56
57
58
59
60
61
62
# File 'src/ruby/bin/apis/pubsub_demo.rb', line 54

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

#sanity_check_values_of_accessors(op_view, expected_metadata, expected_trailing_metadata) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'src/ruby/spec/generic/client_stub_spec.rb', line 64

def sanity_check_values_of_accessors(op_view,
                                     ,
                                     )
  expected_status = Struct::Status.new
  expected_status.code = 0
  expected_status.details = 'OK'
  expected_status. = 

  expect(op_view.status).to eq(expected_status)
  expect(op_view.).to eq()
  expect(op_view.).to eq()

  expect(op_view.cancelled?).to be(false)
  expect(op_view.write_flag).to be(nil)

  # The deadline attribute of a call can be either
  # a GRPC::Core::TimeSpec or a Time, which are mutually exclusive.
  # TODO: fix so that the accessor always returns the same type.
  expect(op_view.deadline.is_a?(GRPC::Core::TimeSpec) ||
         op_view.deadline.is_a?(Time)).to be(true)
end

#ssl_credsObject

creates a SSL Credentials from the production certificates.



91
92
93
94
# File 'src/ruby/pb/test/client.rb', line 91

def ssl_creds(use_test_ca)
  return test_creds if use_test_ca
  prod_creds
end

#start_server(port = 0) ⇒ Object



53
54
55
56
57
58
59
60
# File 'src/ruby/spec/channel_connection_spec.rb', line 53

def start_server(port = 0)
  @srv = GRPC::RpcServer.new(pool_size: 1)
  server_port = @srv.add_http2_port("localhost:#{port}", :this_port_is_insecure)
  @srv.handle(EchoService)
  @server_thd = Thread.new { @srv.run }
  @srv.wait_till_running
  server_port
end

#stop_serverObject



62
63
64
65
66
67
# File 'src/ruby/spec/channel_connection_spec.rb', line 62

def stop_server
  expect(@srv.stopped?).to be(false)
  @srv.stop
  @server_thd.join
  expect(@srv.stopped?).to be(true)
end

#subscriber_stub(opts) ⇒ Object

Creates a stub for accessing the subscriber service.



65
66
67
68
69
70
71
72
73
# File 'src/ruby/bin/apis/pubsub_demo.rb', line 65

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.



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

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

#test_server_credsObject

creates a ServerCredentials from the test certificates.



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

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



19
20
21
22
23
24
25
26
27
# File 'src/ruby/spec/generic/client_stub_spec.rb', line 19

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