use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project grpc-java by grpc.
the class BinlogHelperTest method clientInterceptor.
@Test
public void clientInterceptor() throws Exception {
final AtomicReference<ClientCall.Listener<byte[]>> interceptedListener = new AtomicReference<>();
// capture these manually because ClientCall can not be mocked
final AtomicReference<Metadata> actualClientInitial = new AtomicReference<>();
final AtomicReference<Object> actualRequest = new AtomicReference<>();
final SettableFuture<Void> halfCloseCalled = SettableFuture.create();
final SettableFuture<Void> cancelCalled = SettableFuture.create();
Channel channel = new Channel() {
@Override
public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
return new NoopClientCall<RequestT, ResponseT>() {
@Override
@SuppressWarnings("unchecked")
public void start(Listener<ResponseT> responseListener, Metadata headers) {
interceptedListener.set((Listener<byte[]>) responseListener);
actualClientInitial.set(headers);
}
@Override
public void sendMessage(RequestT message) {
actualRequest.set(message);
}
@Override
public void cancel(String message, Throwable cause) {
cancelCalled.set(null);
}
@Override
public void halfClose() {
halfCloseCalled.set(null);
}
@Override
public Attributes getAttributes() {
return Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, peer).build();
}
};
}
@Override
public String authority() {
return "the-authority";
}
};
@SuppressWarnings("unchecked") ClientCall.Listener<byte[]> mockListener = mock(ClientCall.Listener.class);
MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("service/method").setRequestMarshaller(BYTEARRAY_MARSHALLER).setResponseMarshaller(BYTEARRAY_MARSHALLER).build();
ClientCall<byte[], byte[]> interceptedCall = new BinlogHelper(mockSinkWriter).getClientInterceptor(CALL_ID).interceptCall(method, CallOptions.DEFAULT, channel);
// send client header
{
Metadata clientInitial = new Metadata();
interceptedCall.start(mockListener, clientInitial);
verify(mockSinkWriter).logClientHeader(/*seq=*/
eq(1L), eq("service/method"), eq("the-authority"), ArgumentMatchers.<Duration>isNull(), same(clientInitial), eq(Logger.LOGGER_CLIENT), eq(CALL_ID), ArgumentMatchers.<SocketAddress>isNull());
verifyNoMoreInteractions(mockSinkWriter);
assertSame(clientInitial, actualClientInitial.get());
}
// receive server header
{
Metadata serverInitial = new Metadata();
interceptedListener.get().onHeaders(serverInitial);
verify(mockSinkWriter).logServerHeader(/*seq=*/
eq(2L), same(serverInitial), eq(Logger.LOGGER_CLIENT), eq(CALL_ID), same(peer));
verifyNoMoreInteractions(mockSinkWriter);
verify(mockListener).onHeaders(same(serverInitial));
}
// send client msg
{
byte[] request = "this is a request".getBytes(US_ASCII);
interceptedCall.sendMessage(request);
verify(mockSinkWriter).logRpcMessage(/*seq=*/
eq(3L), eq(EventType.EVENT_TYPE_CLIENT_MESSAGE), same(BYTEARRAY_MARSHALLER), same(request), eq(Logger.LOGGER_CLIENT), eq(CALL_ID));
verifyNoMoreInteractions(mockSinkWriter);
assertSame(request, actualRequest.get());
}
// client half close
{
interceptedCall.halfClose();
verify(mockSinkWriter).logHalfClose(/*seq=*/
eq(4L), eq(Logger.LOGGER_CLIENT), eq(CALL_ID));
halfCloseCalled.get(1, TimeUnit.SECONDS);
verifyNoMoreInteractions(mockSinkWriter);
}
// receive server msg
{
byte[] response = "this is a response".getBytes(US_ASCII);
interceptedListener.get().onMessage(response);
verify(mockSinkWriter).logRpcMessage(/*seq=*/
eq(5L), eq(EventType.EVENT_TYPE_SERVER_MESSAGE), same(BYTEARRAY_MARSHALLER), same(response), eq(Logger.LOGGER_CLIENT), eq(CALL_ID));
verifyNoMoreInteractions(mockSinkWriter);
verify(mockListener).onMessage(same(response));
}
// receive trailer
{
Status status = Status.INTERNAL.withDescription("some description");
Metadata trailers = new Metadata();
interceptedListener.get().onClose(status, trailers);
verify(mockSinkWriter).logTrailer(/*seq=*/
eq(6L), same(status), same(trailers), eq(Logger.LOGGER_CLIENT), eq(CALL_ID), ArgumentMatchers.<SocketAddress>isNull());
verifyNoMoreInteractions(mockSinkWriter);
verify(mockListener).onClose(same(status), same(trailers));
}
// cancel
{
interceptedCall.cancel(null, null);
verify(mockSinkWriter).logCancel(/*seq=*/
eq(7L), eq(Logger.LOGGER_CLIENT), eq(CALL_ID));
cancelCalled.get(1, TimeUnit.SECONDS);
}
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project grpc-java by grpc.
the class BinlogHelperTest method serverInterceptor.
@Test
public void serverInterceptor() throws Exception {
final AtomicReference<ServerCall<byte[], byte[]>> interceptedCall = new AtomicReference<>();
ServerCall.Listener<byte[]> capturedListener;
@SuppressWarnings("unchecked") final ServerCall.Listener<byte[]> mockListener = mock(ServerCall.Listener.class);
// capture these manually because ServerCall can not be mocked
final AtomicReference<Metadata> actualServerInitial = new AtomicReference<>();
final AtomicReference<byte[]> actualResponse = new AtomicReference<>();
final AtomicReference<Status> actualStatus = new AtomicReference<>();
final AtomicReference<Metadata> actualTrailers = new AtomicReference<>();
// begin call and receive client header
{
Metadata clientInitial = new Metadata();
final MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("service/method").setRequestMarshaller(BYTEARRAY_MARSHALLER).setResponseMarshaller(BYTEARRAY_MARSHALLER).build();
capturedListener = new BinlogHelper(mockSinkWriter).getServerInterceptor(CALL_ID).interceptCall(new NoopServerCall<byte[], byte[]>() {
@Override
public void sendHeaders(Metadata headers) {
actualServerInitial.set(headers);
}
@Override
public void sendMessage(byte[] message) {
actualResponse.set(message);
}
@Override
public void close(Status status, Metadata trailers) {
actualStatus.set(status);
actualTrailers.set(trailers);
}
@Override
public MethodDescriptor<byte[], byte[]> getMethodDescriptor() {
return method;
}
@Override
public Attributes getAttributes() {
return Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, peer).build();
}
@Override
public String getAuthority() {
return "the-authority";
}
}, clientInitial, new ServerCallHandler<byte[], byte[]>() {
@Override
public ServerCall.Listener<byte[]> startCall(ServerCall<byte[], byte[]> call, Metadata headers) {
interceptedCall.set(call);
return mockListener;
}
});
verify(mockSinkWriter).logClientHeader(/*seq=*/
eq(1L), eq("service/method"), eq("the-authority"), ArgumentMatchers.<Duration>isNull(), same(clientInitial), eq(Logger.LOGGER_SERVER), eq(CALL_ID), same(peer));
verifyNoMoreInteractions(mockSinkWriter);
}
// send server header
{
Metadata serverInital = new Metadata();
interceptedCall.get().sendHeaders(serverInital);
verify(mockSinkWriter).logServerHeader(/*seq=*/
eq(2L), same(serverInital), eq(Logger.LOGGER_SERVER), eq(CALL_ID), ArgumentMatchers.<SocketAddress>isNull());
verifyNoMoreInteractions(mockSinkWriter);
assertSame(serverInital, actualServerInitial.get());
}
// receive client msg
{
byte[] request = "this is a request".getBytes(US_ASCII);
capturedListener.onMessage(request);
verify(mockSinkWriter).logRpcMessage(/*seq=*/
eq(3L), eq(EventType.EVENT_TYPE_CLIENT_MESSAGE), same(BYTEARRAY_MARSHALLER), same(request), eq(Logger.LOGGER_SERVER), eq(CALL_ID));
verifyNoMoreInteractions(mockSinkWriter);
verify(mockListener).onMessage(same(request));
}
// client half close
{
capturedListener.onHalfClose();
verify(mockSinkWriter).logHalfClose(eq(4L), eq(Logger.LOGGER_SERVER), eq(CALL_ID));
verifyNoMoreInteractions(mockSinkWriter);
verify(mockListener).onHalfClose();
}
// send server msg
{
byte[] response = "this is a response".getBytes(US_ASCII);
interceptedCall.get().sendMessage(response);
verify(mockSinkWriter).logRpcMessage(/*seq=*/
eq(5L), eq(EventType.EVENT_TYPE_SERVER_MESSAGE), same(BYTEARRAY_MARSHALLER), same(response), eq(Logger.LOGGER_SERVER), eq(CALL_ID));
verifyNoMoreInteractions(mockSinkWriter);
assertSame(response, actualResponse.get());
}
// send trailer
{
Status status = Status.INTERNAL.withDescription("some description");
Metadata trailers = new Metadata();
interceptedCall.get().close(status, trailers);
verify(mockSinkWriter).logTrailer(/*seq=*/
eq(6L), same(status), same(trailers), eq(Logger.LOGGER_SERVER), eq(CALL_ID), ArgumentMatchers.<SocketAddress>isNull());
verifyNoMoreInteractions(mockSinkWriter);
assertSame(status, actualStatus.get());
assertSame(trailers, actualTrailers.get());
}
// cancel
{
capturedListener.onCancel();
verify(mockSinkWriter).logCancel(/*seq=*/
eq(7L), eq(Logger.LOGGER_SERVER), eq(CALL_ID));
verify(mockListener).onCancel();
}
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project grpc-java by grpc.
the class ManagedChannelImplTest method newCallWithConfigSelector.
@Test
public void newCallWithConfigSelector() {
FakeNameResolverFactory nameResolverFactory = new FakeNameResolverFactory.Builder(expectedUri).setServers(ImmutableList.of(addressGroup)).build();
channelBuilder.nameResolverFactory(nameResolverFactory);
channel = new ManagedChannelImpl(channelBuilder, mockTransportFactory, new FakeBackoffPolicyProvider(), balancerRpcExecutorPool, timer.getStopwatchSupplier(), Collections.<ClientInterceptor>emptyList(), timer.getTimeProvider());
nameResolverFactory.nextConfigOrError.set(ConfigOrError.fromConfig(ManagedChannelServiceConfig.empty()));
final Metadata.Key<String> metadataKey = Metadata.Key.of("test", Metadata.ASCII_STRING_MARSHALLER);
final CallOptions.Key<String> callOptionsKey = CallOptions.Key.create("test");
InternalConfigSelector configSelector = new InternalConfigSelector() {
@Override
public Result selectConfig(final PickSubchannelArgs args) {
return Result.newBuilder().setConfig(ManagedChannelServiceConfig.empty()).setInterceptor(// An interceptor that mutates CallOptions based on headers value.
new ClientInterceptor() {
String value = args.getHeaders().get(metadataKey);
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
callOptions = callOptions.withOption(callOptionsKey, value);
return next.newCall(method, callOptions);
}
}).build();
}
};
nameResolverFactory.nextAttributes.set(Attributes.newBuilder().set(InternalConfigSelector.KEY, configSelector).build());
channel.getState(true);
Metadata headers = new Metadata();
headers.put(metadataKey, "fooValue");
ClientStream mockStream = mock(ClientStream.class);
ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
call.start(mockCallListener, headers);
ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
verify(mockLoadBalancerProvider).newLoadBalancer(helperCaptor.capture());
helper = helperCaptor.getValue();
// Make the transport available
Subchannel subchannel = createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
requestConnectionSafely(helper, subchannel);
verify(mockTransportFactory).newClientTransport(any(SocketAddress.class), any(ClientTransportOptions.class), any(ChannelLogger.class));
MockClientTransportInfo transportInfo = transports.poll();
ConnectionClientTransport mockTransport = transportInfo.transport;
ManagedClientTransport.Listener transportListener = transportInfo.listener;
when(mockTransport.newStream(same(method), same(headers), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any())).thenReturn(mockStream);
transportListener.transportReady();
when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
updateBalancingStateSafely(helper, READY, mockPicker);
executor.runDueTasks();
ArgumentCaptor<CallOptions> callOptionsCaptor = ArgumentCaptor.forClass(null);
verify(mockTransport).newStream(same(method), same(headers), callOptionsCaptor.capture(), ArgumentMatchers.<ClientStreamTracer[]>any());
assertThat(callOptionsCaptor.getValue().getOption(callOptionsKey)).isEqualTo("fooValue");
verify(mockStream).start(streamListenerCaptor.capture());
// Clean up as much as possible to allow the channel to terminate.
shutdownSafely(helper, subchannel);
timer.forwardNanos(TimeUnit.SECONDS.toNanos(ManagedChannelImpl.SUBCHANNEL_SHUTDOWN_DELAY_SECONDS));
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project grpc-java by grpc.
the class ManagedChannelImplTest method informationPropagatedToNewStreamAndCallCredentials.
/**
* Test that information such as the Call's context, MethodDescriptor, authority, executor are
* propagated to newStream() and applyRequestMetadata().
*/
@Test
public void informationPropagatedToNewStreamAndCallCredentials() {
createChannel();
CallOptions callOptions = CallOptions.DEFAULT.withCallCredentials(creds);
final Context.Key<String> testKey = Context.key("testing");
Context ctx = Context.current().withValue(testKey, "testValue");
final LinkedList<Context> credsApplyContexts = new LinkedList<>();
final LinkedList<Context> newStreamContexts = new LinkedList<>();
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
credsApplyContexts.add(Context.current());
return null;
}
}).when(creds).applyRequestMetadata(any(RequestInfo.class), any(Executor.class), any(CallCredentials.MetadataApplier.class));
// First call will be on delayed transport. Only newCall() is run within the expected context,
// so that we can verify that the context is explicitly attached before calling newStream() and
// applyRequestMetadata(), which happens after we detach the context from the thread.
Context origCtx = ctx.attach();
assertEquals("testValue", testKey.get());
ClientCall<String, Integer> call = channel.newCall(method, callOptions);
ctx.detach(origCtx);
assertNull(testKey.get());
call.start(mockCallListener, new Metadata());
// Simulate name resolution results
EquivalentAddressGroup addressGroup = new EquivalentAddressGroup(socketAddress);
Subchannel subchannel = createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
requestConnectionSafely(helper, subchannel);
verify(mockTransportFactory).newClientTransport(same(socketAddress), eq(clientTransportOptions), any(ChannelLogger.class));
MockClientTransportInfo transportInfo = transports.poll();
final ConnectionClientTransport transport = transportInfo.transport;
when(transport.getAttributes()).thenReturn(Attributes.EMPTY);
doAnswer(new Answer<ClientStream>() {
@Override
public ClientStream answer(InvocationOnMock in) throws Throwable {
newStreamContexts.add(Context.current());
return mock(ClientStream.class);
}
}).when(transport).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any());
verify(creds, never()).applyRequestMetadata(any(RequestInfo.class), any(Executor.class), any(CallCredentials.MetadataApplier.class));
// applyRequestMetadata() is called after the transport becomes ready.
transportInfo.listener.transportReady();
when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
updateBalancingStateSafely(helper, READY, mockPicker);
executor.runDueTasks();
ArgumentCaptor<RequestInfo> infoCaptor = ArgumentCaptor.forClass(null);
ArgumentCaptor<CallCredentials.MetadataApplier> applierCaptor = ArgumentCaptor.forClass(null);
verify(creds).applyRequestMetadata(infoCaptor.capture(), same(executor.getScheduledExecutorService()), applierCaptor.capture());
assertEquals("testValue", testKey.get(credsApplyContexts.poll()));
assertEquals(AUTHORITY, infoCaptor.getValue().getAuthority());
assertEquals(SecurityLevel.NONE, infoCaptor.getValue().getSecurityLevel());
verify(transport, never()).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any());
// newStream() is called after apply() is called
applierCaptor.getValue().apply(new Metadata());
verify(transport).newStream(same(method), any(Metadata.class), same(callOptions), ArgumentMatchers.<ClientStreamTracer[]>any());
assertEquals("testValue", testKey.get(newStreamContexts.poll()));
// The context should not live beyond the scope of newStream() and applyRequestMetadata()
assertNull(testKey.get());
// Second call will not be on delayed transport
origCtx = ctx.attach();
call = channel.newCall(method, callOptions);
ctx.detach(origCtx);
call.start(mockCallListener, new Metadata());
verify(creds, times(2)).applyRequestMetadata(infoCaptor.capture(), same(executor.getScheduledExecutorService()), applierCaptor.capture());
assertEquals("testValue", testKey.get(credsApplyContexts.poll()));
assertEquals(AUTHORITY, infoCaptor.getValue().getAuthority());
assertEquals(SecurityLevel.NONE, infoCaptor.getValue().getSecurityLevel());
// This is from the first call
verify(transport).newStream(any(MethodDescriptor.class), any(Metadata.class), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any());
// Still, newStream() is called after apply() is called
applierCaptor.getValue().apply(new Metadata());
verify(transport, times(2)).newStream(same(method), any(Metadata.class), same(callOptions), ArgumentMatchers.<ClientStreamTracer[]>any());
assertEquals("testValue", testKey.get(newStreamContexts.poll()));
assertNull(testKey.get());
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.MethodDescriptor in project grpc-java by grpc.
the class ManagedChannelImplTest method binaryLogInstalled.
@Test
public void binaryLogInstalled() throws Exception {
final SettableFuture<Boolean> intercepted = SettableFuture.create();
channelBuilder.binlog = new BinaryLog() {
@Override
public void close() throws IOException {
// noop
}
@Override
public <ReqT, RespT> ServerMethodDefinition<?, ?> wrapMethodDefinition(ServerMethodDefinition<ReqT, RespT> oMethodDef) {
return oMethodDef;
}
@Override
public Channel wrapChannel(Channel channel) {
return ClientInterceptors.intercept(channel, new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
intercepted.set(true);
return next.newCall(method, callOptions);
}
});
}
};
createChannel();
ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
call.start(mockCallListener, new Metadata());
assertTrue(intercepted.get());
}
Aggregations