Top Level Namespace

Defined Under Namespace

Modules: GRPC, Grpc, Math, RubyLogger, StdoutLogger Classes: Args, AssertionError, BidiService, BlockingEnumerator, Calculator, CheckCallAfterFinishedService, ConfigureTarget, DebugIsTruncated, DebugMessageTestService, EchoMsg, EchoService, EmptyService, EncodeDecodeMsg, EnumeratorQueue, FailingService, Fibber, FullDuplexEnumerator, GoodMsg, GoogleRpcStatusTestService, NamedTests, NoProto, NoProtoMsg, NoProtoService, NoRpcImplementation, NoStatusDetailsBinTestService, PingPongPlayer, RpcConfig, SlowService, SslTestService, StatsPerMethod, Struct, SynchronizedCancellationService, TestClientInterceptor, TestServerInterceptor, TestTarget, UserAgentEchoService, WriteFlagSettingStreamingInputEnumerable

Constant Summary collapse

AUTH_ENV =
Google::Auth::CredentialsLoader::ENV_VAR
Server =
GRPC::Core::Server
NoProtoStub =
NoProtoService.rpc_stub_class
UserAgentEchoServiceStub =
UserAgentEchoService.rpc_stub_class
SslTestServiceStub =
SslTestService.rpc_stub_class
EchoStub =
EchoService.rpc_stub_class
TimeConsts =
GRPC::Core::TimeConsts
StatusCodes =
GRPC::Core::StatusCodes
TEST_DEBUG_MESSAGE =
'raised by test server'.freeze
DebugMessageTestServiceStub =
DebugMessageTestService.rpc_stub_class
GenericService =
GRPC::GenericService
Dsl =
GenericService::Dsl
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

Constants included from GRPC::Spec::Helpers

GRPC::Spec::Helpers::RpcServer

Constants included from GRPC::Core::StatusCodes

GRPC::Core::StatusCodes::ABORTED, GRPC::Core::StatusCodes::ALREADY_EXISTS, GRPC::Core::StatusCodes::CANCELLED, GRPC::Core::StatusCodes::DATA_LOSS, GRPC::Core::StatusCodes::DEADLINE_EXCEEDED, GRPC::Core::StatusCodes::FAILED_PRECONDITION, GRPC::Core::StatusCodes::INTERNAL, GRPC::Core::StatusCodes::INVALID_ARGUMENT, GRPC::Core::StatusCodes::NOT_FOUND, GRPC::Core::StatusCodes::OK, GRPC::Core::StatusCodes::OUT_OF_RANGE, GRPC::Core::StatusCodes::PERMISSION_DENIED, GRPC::Core::StatusCodes::RESOURCE_EXHAUSTED, GRPC::Core::StatusCodes::UNAUTHENTICATED, GRPC::Core::StatusCodes::UNAVAILABLE, GRPC::Core::StatusCodes::UNIMPLEMENTED, GRPC::Core::StatusCodes::UNKNOWN

Instance Method Summary collapse

Methods included from GRPC::Spec::Helpers

#build_insecure_stub, #build_rpc_server, #new_core_server_for_testing, #new_rpc_server_for_testing, #run_services_on_server, #update_server_args_hash

Methods included from GRPC::Core::TimeConsts

from_relative_time

Instance Method Details

#_check_args(args) ⇒ Object



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

def _check_args(args)
  %w(server_host server_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

#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



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

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

#close_active_server_call(active_server_call) ⇒ Object



86
87
88
89
# File 'src/ruby/spec/generic/client_stub_spec.rb', line 86

def close_active_server_call(active_server_call)
  active_server_call.send(:set_input_stream_done)
  active_server_call.send(:set_output_stream_done)
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')
  GRPC.logger.info("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



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

def create_stub(opts)
  address = "#{opts.server_host}:#{opts.server_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: {}
    }
    unless opts.server_host_override.empty?
      stub_opts[:channel_args].merge!({
          GRPC::Core::Channel::SSL_TARGET => opts.server_host_override
      })
    end

    # 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

#debug_symbols_output_dirObject



34
35
36
37
38
# File 'src/ruby/ext/grpc/extconf.rb', line 34

def debug_symbols_output_dir
  d = ENV['GRPC_RUBY_DEBUG_SYMBOLS_OUTPUT_DIR']
  return nil if d.nil? or d.size == 0
  d
end

#do_div(stub) ⇒ Object



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

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)
  GRPC.logger.info("Answer: #{resp.inspect}")
  GRPC.logger.info('----------------')
end

#do_div_many(stub) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'src/ruby/bin/math_client.rb', line 77

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)
  resp.each do |r|
    GRPC.logger.info("Answer: #{r.inspect}")
  end
  GRPC.logger.info('----------------')
end

#do_fib(stub) ⇒ Object



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

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)
  resp.each do |r|
    GRPC.logger.info("Answer: #{r.inspect}")
  end
  GRPC.logger.info('----------------')
