tsloughter / grpcbox

Erlang grpc on chatterbox
Apache License 2.0
139 stars 62 forks source link

Add optional configuration information to service handlers #70

Open srstrong opened 2 years ago

srstrong commented 2 years ago

I have an issue where it would be nice to add an additional parameter to every service method with some configuration/state information provided when starting the service - so something along the lines of:

AdditionalOptions = ... %% some term
Server = #{grpc_opts => #{service_protos => [my_service], 
                                              services => #{'my.myService' => {my_service_handler, AdditionalOptions}}
                  ,...}
grpcbox:start_server(Server)

and then in my_service.erl:

my_service_function(Ctx, Input, AdditionalOptions) ->
 ...

or alternatively:

my_service_function(Ctx, Input) ->
  AdditionalOptions = ctx:get(Ctx, ctx_additional_options),
  ...

I guess the latter means that the generated behaviours don't need changing...

Any thoughts on a) whether this is a PR that you'd be interested in taking and b) if it is something you'd be interested in, views on what the usage should look like?

tsloughter commented 2 years ago

So just some additional configuration you can pass to the server handler? Makes sense to me. Surprised that isn't already possible, hehe, since the only other option I guess would be to be pulling that out of like application;get_env and that is poor form.

I wouldn't put it in the context, no. Assuming I understand the purpose, that it is values you need in the handler that you might otherwise read out of the application environment on each handler call instead of once at the start.

srstrong commented 2 years ago

My scenario is that I'm spinning up multiple instances of a service dynamically on different ports, and each instance needs its own configuration information. I've already got a version working that extends #method to include the extra information, and then grpcbox_stream pulls it out and stores it in the ctx instance for that call. The handler can then pull it from the ctx and do whatever it needs to do. If I pass it as a parameter on the method calls, then I'm inclined to make it a list with a default of [] and always pass it, and make the corresponding update to grpcbox_plugin to add that extra argument (so a list(term())) to the callbacks that go in the behaviour.