use of io.grpc.stub.StreamObserver in project grpc-java by grpc.
the class MoreInProcessTest method asyncClientStreaming_serverResponsePriorToRequest.
@Test
public void asyncClientStreaming_serverResponsePriorToRequest() throws Exception {
// implement a service
final StreamingInputCallResponse fakeResponse = StreamingInputCallResponse.newBuilder().setAggregatedPayloadSize(100).build();
TestServiceImplBase clientStreamingImpl = new TestServiceImplBase() {
@Override
public StreamObserver<StreamingInputCallRequest> streamingInputCall(StreamObserver<StreamingInputCallResponse> responseObserver) {
// send response directly
responseObserver.onNext(fakeResponse);
responseObserver.onCompleted();
return new StreamObserver<StreamingInputCallRequest>() {
@Override
public void onNext(StreamingInputCallRequest value) {
}
@Override
public void onError(Throwable t) {
}
@Override
public void onCompleted() {
}
};
}
};
serviceRegistry.addService(clientStreamingImpl);
// implement a client
final CountDownLatch finishLatch = new CountDownLatch(1);
final AtomicReference<StreamingInputCallResponse> responseRef = new AtomicReference<StreamingInputCallResponse>();
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
StreamObserver<StreamingInputCallResponse> responseObserver = new StreamObserver<StreamingInputCallResponse>() {
@Override
public void onNext(StreamingInputCallResponse response) {
responseRef.set(response);
}
@Override
public void onError(Throwable t) {
throwableRef.set(t);
finishLatch.countDown();
}
@Override
public void onCompleted() {
finishLatch.countDown();
}
};
// make a gRPC call
TestServiceGrpc.newStub(inProcessChannel).streamingInputCall(responseObserver);
assertTrue(finishLatch.await(900, TimeUnit.MILLISECONDS));
assertEquals(fakeResponse, responseRef.get());
assertNull(throwableRef.get());
}
use of io.grpc.stub.StreamObserver in project core-java by SpineEventEngine.
the class CommandRouterOnErrorShould method createRouter.
/**
* Creates a router with mocked {@code CommandBus} which always calls
* {@link StreamObserver#onError(Throwable) StreamObserver.onError()} when
* {@link CommandBus#post(Command, StreamObserver) CommandBus.post()} is invoked.
*/
@Override
CommandRouter createRouter(CommandBus ignored, Message sourceMessage, CommandContext commandContext) {
final CommandBus mockBus = mock(CommandBus.class);
doAnswer(new Answer() {
// is OK for Answer
@SuppressWarnings("ReturnOfNull")
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
final StreamObserver<Response> observer = invocation.getArgument(1);
observer.onError(new RuntimeException("simulate error"));
return null;
}
}).when(mockBus).post(any(Command.class), ArgumentMatchers.<StreamObserver<Response>>any());
return new CommandRouter(mockBus, sourceMessage, commandContext);
}
use of io.grpc.stub.StreamObserver in project beam by apache.
the class BeamFnLoggingClientTest method testLogging.
@Test
public void testLogging() throws Exception {
AtomicBoolean clientClosedStream = new AtomicBoolean();
Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver = new AtomicReference<>();
CallStreamObserver<BeamFnApi.LogEntry.List> inboundServerObserver = TestStreams.withOnNext((BeamFnApi.LogEntry.List logEntries) -> values.addAll(logEntries.getLogEntriesList())).withOnCompleted(new Runnable() {
@Override
public void run() {
// Remember that the client told us that this stream completed
clientClosedStream.set(true);
outboundServerObserver.get().onCompleted();
}
}).build();
BeamFnApi.ApiServiceDescriptor apiServiceDescriptor = BeamFnApi.ApiServiceDescriptor.newBuilder().setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString()).build();
Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl()).addService(new BeamFnLoggingGrpc.BeamFnLoggingImplBase() {
@Override
public StreamObserver<BeamFnApi.LogEntry.List> logging(StreamObserver<BeamFnApi.LogControl> outboundObserver) {
outboundServerObserver.set(outboundObserver);
return inboundServerObserver;
}
}).build();
server.start();
try {
ManagedChannel channel = InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
BeamFnLoggingClient client = new BeamFnLoggingClient(PipelineOptionsFactory.fromArgs(new String[] { "--defaultWorkerLogLevel=OFF", "--workerLogLevelOverrides={\"ConfiguredLogger\": \"DEBUG\"}" }).create(), apiServiceDescriptor, (BeamFnApi.ApiServiceDescriptor descriptor) -> channel, this::createStreamForTest);
// Ensure that log levels were correctly set.
assertEquals(Level.OFF, LogManager.getLogManager().getLogger("").getLevel());
assertEquals(Level.FINE, LogManager.getLogManager().getLogger("ConfiguredLogger").getLevel());
// Should be filtered because the default log level override is OFF
LogManager.getLogManager().getLogger("").log(FILTERED_RECORD);
// Should not be filtered because the default log level override for ConfiguredLogger is DEBUG
LogManager.getLogManager().getLogger("ConfiguredLogger").log(TEST_RECORD);
LogManager.getLogManager().getLogger("ConfiguredLogger").log(TEST_RECORD_WITH_EXCEPTION);
client.close();
// Verify that after close, log levels are reset.
assertEquals(Level.INFO, LogManager.getLogManager().getLogger("").getLevel());
assertNull(LogManager.getLogManager().getLogger("ConfiguredLogger").getLevel());
assertTrue(clientClosedStream.get());
assertTrue(channel.isShutdown());
assertThat(values, contains(TEST_ENTRY, TEST_ENTRY_WITH_EXCEPTION));
} finally {
server.shutdownNow();
}
}
use of io.grpc.stub.StreamObserver in project beam by apache.
the class BeamFnDataGrpcClientTest method testForInboundConsumer.
@Test
public void testForInboundConsumer() throws Exception {
CountDownLatch waitForClientToConnect = new CountDownLatch(1);
Collection<WindowedValue<String>> inboundValuesA = new ConcurrentLinkedQueue<>();
Collection<WindowedValue<String>> inboundValuesB = new ConcurrentLinkedQueue<>();
Collection<BeamFnApi.Elements> inboundServerValues = new ConcurrentLinkedQueue<>();
AtomicReference<StreamObserver<BeamFnApi.Elements>> outboundServerObserver = new AtomicReference<>();
CallStreamObserver<BeamFnApi.Elements> inboundServerObserver = TestStreams.withOnNext(inboundServerValues::add).build();
BeamFnApi.ApiServiceDescriptor apiServiceDescriptor = BeamFnApi.ApiServiceDescriptor.newBuilder().setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString()).build();
Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl()).addService(new BeamFnDataGrpc.BeamFnDataImplBase() {
@Override
public StreamObserver<BeamFnApi.Elements> data(StreamObserver<BeamFnApi.Elements> outboundObserver) {
outboundServerObserver.set(outboundObserver);
waitForClientToConnect.countDown();
return inboundServerObserver;
}
}).build();
server.start();
try {
ManagedChannel channel = InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
BeamFnDataGrpcClient clientFactory = new BeamFnDataGrpcClient(PipelineOptionsFactory.create(), (BeamFnApi.ApiServiceDescriptor descriptor) -> channel, this::createStreamForTest);
CompletableFuture<Void> readFutureA = clientFactory.forInboundConsumer(apiServiceDescriptor, KEY_A, CODER, inboundValuesA::add);
waitForClientToConnect.await();
outboundServerObserver.get().onNext(ELEMENTS_A_1);
// Purposefully transmit some data before the consumer for B is bound showing that
// data is not lost
outboundServerObserver.get().onNext(ELEMENTS_B_1);
Thread.sleep(100);
CompletableFuture<Void> readFutureB = clientFactory.forInboundConsumer(apiServiceDescriptor, KEY_B, CODER, inboundValuesB::add);
// Show that out of order stream completion can occur.
readFutureB.get();
assertThat(inboundValuesB, contains(valueInGlobalWindow("JKL"), valueInGlobalWindow("MNO")));
outboundServerObserver.get().onNext(ELEMENTS_A_2);
readFutureA.get();
assertThat(inboundValuesA, contains(valueInGlobalWindow("ABC"), valueInGlobalWindow("DEF"), valueInGlobalWindow("GHI")));
} finally {
server.shutdownNow();
}
}
use of io.grpc.stub.StreamObserver in project beam by apache.
the class PubsubGrpcClientTest method pullOneMessage.
@Test
public void pullOneMessage() throws IOException {
String expectedSubscription = SUBSCRIPTION.getPath();
final PullRequest expectedRequest = PullRequest.newBuilder().setSubscription(expectedSubscription).setReturnImmediately(true).setMaxMessages(10).build();
Timestamp timestamp = Timestamp.newBuilder().setSeconds(PUB_TIME / 1000).setNanos((int) (PUB_TIME % 1000) * 1000).build();
PubsubMessage expectedPubsubMessage = PubsubMessage.newBuilder().setMessageId(MESSAGE_ID).setData(ByteString.copyFrom(DATA.getBytes())).setPublishTime(timestamp).putAllAttributes(ATTRIBUTES).putAllAttributes(ImmutableMap.of(TIMESTAMP_ATTRIBUTE, String.valueOf(MESSAGE_TIME), ID_ATTRIBUTE, RECORD_ID)).build();
ReceivedMessage expectedReceivedMessage = ReceivedMessage.newBuilder().setMessage(expectedPubsubMessage).setAckId(ACK_ID).build();
final PullResponse response = PullResponse.newBuilder().addAllReceivedMessages(ImmutableList.of(expectedReceivedMessage)).build();
final List<PullRequest> requestsReceived = new ArrayList<>();
SubscriberImplBase subscriberImplBase = new SubscriberImplBase() {
@Override
public void pull(PullRequest request, StreamObserver<PullResponse> responseObserver) {
requestsReceived.add(request);
responseObserver.onNext(response);
responseObserver.onCompleted();
}
};
Server server = InProcessServerBuilder.forName(channelName).addService(subscriberImplBase).build().start();
try {
List<IncomingMessage> acutalMessages = client.pull(REQ_TIME, SUBSCRIPTION, 10, true);
assertEquals(1, acutalMessages.size());
IncomingMessage actualMessage = acutalMessages.get(0);
assertEquals(ACK_ID, actualMessage.ackId);
assertEquals(DATA, new String(actualMessage.elementBytes));
assertEquals(RECORD_ID, actualMessage.recordId);
assertEquals(REQ_TIME, actualMessage.requestTimeMsSinceEpoch);
assertEquals(MESSAGE_TIME, actualMessage.timestampMsSinceEpoch);
assertEquals(expectedRequest, Iterables.getOnlyElement(requestsReceived));
} finally {
server.shutdownNow();
}
}
Aggregations