end

#do_sum(stub) ⇒ Object



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

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

#env_append(name, string) ⇒ Object



72
73
74
# File 'src/ruby/ext/grpc/extconf.rb', line 72

def env_append(name, string)
  ENV[name] += ' ' + string
end

#env_unset?(name) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'src/ruby/ext/grpc/extconf.rb', line 55

def env_unset?(name)
  ENV[name].nil? || ENV[name].size == 0
end

#execute_rpc_in_thread(op, rpc) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'src/ruby/pb/test/xds_client.rb', line 193

def execute_rpc_in_thread(op, rpc)
  Thread.new {
    rpc_stats_key = rpc.to_s
    remote_peer = ""
    begin
      op.execute
      if op..key?('hostname')
        remote_peer = op.['hostname']
      end
      $accumulated_stats_mu.synchronize do
        $num_rpcs_succeeded_by_method[rpc_stats_key] += 1
        $accumulated_method_stats[rpc_stats_key].add_result(0)
      end
    rescue GRPC::BadStatus => e
      $accumulated_stats_mu.synchronize do
        $num_rpcs_failed_by_method[rpc_stats_key] += 1
        $accumulated_method_stats[rpc_stats_key].add_result(e.code)
      end
    end
    $thread_results_mu.synchronize do
      $thread_results << [rpc, remote_peer]
    end
  }
end

#ext_export_filenameObject



171
172
173
174
175
176
# File 'src/ruby/ext/grpc/extconf.rb', line 171

def ext_export_filename()
  name = 'ext-export'
  name += '-truffleruby' if RUBY_ENGINE == 'truffleruby'
  name += '-with-ruby-abi-version' if have_ruby_abi_version()
  name
end

#have_ruby_abi_versionObject



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'src/ruby/ext/grpc/extconf.rb', line 151

def have_ruby_abi_version()
  return true if RUBY_ENGINE == 'truffleruby'
  # ruby_abi_version is only available in development versions: https://github.com/ruby/ruby/pull/6231
  return false if RUBY_PATCHLEVEL >= 0

  m = /(\d+)\.(\d+)/.match(RUBY_VERSION)
  if m.nil?
    puts "Failed to parse ruby version: #{RUBY_VERSION}. Assuming ruby_abi_version symbol is NOT present."
    return false
  end
  major = m[1].to_i
  minor = m[2].to_i
  if major >= 3 and minor >= 2
    puts "Ruby version #{RUBY_VERSION} >= 3.2. Assuming ruby_abi_version symbol is present."
    return true
  end
  puts "Ruby version #{RUBY_VERSION} < 3.2. Assuming ruby_abi_version symbol is NOT present."
  false
end

#inherit_env_or_rbconfig(name) ⇒ Object



59
60
61
# File 'src/ruby/ext/grpc/extconf.rb', line 59

def inherit_env_or_rbconfig(name)
  ENV[name] = inherit_rbconfig(name) if env_unset?(name)
end

#inherit_rbconfig(name, linker_flag: false) ⇒ Object



63
64
65
66
67
68
69
70
# File 'src/ruby/ext/grpc/extconf.rb', line 63

def inherit_rbconfig(name, linker_flag: false)
  value = RbConfig::CONFIG[name] || ''
  if linker_flag
    value = maybe_remove_strip_all_linker_flag(value)
  end
  p "extconf.rb setting ENV[#{name}] = #{value}"
  ENV[name] = value
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



776
777
778
779
780
781
# File 'src/ruby/pb/test/client.rb', line 776

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

#maybe_remove_strip_all_linker_flag(flags) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'src/ruby/ext/grpc/extconf.rb', line 40

def maybe_remove_strip_all_linker_flag(flags)
  if debug_symbols_output_dir
    # Hack to prevent automatic stripping during shared library linking.
    # rake-compiler-dock sets the -s LDFLAG when building rubies for
    # cross compilation, and this -s flag propagates into RbConfig. Stripping
    # during the link is problematic because it prevents us from saving
    # debug symbols. We want to first link our shared library, then save
    # debug symbols, and only after that strip.
    flags = flags.split(' ')
    flags = flags.reject {|flag| flag == '-s'}
    flags = flags.join(' ')
  end
  flags
end

#nulls(l) ⇒ Object

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



173
174
175
176
# File 'src/ruby/pb/test/client.rb', line 173

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

#parse_argsObject

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



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
760
761
762
763
764
765
# File 'src/ruby/pb/test/client.rb', line 730

