gRPC如何在客户端上等待来自StreamingServer的标头

时间:2018-07-12 10:05:45

标签: java stream rpc grpc

对于由原型文件定义的简单gRPC服务:

sudo apt-get install python-dev python-pip

在开始处理来自服务器的响应之前,如何在客户端等待首先等待标头到达?我尝试使用ClientInterceptor并覆盖onHeaders()方法,但在对sayHello()的调用已完成之后会被调用。我该如何验证sayHello客户端中的特定标头,然后根据标头的有效性继续进行调用?

pip install opencv-python

sayHello的代码如下:

service HelloService {
    rpc sayHello() returns (stream string)
}

在上面的sayHello()代码中,它不等待标头到达并且在onHeaders()中设置上下文。我怎样才能做到这一点?在验证服务器发送的流中是否存在some_header之后,我只想将流返回给客户端调用方。

1 个答案:

答案 0 :(得分:3)

标头是由服务器在发送第一条消息之前发送的,因此简单的方法是调用stream.hasNext(),这将阻止等待消息。在许多RPC中,第一条消息很快出现在响应标头之后,因此可以很好地工作。

顺便说一句,我注意到您正在尝试CallOptionsContext

callOptions.withOption(someHeader, "true");
Context.current().withValue(Context.key("test"), "testvalue");

因为这两个对象都是不可变的,所以这两行都不起作用。 with*调用将创建一个新实例,因此您必须使用该行的返回值来执行任何操作。同样,CallOptions和Context主要以相反的方向传递信息,例如从客户端应用程序传递到拦截器。要“反转”方向,应用程序需要设置一个可变的值,例如AtomicReference或回调函数,然后拦截器可以与该值进行交互。

如果服务器响应标头和第一条消息之间可能存在明显的延迟,则情况会变得更加复杂。调用sayHello()的代码:

CompletableFuture<Boolean> future = new CompletableFuture<>();
Iterator<String> stream = blockingStub
    .withOption(SomeHeaderInterceptor.SOME_HEADER, future)
    .sayHello();
// wait for the sayhello active header 
boolean isActive = future.get();

然后在拦截器中

private static final String FULL_METHOD_NAME =
    //"helloworld.Greeter/SayHello";
    GreeterGrpc.getSayHelloMethod().getFullMethodName();
public static final CallOptions.Key<CompletableFuture<Boolean>> SOME_HEADER =
    CallOptions.Key.create("some_header_active", CompletableFuture.completedFuture(false));
private static final Metadata.Key<String> SAYHELLO_ACTIVE_HEADER =
    Metadata.Key.of("some_header_active", Metadata.ASCII_STRING_MARSHALLER);

@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor,
                                                           CallOptions callOptions, Channel channel) {
    CompletableFuture<Boolean> future = callOptions.getOption(SOME_HEADER);
    if (!methodDescriptor.getFullMethodName().equals(FULL_METHOD_NAME)) {
        future.complete(false);
        return channel.newCall(methodDescriptor, callOptions);
    }
    return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(channel.newCall(methodDescriptor, callOptions)) {

        @Override
        public void start(Listener<RespT> responseListener, Metadata headers) {
            super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
                @Override
                public void onHeaders(Metadata headers) {
                    if (!headers.containsKey(SAYHELLO_ACTIVE_HEADER)) {
                        // Could also be future.complete(false)
                        future.completeExceptionally(new Exception("some_header activation missing from header: " + headers));
                    } else {
                        future.complete(true);
                    }
                    super.onHeaders(headers);
                }

                @Override
                public void onClose(Status status, Metadata trailers) {
                    // onHeaders() might not have been called, especially if there was an error
                    if (!future.isDone()) {
                        future.completeExceptionally(status.asRuntimeException(trailers));
                    }
                    super.onClose(status, trailers);
                }
            }, headers);
        }
    };
}

如果您只需要执行验证,而不需要实际延迟,那么可以避免延迟,并在验证失败时让拦截器使调用失败:

private static final String FULL_METHOD_NAME =
    //"helloworld.Greeter/SayHello";
    GreeterGrpc.getSayHelloMethod().getFullMethodName();
private static final Metadata.Key<String> SAYHELLO_ACTIVE_HEADER =
    Metadata.Key.of("some_header_active", Metadata.ASCII_STRING_MARSHALLER);

@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor,
                                                           CallOptions callOptions, Channel channel) {
    if (!methodDescriptor.getFullMethodName().equals(FULL_METHOD_NAME)) {
        return channel.newCall(methodDescriptor, callOptions);
    }
    // We use context to cancel since it is thread-safe, whereas ClientCall.cancel is not
    CancellableContext context = Context.current().withCancellation();
    class ValidatingListener extends ForwardingClientCallListener<RespT> {
        private Listener<RespT> responseListener;

        public ValidatingListener(Listener<RespT> responseListener) {
            this.responseListener = responseListener;
        }

        @Override
        protected Listener<RespT> delegate() {
            return responseListener;
        }

        @Override
        public void onHeaders(Metadata headers) {
            if (!headers.containsKey(SAYHELLO_ACTIVE_HEADER)) {
                Listener<RespT> saved = responseListener;
                responseListener = new Listener<RespT>() {}; // noop listener; throw away future events
                Status status = Status.UNKNOWN.withDescription(
                        "some_header activation missing from header: " + headers);
                context.cancel(status.asRuntimeException());
                saved.onClose(status, new Metadata());
                return;
            }
            // Validation successful
            super.onHeaders(headers);
        }

        @Override
        public void onClose(Status status, Metadata trailers) {
            context.close();
        }
    }

    Context toRestore = context.attach();
    try {
        return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(channel.newCall(methodDescriptor, callOptions)) {

            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {
                super.start(new ValidatingListener(responseListener), headers);
            }
        };
    } finally {
        context.detach(toRestore);
    }
}