elixir-grpc / grpc

An Elixir implementation of gRPC
https://hex.pm/packages/grpc
Apache License 2.0
1.39k stars 212 forks source link

Are grpc server contexts supported? #348

Closed flaviogrossi closed 7 months ago

flaviogrossi commented 7 months ago

Describe the question It seems there is no corresponding concept as other languages' contexts, for example grpc.ServicerContext in python.

The use case is to pass down to controllers some information extracted in a server interceptor, for example authentication details (the interceptor extracts a bearer token from the headers, and then enriches the context with user details, user permissions and so on, which are then used in the handler/controller).

Is this scheduled for implementation? Is there another way to support these use cases?

Versions: latest released version (0.7.0)

beligante commented 7 months ago

By design, this is something you can achieve by using a registry inside your interceptor. I guess if this is something to support in the future, probably will have a similar structure.

defmodule MyAppGRPC.Server.Interceptor do

  @behaviour GRPC.Server.Interceptor

  def init(config) do
    ...
  end

  def call(req, stream, next, config) do
    headers = GRPC.Stream.get_headers(stream)
    {:ok, user} = Auth.authorize(headers)

    Registry.register(AuthRegistry, stream, user)

    next.(req, stream)
  end
end

defmodule MyAppGRPC.Server.Foo do
  use GRPC.Server, service: Helloworld.Greeter.Service

  @spec say_hello(Helloworld.HelloRequest.t(), GRPC.Server.Stream.t()) :: Helloworld.HelloReply.t()
  def say_hello(request, stream) do
    [{_pid, user}] = Registry.lookup(AuthRegistry, stream)

    Helloworld.HelloReply.new(
      message: "Hello #{request.name} - Auth as: #{user.name}",
      today: %Google.Protobuf.Timestamp{}
    )
  end
end
flaviogrossi commented 7 months ago

By design, this is something you can achieve by using a registry inside your interceptor.

that's the approach I'm using right now. Thanks for clarifying that it is the currently recommended approach. Closing to mark it as answered.