Search in sources :

Example 21 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project spring_boot by hryou0922.

the class HelloStreamClient method client2ServerRpc.

/**
 * 异步客户端流
 */
public void client2ServerRpc(int count) throws InterruptedException {
    logger.info("request client2ServerRpc {}", count);
    final CountDownLatch finishLatch = new CountDownLatch(1);
    StreamObserver<SimpleSummary> responseObserver = new StreamObserver<SimpleSummary>() {

        @Override
        public void onNext(SimpleSummary value) {
            // 返回SimpleSummary
            logger.info("client2ServerRpc onNext : {}", value);
        }

        @Override
        public void onError(Throwable t) {
            logger.error("client2ServerRpc error : {}", t);
            finishLatch.countDown();
        }

        @Override
        public void onCompleted() {
            logger.error("client2ServerRpc finish");
            finishLatch.countDown();
        }
    };
    StreamObserver<Simple> requestObserver = asyncStub.client2ServerRpc(responseObserver);
    try {
        for (int i = 0; i < count; i++) {
            logger.info("simple2 : {}", i);
            Simple simple = Simple.newBuilder().setName("client2ServerRpc" + i).setNum(i).build();
            requestObserver.onNext(simple);
            Thread.sleep(random.nextInt(200) + 50);
        }
    } catch (RuntimeException e) {
        // Cancel RPC
        requestObserver.onError(e);
        throw e;
    }
    // 结束请求
    requestObserver.onCompleted();
    // Receiving happens asynchronously
    if (!finishLatch.await(1, TimeUnit.MINUTES)) {
        logger.error("client2ServerRpc can not finish within 1 minutes");
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) StatusRuntimeException(io.grpc.StatusRuntimeException) SimpleSummary(com.hry.spring.grpc.mystream.SimpleSummary) CountDownLatch(java.util.concurrent.CountDownLatch) Simple(com.hry.spring.grpc.mystream.Simple)

Example 22 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project fabric-sdk-java by hyperledger.

the class OrdererClient method sendDeliver.

DeliverResponse[] sendDeliver(Common.Envelope envelope) throws TransactionException {
    if (shutdown) {
        throw new TransactionException("Orderer client is shutdown");
    }
    StreamObserver<Common.Envelope> nso = null;
    ManagedChannel lmanagedChannel = managedChannel;
    if (lmanagedChannel == null || lmanagedChannel.isTerminated() || lmanagedChannel.isShutdown()) {
        lmanagedChannel = channelBuilder.build();
        managedChannel = lmanagedChannel;
    }
    try {
        AtomicBroadcastGrpc.AtomicBroadcastStub broadcast = AtomicBroadcastGrpc.newStub(lmanagedChannel);
        // final DeliverResponse[] ret = new DeliverResponse[1];
        final List<DeliverResponse> retList = new ArrayList<>();
        final List<Throwable> throwableList = new ArrayList<>();
        final CountDownLatch finishLatch = new CountDownLatch(1);
        StreamObserver<DeliverResponse> so = new StreamObserver<DeliverResponse>() {

            boolean done = false;

            @Override
            public void onNext(DeliverResponse resp) {
                // logger.info("Got Broadcast response: " + resp);
                logger.debug("resp status value: " + resp.getStatusValue() + ", resp: " + resp.getStatus() + ", type case: " + resp.getTypeCase());
                if (done) {
                    return;
                }
                if (resp.getTypeCase() == STATUS) {
                    done = true;
                    retList.add(0, resp);
                    finishLatch.countDown();
                } else {
                    retList.add(resp);
                }
            }

            @Override
            public void onError(Throwable t) {
                if (!shutdown) {
                    logger.error(format("Received error on channel %s, orderer %s, url %s, %s", channelName, name, url, t.getMessage()), t);
                }
                throwableList.add(t);
                finishLatch.countDown();
            }

            @Override
            public void onCompleted() {
                logger.trace("onCompleted");
                finishLatch.countDown();
            }
        };
        nso = broadcast.deliver(so);
        nso.onNext(envelope);
        try {
            if (!finishLatch.await(ordererWaitTimeMilliSecs, TimeUnit.MILLISECONDS)) {
                TransactionException ex = new TransactionException(format("Channel %s sendDeliver time exceeded for orderer %s, timed out at %d ms.", channelName, name, ordererWaitTimeMilliSecs));
                logger.error(ex.getMessage(), ex);
                throw ex;
            }
            logger.trace("Done waiting for reply!");
        } catch (InterruptedException e) {
            logger.error(e);
        }
        if (!throwableList.isEmpty()) {
            Throwable throwable = throwableList.get(0);
            TransactionException e = new TransactionException(format("Channel %s sendDeliver failed on orderer %s. Reason: %s", channelName, name, throwable.getMessage()), throwable);
            logger.error(e.getMessage(), e);
            throw e;
        }
        return retList.toArray(new DeliverResponse[retList.size()]);
    } catch (Throwable t) {
        managedChannel = null;
        throw t;
    } finally {
        if (null != nso) {
            try {
                nso.onCompleted();
            } catch (Exception e) {
                // Best effort only report on debug
                logger.debug(format("Exception completing sendDeliver with channel %s,  name %s, url %s %s", channelName, name, url, e.getMessage()), e);
            }
        }
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) AtomicBroadcastGrpc(org.hyperledger.fabric.protos.orderer.AtomicBroadcastGrpc) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) TransactionException(org.hyperledger.fabric.sdk.exception.TransactionException) ManagedChannel(io.grpc.ManagedChannel) DeliverResponse(org.hyperledger.fabric.protos.orderer.Ab.DeliverResponse)

Example 23 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project ballerina by ballerina-lang.

the class ErrorResponse method execute.

@Override
public void execute(Context context) {
    BStruct endpointClient = (BStruct) context.getRefArgument(CLIENT_RESPONDER_REF_INDEX);
    BValue responseValue = context.getRefArgument(RESPONSE_MESSAGE_REF_INDEX);
    if (responseValue instanceof BStruct) {
        BStruct responseStruct = (BStruct) responseValue;
        int statusCode = Integer.parseInt(String.valueOf(responseStruct.getIntField(0)));
        String errorMsg = responseStruct.getStringField(0);
        StreamObserver responseObserver = MessageUtils.getResponseObserver(endpointClient);
        if (responseObserver == null) {
            context.setError(MessageUtils.getConnectorError(context, new StatusRuntimeException(Status.fromCode(Status.INTERNAL.getCode()).withDescription("Error while sending the error. Response" + " observer not found."))));
        } else {
            responseObserver.onError(new StatusRuntimeException(Status.fromCodeValue(statusCode).withDescription(errorMsg)));
        }
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) BStruct(org.ballerinalang.model.values.BStruct) BValue(org.ballerinalang.model.values.BValue) StatusRuntimeException(io.grpc.StatusRuntimeException)

Example 24 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project ballerina by ballerina-lang.

the class IsCancelled method execute.

@Override
public void execute(Context context) {
    BStruct endpointClient = (BStruct) context.getRefArgument(CLIENT_RESPONDER_REF_INDEX);
    StreamObserver responseObserver = MessageUtils.getResponseObserver(endpointClient);
    if (responseObserver instanceof ServerCallStreamObserver) {
        ServerCallStreamObserver serverCallStreamObserver = (ServerCallStreamObserver) responseObserver;
        context.setReturnValues(new BBoolean(serverCallStreamObserver.isCancelled()));
    } else {
        context.setReturnValues(new BBoolean(Boolean.TRUE));
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) BStruct(org.ballerinalang.model.values.BStruct) BBoolean(org.ballerinalang.model.values.BBoolean)

Example 25 with StreamObserver

use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver in project ballerina by ballerina-lang.

the class Complete method execute.

@Override
public void execute(Context context) {
    BStruct connectionStruct = (BStruct) context.getRefArgument(0);
    StreamObserver requestSender = (StreamObserver) connectionStruct.getNativeData(REQUEST_SENDER);
    if (requestSender == null) {
        context.setError(MessageUtils.getConnectorError(context, new StatusRuntimeException(Status.fromCode(Status.INTERNAL.getCode()).withDescription("Error while initializing connector. " + "response sender doesnot exist"))));
    } else {
        try {
            requestSender.onCompleted();
        } catch (Throwable e) {
            LOG.error("Error while sending client response.", e);
            context.setError(MessageUtils.getConnectorError(context, e));
        }
    }
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) BStruct(org.ballerinalang.model.values.BStruct) StatusRuntimeException(io.grpc.StatusRuntimeException)

Aggregations

StreamObserver (io.grpc.stub.StreamObserver)130 Test (org.junit.Test)93 CountDownLatch (java.util.concurrent.CountDownLatch)50 ArrayList (java.util.ArrayList)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)38 StreamObserver (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.stub.StreamObserver)27 StatusRuntimeException (io.grpc.StatusRuntimeException)26 Status (io.grpc.Status)20 List (java.util.List)18 BeamFnApi (org.apache.beam.model.fnexecution.v1.BeamFnApi)18 ManagedChannel (org.apache.beam.vendor.grpc.v1p43p2.io.grpc.ManagedChannel)18 CompletableFuture (java.util.concurrent.CompletableFuture)17 ExecutorService (java.util.concurrent.ExecutorService)16 SegmentId (io.pravega.controller.stream.api.grpc.v1.Controller.SegmentId)14 ServerRequest (io.pravega.controller.stream.api.grpc.v1.Controller.ServerRequest)14 VisibleForTesting (com.google.common.annotations.VisibleForTesting)12 Strings (com.google.common.base.Strings)12 Throwables (com.google.common.base.Throwables)12 ImmutableMap (com.google.common.collect.ImmutableMap)12 AuthHandler (io.pravega.auth.AuthHandler)12