Skip to content

Client: Interceptors

Shaun McCormick edited this page Jul 14, 2023 · 3 revisions

Gruf comes with an assistance class for client interceptors that you can use - or you can use the native gRPC core interceptors. Either way, you pass them into the client_options when creating a client:

class MyInterceptor < Gruf::Interceptors::ClientInterceptor
  def call(request_context:)
    logger.info "Got method #{request_context.method}!"
    yield
  end
end

client = ::Gruf::Client.new(
  service: ::Demo::Jobs,
  client_options: {
    interceptors: [MyInterceptor.new]
  }
)

The interceptors option in client_options can accept either a GRPC::ClientInterceptor class or a Gruf::Interceptors::ClientInterceptor, since the latter just extends the former. The gruf client interceptors take an optional alternative approach: rather than having separate methods for each request type, it provides a default call method that passes in a RequestContext object, which has the following attributes:

  • type - A Symbol of the type of request (request_response, server_streamer, etc)
  • requests An enumerable of requests being sent. For unary requests, this is a single request in an array
  • call - The GRPC::ActiveCall object
  • method - The Method being called
  • metadata - The hash of outgoing metadata

Note that you must yield back the block when building a client interceptor, so that the call can be executed.

Example: Adding a JWT to outgoing metadata

First, create an interceptor:

class MyInterceptor < ::Gruf::Interceptors::ClientInterceptor
  def call(request_context:)
    request_context.metadata[:jwt] = JwtGenerator.build
    yield
  end
end

Then in your gruf client instantiation:

client = Gruf::Client.new(
  service: ::MyRpcService,
  options: {
    hostname: "0.0.0.0:9000" # address of service
  },
  client_options: {
    interceptors: [MyInterceptor.new]
  }
)
req = MyReq.new(name: 'foo')
client.call(:MyEndpoint, req)

This will run your interceptor for each call with that client.


Next: Client: Synchronized Calls