Search in sources :

Example 1 with ServerCall

use of io.grpc.ServerCall in project pinpoint by naver.

the class HeaderPropagationInterceptor method interceptCall.

@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
    Header headerObject;
    try {
        headerObject = headerReader.extract(headers);
    } catch (Exception e) {
        if (logger.isInfoEnabled()) {
            logger.info("Header extract fail cause={}, method={} headers={}, attr={}", e.getMessage(), call.getMethodDescriptor().getFullMethodName(), headers, call.getAttributes(), e);
        }
        call.close(Status.INVALID_ARGUMENT.withDescription(e.getMessage()), new Metadata());
        return new ServerCall.Listener<ReqT>() {
        };
    }
    final Context currentContext = Context.current();
    final Context newContext = currentContext.withValue(contextKey, headerObject);
    if (logger.isDebugEnabled()) {
        logger.debug("headerPropagation method={}, headers={}, attr={}", call.getMethodDescriptor().getFullMethodName(), headers, call.getAttributes());
    }
    ServerCall.Listener<ReqT> contextPropagateInterceptor = Contexts.interceptCall(newContext, call, headers, next);
    return contextPropagateInterceptor;
}
Also used : Context(io.grpc.Context) Header(com.navercorp.pinpoint.grpc.Header) ServerCall(io.grpc.ServerCall) Metadata(io.grpc.Metadata)

Example 2 with ServerCall

use of io.grpc.ServerCall in project grpc-java by grpc.

the class CascadingTest method startCallTreeServer.

/**
 * Create a tree of client to server calls where each received call on the server
 * fans out to two downstream calls. Uses SimpleRequest.response_size to limit the nodeCount
 * of the tree. One of the leaves will ABORT to trigger cancellation back up to tree.
 */
private void startCallTreeServer(int depthThreshold) throws IOException {
    final AtomicInteger nodeCount = new AtomicInteger((2 << depthThreshold) - 1);
    server = InProcessServerBuilder.forName("channel").executor(otherWork).addService(ServerInterceptors.intercept(service, new ServerInterceptor() {

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(final ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            // Respond with the headers but nothing else.
            call.sendHeaders(new Metadata());
            call.request(1);
            return new ServerCall.Listener<ReqT>() {

                @Override
                public void onMessage(final ReqT message) {
                    Messages.SimpleRequest req = (Messages.SimpleRequest) message;
                    if (nodeCount.decrementAndGet() == 0) {
                        // we are in the final leaf node so trigger an ABORT upwards
                        Context.currentContextExecutor(otherWork).execute(new Runnable() {

                            @Override
                            public void run() {
                                synchronized (call) {
                                    call.close(Status.ABORTED, new Metadata());
                                }
                            }
                        });
                    } else if (req.getResponseSize() != 0) {
                        // We are in a non leaf node so fire off two requests
                        req = req.toBuilder().setResponseSize(req.getResponseSize() - 1).build();
                        for (int i = 0; i < 2; i++) {
                            asyncStub.unaryCall(req, new StreamObserver<Messages.SimpleResponse>() {

                                @Override
                                public void onNext(Messages.SimpleResponse value) {
                                }

                                @Override
                                public void onError(Throwable t) {
                                    Status status = Status.fromThrowable(t);
                                    if (status.getCode() == Status.Code.CANCELLED) {
                                        observedCancellations.countDown();
                                    }
                                    // Propagate closure upwards.
                                    try {
                                        synchronized (call) {
                                            call.close(status, new Metadata());
                                        }
                                    } catch (IllegalStateException t2) {
                                    // Ignore error if already closed.
                                    }
                                }

                                @Override
                                public void onCompleted() {
                                }
                            });
                        }
                    }
                }

                @Override
                public void onCancel() {
                    receivedCancellations.countDown();
                }
            };
        }
    })).build();
    server.start();
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Status(io.grpc.Status) ServerCallHandler(io.grpc.ServerCallHandler) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) Metadata(io.grpc.Metadata) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerCall(io.grpc.ServerCall) ServerInterceptor(io.grpc.ServerInterceptor) SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse)

Example 3 with ServerCall

use of io.grpc.ServerCall in project grpc-java by grpc.

the class ServerCallsTest method runtimeStreamObserverIsServerCallStreamObserver.

