Class: GRPC::OpenTracing::ClientInterceptor

Inherits:
Object
  • Object
show all
Defined in:
lib/grpc/opentracing/client_interceptor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tracer: ::OpenTracing.global_tracer, active_span: nil, decorators: [RequestReplySpanDecorator]) ⇒ ClientInterceptor

Returns a new instance of ClientInterceptor.



6
7
8
9
10
# File 'lib/grpc/opentracing/client_interceptor.rb', line 6

def initialize(tracer: ::OpenTracing.global_tracer, active_span: nil, decorators: [RequestReplySpanDecorator])
  @tracer = tracer
  @active_span = active_span
  @decorators = decorators
end

Instance Attribute Details

#active_spanObject (readonly)

Returns the value of attribute active_span.



4
5
6
# File 'lib/grpc/opentracing/client_interceptor.rb', line 4

def active_span
  @active_span
end

#decoratorsObject (readonly)

Returns the value of attribute decorators.



4
5
6
# File 'lib/grpc/opentracing/client_interceptor.rb', line 4

def decorators
  @decorators
end

#tracerObject (readonly)

Returns the value of attribute tracer.



4
5
6
# File 'lib/grpc/opentracing/client_interceptor.rb', line 4

def tracer
  @tracer
end

Instance Method Details

#intercept(client) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/grpc/opentracing/client_interceptor.rb', line 12

def intercept(client)
  client.instance_variable_set(:@tracer, tracer)
  client.instance_variable_set(:@active_span, active_span)
  client.instance_variable_set(:@decorators, decorators)

  client.instance_eval do
    class << self
      alias_method :request_response_without_instrumentation, :request_response
    end

    def active_span
      @active_span.respond_to?(:call) ? @active_span.call : @active_span
    end

    def request_response(method, req, marshal, unmarshal, metadata: {}, **fields)
      tags = {
        'component' => 'gRPC',
        'span.kind' => 'client',
        'grpc.method_type' => 'request_response',
        'grpc.headers' => MultiJson.dump()
      }
      current_span = @tracer.start_span(method, child_of: active_span, tags: tags)

      hpack_carrier = HPACKCarrier.new()
      @tracer.inject(current_span.context, ::OpenTracing::FORMAT_TEXT_MAP, hpack_carrier)

      response = request_response_without_instrumentation(method, req, marshal, unmarshal,
                                                          metadata: , **fields)

      response
    rescue Exception => e
      if current_span
        current_span.set_tag('error', true)
        current_span.log(event: 'error', :'error.object' => e)
      end
      raise
    ensure
      if @decorators
        @decorators.each do |decorator|
          decorator.call(current_span, method, req, response, e)
        end
      end
      current_span.finish if current_span
    end
  end

  client
end