module Yrpc class Client < SimpleDelegator def initialize(service:, options: {}, client_options: {}) @base_klass = service @service_klass = "#{base_klass}::Service".constantize @opts = options || {} @opts[:password] = options.fetch(:password, '').to_s @opts[:hostname] = options.fetch(:hostname, Yrpc.default_client_host) client = "#{service}::Stub".constantize.new(@opts[:hostname], build_ssl_credentials, interceptors: [*client_options[:interceptors]]) super(client) end attr_reader :service_klass attr_reader :base_klass attr_reader :opts def invoke(request_method, params = {}, metadata={}, opts={}, &block) request_method = request_method.to_sym req = streaming_request?(request_method) ? params : request_object(request_method, params) md = build_metadata(metadata) call_sig = call_signature(request_method) raise NotImplementedError, "The method #{request_method} has not been implemented in this service." unless call_sig resp = execute(call_sig, req, md, opts, &block) p resp Response.new(resp) end def build_metadata(metadata = {}) unless opts[:password].empty? username = opts.fetch(:username, 'grpc').to_s username = username.empty? ? '' : "#{username}:" auth_string = Base64.encode64("#{username}#{opts[:password]}") metadata[:authorization] = "Basic #{auth_string}".tr("\n", '') end metadata end def execute(call_sig, req, metadata, opts = {}, &block) # Timer.time do opts[:return_op] = true opts[:metadata] = metadata # end send(call_sig, req, opts, &block) end def rpc_desc(request_method) service_klass.rpc_descs[request_method] end def request_object(request_method, params = {}) desc = rpc_desc(request_method) desc && desc.input ? desc.input.new(params) : nil end def call_signature(request_method) desc = rpc_desc(request_method) desc && desc.name ? desc.name.to_s.underscore.to_sym : nil end def build_ssl_credentials cert = nil if opts[:ssl_certificate_file] cert = File.read(opts[:ssl_certificate_file]).to_s.strip elsif opts[:ssl_certificate] cert = opts[:ssl_certificate].to_s.strip end cert ? GRPC::Core::ChannelCredentials.new(cert) : :this_channel_is_insecure end def streaming_request?(request_method) desc = rpc_desc(request_method) desc && (desc.client_streamer? || desc.bidi_streamer?) end end end