How to Access attributes from grpc Context.current()?
Asked Answered
S

1

5

Would it be possible to access context attributes of a grpc call from the rpc method definition?

I have written a Server Interceptor which is something similar to this

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, final Metadata requestHeaders, ServerCallHandler<ReqT, RespT> next) {

   Context.Key<String> USER = Context.key("USER");
 
  Context ctx = Context.current().withValue(USER, "chandan");
  return Contexts.interceptCall(ctx, call, requestHeaders, next);
}

and in the service implementation, I was trying something like

Context.Key<String> key = Context.key("USER");
String value = key.get(Context.current())

Everytime value was null. However While debugging in intellij I could see those values in the context.current().keyValueEntries as

CompressedIndex(bitmap=100001000000000000000000000000 Leaf(key=USER value=chandan) Leaf(key=opencensus-trace-span-key value=BlankSpan) )

How do I access the Context attributes/What is the right way to go about this?

Stickler answered 18/7, 2019 at 15:45 Comment(0)
A
9

Context.Key uses reference equality. The "USER" string is a debug string used in toString() output. You should create the Key once and reference that one instance anywhere you need it.

Because Context.Key uses reference equality, you can use normal Java visibility restrictions to limit who can access the value, just like you could do with ThreadLocal.

Allegedly answered 18/7, 2019 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.