@Test
public void runtimeStreamObserverIsServerCallStreamObserver() throws Exception {
    final AtomicBoolean invokeCalled = new AtomicBoolean();
    final AtomicBoolean onCancelCalled = new AtomicBoolean();
    final AtomicBoolean onReadyCalled = new AtomicBoolean();
    final AtomicReference<ServerCallStreamObserver<Integer>> callObserver = new AtomicReference<>();
    ServerCallHandler<Integer, Integer> callHandler = ServerCalls.asyncBidiStreamingCall(new ServerCalls.BidiStreamingMethod<Integer, Integer>() {

        @Override
        public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
            assertTrue(responseObserver instanceof ServerCallStreamObserver);
            ServerCallStreamObserver<Integer> serverCallObserver = (ServerCallStreamObserver<Integer>) responseObserver;
            callObserver.set(serverCallObserver);
            serverCallObserver.setOnCancelHandler(new Runnable() {

                @Override
                public void run() {
                    onCancelCalled.set(true);
                }
            });
            serverCallObserver.setOnReadyHandler(new Runnable() {

                @Override
                public void run() {
                    onReadyCalled.set(true);
                }
            });
            invokeCalled.set(true);
            return new ServerCalls.NoopStreamObserver<>();
        }
    });
    ServerCall.Listener<Integer> callListener = callHandler.startCall(serverCall, new Metadata());
    serverCall.isReady = true;
    serverCall.isCancelled = false;
    assertTrue(callObserver.get().isReady());
    assertFalse(callObserver.get().isCancelled());
    callListener.onReady();
    callListener.onMessage(1);
    callListener.onCancel();
    assertTrue(invokeCalled.get());
    assertTrue(onReadyCalled.get());
    assertTrue(onCancelCalled.get());
    serverCall.isReady = false;
    serverCall.isCancelled = true;
    assertFalse(callObserver.get().isReady());
    assertTrue(callObserver.get().isCancelled());
    // Is called twice, once to permit the first message and once again after the first message
    // has been processed (auto flow control)
    assertThat(serverCall.requestCalls).containsExactly(1, 1).inOrder();
}
Also used : Metadata(io.grpc.Metadata) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServerCall(io.grpc.ServerCall) Test(org.junit.Test)

Example 4 with ServerCall

use of io.grpc.ServerCall in project grpc-java by grpc.

the class ServerCallsTest method cannotDisableAutoRequestAfterServiceInvocation.

@Test
public void cannotDisableAutoRequestAfterServiceInvocation() throws Exception {
    final AtomicReference<ServerCallStreamObserver<Integer>> callObserver = new AtomicReference<>();
    ServerCallHandler<Integer, Integer> callHandler = ServerCalls.asyncBidiStreamingCall(new ServerCalls.BidiStreamingMethod<Integer, Integer>() {

        @Override
        public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
            callObserver.set((ServerCallStreamObserver<Integer>) responseObserver);
            return new ServerCalls.NoopStreamObserver<>();
        }
    });
    ServerCall.Listener<Integer> callListener = callHandler.startCall(serverCall, new Metadata());
    callListener.onMessage(1);
    try {
        callObserver.get().disableAutoRequest();
        fail("Cannot set onCancel handler after service invocation");
    } catch (IllegalStateException expected) {
    // Expected
    }
}
Also used : Metadata(io.grpc.Metadata) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerCall(io.grpc.ServerCall) Test(org.junit.Test)

Example 5 with ServerCall

use of io.grpc.ServerCall in project grpc-java by grpc.

the class ServerCallsTest method onReadyHandlerCalledForUnaryRequest.

@Test
public void onReadyHandlerCalledForUnaryRequest() throws Exception {
    final AtomicInteger onReadyCalled = new AtomicInteger();
    ServerCallHandler<Integer, Integer> callHandler = ServerCalls.asyncServerStreamingCall(new ServerCalls.ServerStreamingMethod<Integer, Integer>() {

        @Override
        public void invoke(Integer req, StreamObserver<Integer> responseObserver) {
            ServerCallStreamObserver<Integer> serverCallObserver = (ServerCallStreamObserver<Integer>) responseObserver;
            serverCallObserver.setOnReadyHandler(new Runnable() {

                @Override
                public void run() {
                    onReadyCalled.incrementAndGet();
                }
            });
        }
    });
    ServerCall.Listener<Integer> callListener = callHandler.startCall(serverCall, new Metadata());
    serverCall.isReady = true;
    serverCall.isCancelled = false;
    callListener.onReady();
    // On ready is not called until the unary request message is delivered
    assertEquals(0, onReadyCalled.get());
    // delivering the message doesn't trigger onReady listener either
    callListener.onMessage(1);
    assertEquals(0, onReadyCalled.get());
    // half-closing triggers the unary request delivery and onReady
    callListener.onHalfClose();
    assertEquals(1, onReadyCalled.get());
    // Next on ready event from the transport triggers listener
    callListener.onReady();
    assertEquals(2, onReadyCalled.get());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ServerCall(io.grpc.ServerCall) Metadata(io.grpc.Metadata) Test(org.junit.Test)

Aggregations

ServerCall (io.grpc.ServerCall)52 Metadata (io.grpc.Metadata)48 Test (org.junit.Test)42 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)26 AtomicReference (java.util.concurrent.atomic.AtomicReference)19 ServerCallHandler (io.grpc.ServerCallHandler)14 Status (io.grpc.Status)14 Context (io.grpc.Context)11 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 JumpToApplicationThreadServerStreamListener (io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener)10 Server (io.grpc.Server)9 ServerInterceptor (io.grpc.ServerInterceptor)9 ServiceDescriptor (io.grpc.ServiceDescriptor)9 IOException (java.io.IOException)8 ExecutionException (java.util.concurrent.ExecutionException)8 StatusException (io.grpc.StatusException)7 TimeoutException (java.util.concurrent.TimeoutException)7 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)7 Listener (io.grpc.ServerCall.Listener)6 StatusRuntimeException (io.grpc.StatusRuntimeException)5