Home | History | Annotate | Download | only in qps
      1 #!/usr/bin/env ruby
      2 
      3 # Copyright 2016 gRPC authors.
      4 #
      5 # Licensed under the Apache License, Version 2.0 (the "License");
      6 # you may not use this file except in compliance with the License.
      7 # You may obtain a copy of the License at
      8 #
      9 #     http://www.apache.org/licenses/LICENSE-2.0
     10 #
     11 # Unless required by applicable law or agreed to in writing, software
     12 # distributed under the License is distributed on an "AS IS" BASIS,
     13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14 # See the License for the specific language governing permissions and
     15 # limitations under the License.
     16 
     17 # Worker and worker service implementation
     18 
     19 this_dir = File.expand_path(File.dirname(__FILE__))
     20 lib_dir = File.join(File.dirname(this_dir), 'lib')
     21 $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
     22 $LOAD_PATH.unshift(this_dir) unless $LOAD_PATH.include?(this_dir)
     23 
     24 require 'grpc'
     25 
     26 # produces a string of null chars (\0 aka pack 'x') of length l.
     27 def nulls(l)
     28   fail 'requires #{l} to be +ve' if l < 0
     29   [].pack('x' * l).force_encoding('ascii-8bit')
     30 end
     31 
     32 # load the test-only certificates
     33 def load_test_certs
     34   this_dir = File.expand_path(File.dirname(__FILE__))
     35   data_dir = File.join(File.dirname(this_dir), 'spec/testdata')
     36   files = ['ca.pem', 'server1.key', 'server1.pem']
     37   files.map { |f| File.open(File.join(data_dir, f)).read }
     38 end
     39 
     40 
     41 # A EnumeratorQueue wraps a Queue yielding the items added to it via each_item.
     42 class EnumeratorQueue
     43   extend Forwardable
     44   def_delegators :@q, :push
     45 
     46   def initialize(sentinel)
     47     @q = Queue.new
     48     @sentinel = sentinel
     49   end
     50 
     51   def each_item
     52     return enum_for(:each_item) unless block_given?
     53     loop do
     54       r = @q.pop
     55       break if r.equal?(@sentinel)
     56       fail r if r.is_a? Exception
     57       yield r
     58     end
     59   end
     60 end
     61 
     62 # A PingPongEnumerator reads requests and responds one-by-one when enumerated
     63 # via #each_item
     64 class PingPongEnumerator
     65   def initialize(reqs)
     66     @reqs = reqs
     67   end
     68 
     69   def each_item
     70     return enum_for(:each_item) unless block_given?
     71     sr = Grpc::Testing::SimpleResponse
     72     pl = Grpc::Testing::Payload
     73     @reqs.each do |req|
     74       yield sr.new(payload: pl.new(body: nulls(req.response_size)))
     75     end
     76   end
     77 end
     78