Grpc Java server test for ServerInterceptors

216 views
Skip to first unread message

Eduwer Camacaro

unread,
Nov 7, 2023, 3:48:34 PM11/7/23
to grpc.io
Hi Grpc team! 
I have a ServerInterceptor instance for my grpc server, it does something like this:

@Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
            ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
        Context context = Context.current();
        .... // more code here 
        context = context.withValue(USER_ID, "my-user-id");
        return Contexts.interceptCall(context, call, headers, next);
    }

and in my service method I get access to the userId using smth like this:

USER_ID.get()


I have some questions:
Is this implementation correct?
Is this thread safe?
Is there any way to test that implementation?
Is there any documentation that I can check to understand how Threads are handled by the grpc server?

Thanks in advance! :) 

Edu-

Larry Safran

unread,
Nov 7, 2023, 7:24:37 PM11/7/23
to Eduwer Camacaro, grpc.io
Hi Edu,

Yes, that implementation looks good.  We have an example that does something similar:  https://github.com/grpc/grpc-java/tree/master/examples/example-oauth

ServerInterceptors are called sequentially by a single thread, so it will be thread safe.  Additionally, Context objects are immutable.  Context.withValue constructs a new object, so there is no concern about threads doing concurrent updates.

The example has a unit test using JUnit.  I would recommend also making very simple client/server classes like in the above example to see it working end-to-end.  

As to documentation, there is no central documentation discussing threads.  We do use the @ThreadSafe annotation (for example on ServerInterceptor).  Anything public (not Experimental or Internal) not so annotated should be assumed not to be thread safe. If you look through the code, you will see that much of the task coordination that is done is through the use of Executor classes.  

Thanks,
  Larry

--
You received this message because you are subscribed to the Google Groups "grpc.io" group.
To unsubscribe from this group and stop receiving emails from it, send an email to grpc-io+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/grpc-io/928b79d2-8b8c-4b0f-bc8f-51a4bc0dcd5an%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages