Hi there,
I have a load balancer that routes based on a shard ID to the correct gRPC server. The code is essentially the following:
  public void stateUpdate(StateUpdateRequest req, StreamObserver<Empty> responseObserver) {
       // Run on Virtual Thread
    executor.submit(() -> {
      if (isAuthorized(req)) {
        responseObserver.onError(Status.PERMISSION_DENIED.asException());
        return;
      }
      try {
        int shard = calculateShard(req.getAccount());
        // How to add "X-Shard" header with above value to request?
        clientStub
          .update(createUpdateRequest(req));
      } catch (Exception e) {
        log.error("forwarding state update", e);
        responseObserver.onError(Status.INTERNAL.asException());
        return;
      }
      responseObserver.onNext(EMPTY);
      responseObserver.onCompleted();
    });
  }
I would need to add the calculated shard as the "X-Shard" header value to every request made by the stub. The single stub is shared by all the threads.
What is the easiest way to make this happen? I've previously created stubs with interceptors that always attach a fixed header value, e.g. a JWT token. However, the header value is dynamically calculated in this case. If I use withOptions to pass data to the interceptor, then on the surface it doesn't seem thread-safe unless there's something smart being done under the hood?
My question: What is the cleanest way to accomplish this?
Best,
Edvard