def parse_args
  args = Args.new
  args.server_host_override = ''
  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['server_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['server_host_override'] = v
    end
    opts.on('--server_port SERVER_PORT', 'server port') do |v|
      args['server_port'] = v
    end
    # 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 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

#run_test_loop(stub, target_seconds_between_rpcs, fail_on_failed_rpcs) ⇒ Object

send 1 rpc every 1/qps second



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'src/ruby/pb/test/xds_client.rb', line 219

def run_test_loop(stub, target_seconds_between_rpcs, fail_on_failed_rpcs)
  include Grpc::Testing
  simple_req = SimpleRequest.new()
  empty_req = Empty.new()
  target_next_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  # Some RPCs are meant to be "kept open". Since Ruby does not have an
  # async API, we are executing those RPCs in a thread so that they don't
  # block.
  keep_open_threads = Array.new
  while !$shutdown
    now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    sleep_seconds = target_next_start - now
    if sleep_seconds < 0
      target_next_start = now + target_seconds_between_rpcs
    else
      target_next_start += target_seconds_between_rpcs
      sleep(sleep_seconds)
    end
    deadline_sec = $rpc_config.timeout_sec > 0 ? $rpc_config.timeout_sec : 30
    deadline = GRPC::Core::TimeConsts::from_relative_time(deadline_sec)
    results = {}
    $rpc_config.rpcs_to_send.each do |rpc|
      # rpc is in the form of :UNARY_CALL or :EMPTY_CALL here
       = $rpc_config..key?(rpc) ?
                   $rpc_config.[rpc] : {}
      $accumulated_stats_mu.synchronize do
        $num_rpcs_started_by_method[rpc.to_s] += 1
        $accumulated_method_stats[rpc.to_s].increment_rpcs_started()
      end
      if rpc == :UNARY_CALL
        op = stub.unary_call(simple_req,
                             metadata: ,
                             deadline: deadline,
                             return_op: true)
      elsif rpc == :EMPTY_CALL
        op = stub.empty_call(empty_req,
                             metadata: ,
                             deadline: deadline,
                             return_op: true)
      else
        raise "Unsupported rpc #{rpc}"
      end
      keep_open_threads << execute_rpc_in_thread(op, rpc)
    end
    # collect results from threads
    $thread_results_mu.synchronize do
      $thread_results.each do |r|
        rpc_name, remote_peer = r
        results[rpc_name] = remote_peer
      end
      $thread_results = Array.new
    end
    $watchers_mutex.synchronize do
      $watchers.each do |watcher|
        # this is counted once when each group of all rpcs_to_send were done
        watcher['rpcs_needed'] -= 1
        results.each do |rpc_name, remote_peer|
          # These stats expect rpc_name to be in the form of
          # UnaryCall or EmptyCall, not the underscore-case all-caps form
          rpc_name = $RPC_MAP.invert()[rpc_name]
          if remote_peer.strip.empty?
            # error is counted per individual RPC
            watcher['no_remote_peer'] += 1
          else
            if not watcher['rpcs_by_method'].key?(rpc_name)
              watcher['rpcs_by_method'][rpc_name] = Hash.new(0)
            end
            # increment the remote hostname distribution histogram
            # both by overall, and broken down per RPC
            watcher['rpcs_by_method'][rpc_name][remote_peer] +=  1
            watcher['rpcs_by_peer'][remote_peer] += 1
          end
        end
      end
      $watchers_cv.broadcast
    end
  end
  keep_open_threads.each { |thd| thd.join }
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_creds(use_test_ca) ⇒ Object

creates the SSL Credentials.



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



21
22
23
24
25
26
27
28
# File 'src/ruby/spec/channel_connection_spec.rb', line 21

def start_server(port = 0)
  @srv = new_rpc_server_for_testing(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



30
31
32
33
34
35
# File 'src/ruby/spec/channel_connection_spec.rb', line 30

def stop_server
  expect(@srv.stopped?).to be(false)
  @srv.stop
  @server_thd.join
  expect(@srv.stopped?).to be(true)
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

#with_protos(file_paths) ⇒ Object



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
# File 'src/ruby/spec/pb/codegen/package_option_spec.rb', line 73

def with_protos(file_paths)
  pb_dir = File.dirname(__FILE__)
  bins_dir = File.join('..', '..', '..', '..', '..', 'cmake', 'build')
  plugin = File.join(bins_dir, 'grpc_ruby_plugin')
  protoc = File.join(bins_dir, 'third_party', 'protobuf', 'protoc')

  # Generate the service from the proto
  Dir.mktmpdir(nil, File.dirname(__FILE__)) do |tmp_dir|
    gen_file = system(protoc,
                      '-I.',
                      *file_paths,
                      "--grpc_out=#{tmp_dir}", # generate the service
                      "--ruby_out=#{tmp_dir}", # generate the definitions
                      "--plugin=protoc-gen-grpc=#{plugin}",
                      chdir: pb_dir,
                      out: File::NULL)

    expect(gen_file).to be_truthy
    begin
      $LOAD_PATH.push(tmp_dir)
      yield
    ensure
      $LOAD_PATH.delete(tmp_dir)
    end
  end
end