use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.CallOptions in project etcd-java by IBM.
the class GrpcClient method call.
// deadline is for entire request (including retry pauses),
// timeout is per-attempt and 0 means not specified
private <ReqT, R> ListenableFuture<R> call(MethodDescriptor<ReqT, R> method, Condition precondition, ReqT request, RetryDecision<ReqT> retry, int attempt, boolean backoff, Deadline deadline, long timeoutMs) {
if (precondition != null && !precondition.satisfied()) {
return Futures.immediateFailedFuture(new CancellationException("precondition false"));
}
// TODO(maybe) in delay case (attempt > 1), if "session" is inactive,
// skip attempt (and dont increment attempt #)
final CallOptions baseCallOpts = getCallOptions();
CallOptions callOpts = deadline != null ? baseCallOpts.withDeadline(deadline) : baseCallOpts;
return Futures.catchingAsync(fuCall(method, request, callOpts, timeoutMs), Exception.class, t -> {
boolean reauth;
if ((!backoff && attempt > 0) || (!(reauth = reauthIfRequired(t, baseCallOpts)) && !retry.retry(t, request)))
return Futures.immediateFailedFuture(t);
if (attempt == 0 || reauth)
return call(method, precondition, request, retry, reauth ? attempt : 1, backoff, deadline, timeoutMs);
// TODO review backoff pattern
long delay = 500L * (1L << Math.min(attempt - 2, 4));
return Futures.dereference(ses.schedule(() -> call(method, precondition, request, retry, attempt + 1, backoff, deadline, timeoutMs), delay, MILLISECONDS));
});
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.CallOptions in project pravega by pravega.
the class RPCTracingHelpersTest method testInterceptors.
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testInterceptors() {
String requestDescriptor = "createStream-myScope-myStream";
long requestId = 1234L;
ClientInterceptor clientInterceptor = RPCTracingHelpers.getClientInterceptor();
RequestTracker requestTracker = new RequestTracker(true);
// Mocking RPC elements.
MethodDescriptor.Marshaller<Object> mockMarshaller = Mockito.mock(MethodDescriptor.Marshaller.class);
ClientCall.Listener<Object> listener = Mockito.mock(ClientCall.Listener.class);
ServerCall serverCall = Mockito.mock(ServerCall.class);
ServerCallHandler serverCallHandler = Mockito.mock(ServerCallHandler.class);
@Cleanup("shutdown") ManagedChannel channel = NettyChannelBuilder.forTarget("localhost").build();
MethodDescriptor method = MethodDescriptor.newBuilder().setFullMethodName("createStream").setType(MethodDescriptor.MethodType.UNARY).setRequestMarshaller(mockMarshaller).setResponseMarshaller(mockMarshaller).build();
Mockito.when(serverCall.getMethodDescriptor()).thenReturn(method);
// Actual elements to work with.
CallOptions callOptions = CallOptions.DEFAULT;
Metadata headers = new Metadata();
// Test that headers do not contain tracing-related key/values, as call options are not set.
clientInterceptor.interceptCall(method, callOptions, channel).start(listener, headers);
assertFalse(headers.containsKey(RPCTracingHelpers.DESCRIPTOR_HEADER));
assertFalse(headers.containsKey(RPCTracingHelpers.ID_HEADER));
// Check that the server interceptor handles clients not sending tracing headers and that the cache remains clean.
ServerInterceptor serverInterceptor = RPCTracingHelpers.getServerInterceptor(requestTracker);
serverInterceptor.interceptCall(serverCall, headers, serverCallHandler);
assertEquals(0, requestTracker.getNumDescriptors());
// Add call options and check that headers are correctly set.
callOptions = callOptions.withOption(RPCTracingHelpers.REQUEST_DESCRIPTOR_CALL_OPTION, requestDescriptor).withOption(RPCTracingHelpers.REQUEST_ID_CALL_OPTION, String.valueOf(requestId));
clientInterceptor.interceptCall(method, callOptions, channel).start(listener, headers);
assertEquals(requestDescriptor, headers.get(RPCTracingHelpers.DESCRIPTOR_HEADER));
assertEquals(requestId, Long.parseLong(headers.get(RPCTracingHelpers.ID_HEADER)));
// Test that the server interceptor correctly sets these headers in the cache for further tracking.
serverInterceptor.interceptCall(serverCall, headers, serverCallHandler);
assertEquals(1, requestTracker.getNumDescriptors());
assertEquals(requestId, requestTracker.getRequestIdFor(requestDescriptor));
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.CallOptions in project jetcd by coreos.
the class ClientConnectionManager method defaultChannelBuilder.
@SuppressWarnings("rawtypes")
ManagedChannelBuilder<?> defaultChannelBuilder(String target) {
if (target == null) {
throw new IllegalArgumentException("At least one endpoint should be provided");
}
final Vertx vertx = Vertx.vertx();
final VertxChannelBuilder channelBuilder = VertxChannelBuilder.forTarget(vertx, target);
if (builder.authority() != null) {
channelBuilder.overrideAuthority(builder.authority());
}
if (builder.maxInboundMessageSize() != null) {
channelBuilder.maxInboundMessageSize(builder.maxInboundMessageSize());
}
if (builder.sslContext() != null) {
channelBuilder.nettyBuilder().negotiationType(NegotiationType.TLS);
channelBuilder.nettyBuilder().sslContext(builder.sslContext());
} else {
channelBuilder.nettyBuilder().negotiationType(NegotiationType.PLAINTEXT);
}
if (builder.keepaliveTime() != null) {
channelBuilder.keepAliveTime(builder.keepaliveTime().toMillis(), TimeUnit.MILLISECONDS);
}
if (builder.keepaliveTimeout() != null) {
channelBuilder.keepAliveTimeout(builder.keepaliveTimeout().toMillis(), TimeUnit.MILLISECONDS);
}
if (builder.keepaliveWithoutCalls() != null) {
channelBuilder.keepAliveWithoutCalls(builder.keepaliveWithoutCalls());
}
if (builder.connectTimeout() != null) {
channelBuilder.nettyBuilder().withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) builder.connectTimeout().toMillis());
}
if (builder.loadBalancerPolicy() != null) {
channelBuilder.defaultLoadBalancingPolicy(builder.loadBalancerPolicy());
} else {
channelBuilder.defaultLoadBalancingPolicy("pick_first");
}
if (builder.headers() != null) {
channelBuilder.intercept(new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
builder.headers().forEach((BiConsumer<Metadata.Key, Object>) headers::put);
super.start(responseListener, headers);
}
};
}
});
}
if (builder.interceptors() != null) {
channelBuilder.intercept(builder.interceptors());
}
return channelBuilder;
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.CallOptions in project grpc-java by grpc.
the class ManagedChannelImplTest method subchannelChannel_normalUsage.
@Test
public void subchannelChannel_normalUsage() {
createChannel();
Subchannel subchannel = createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
verify(balancerRpcExecutorPool, never()).getObject();
Channel sChannel = subchannel.asChannel();
verify(balancerRpcExecutorPool).getObject();
Metadata headers = new Metadata();
CallOptions callOptions = CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS);
// Subchannel must be READY when creating the RPC.
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;
transportListener.transportReady();
ClientCall<String, Integer> call = sChannel.newCall(method, callOptions);
call.start(mockCallListener, headers);
verify(mockTransport).newStream(same(method), same(headers), callOptionsCaptor.capture(), ArgumentMatchers.<ClientStreamTracer[]>any());
CallOptions capturedCallOption = callOptionsCaptor.getValue();
assertThat(capturedCallOption.getDeadline()).isSameInstanceAs(callOptions.getDeadline());
assertThat(capturedCallOption.getOption(GrpcUtil.CALL_OPTIONS_RPC_OWNED_BY_BALANCER)).isTrue();
}
use of org.apache.beam.vendor.grpc.v1p43p2.io.grpc.CallOptions in project grpc-java by grpc.
the class ManagedChannelImplTest method oobChannelWithOobChannelCredsHasChannelCallCredentials.
@Test
public void oobChannelWithOobChannelCredsHasChannelCallCredentials() {
Metadata.Key<String> metadataKey = Metadata.Key.of("token", Metadata.ASCII_STRING_MARSHALLER);
String channelCredValue = "channel-provided call cred";
when(mockTransportFactory.swapChannelCredentials(any(CompositeChannelCredentials.class))).thenAnswer(new Answer<SwapChannelCredentialsResult>() {
@Override
public SwapChannelCredentialsResult answer(InvocationOnMock invocation) {
CompositeChannelCredentials c = invocation.getArgument(0, CompositeChannelCredentials.class);
return new SwapChannelCredentialsResult(mockTransportFactory, c.getCallCredentials());
}
});
channelBuilder = new ManagedChannelImplBuilder(TARGET, InsecureChannelCredentials.create(), new FakeCallCredentials(metadataKey, channelCredValue), new UnsupportedClientTransportFactoryBuilder(), new FixedPortProvider(DEFAULT_PORT));
channelBuilder.disableRetry();
configureBuilder(channelBuilder);
createChannel();
// Verify that the normal channel has call creds, to validate configuration
Subchannel subchannel = createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
requestConnectionSafely(helper, subchannel);
MockClientTransportInfo transportInfo = transports.poll();
transportInfo.listener.transportReady();
when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
updateBalancingStateSafely(helper, READY, mockPicker);
String callCredValue = "per-RPC call cred";
CallOptions callOptions = CallOptions.DEFAULT.withCallCredentials(new FakeCallCredentials(metadataKey, callCredValue));
Metadata headers = new Metadata();
ClientCall<String, Integer> call = channel.newCall(method, callOptions);
call.start(mockCallListener, headers);
verify(transportInfo.transport).newStream(same(method), same(headers), same(callOptions), ArgumentMatchers.<ClientStreamTracer[]>any());
assertThat(headers.getAll(metadataKey)).containsExactly(channelCredValue, callCredValue).inOrder();
// Verify that resolving oob channel with oob channel creds provides call creds
String oobChannelCredValue = "oob-channel-provided call cred";
ChannelCredentials oobChannelCreds = CompositeChannelCredentials.create(InsecureChannelCredentials.create(), new FakeCallCredentials(metadataKey, oobChannelCredValue));
ManagedChannel oob = helper.createResolvingOobChannelBuilder("fake://oobauthority/", oobChannelCreds).nameResolverFactory(new FakeNameResolverFactory.Builder(URI.create("fake://oobauthority/")).build()).defaultLoadBalancingPolicy(MOCK_POLICY_NAME).idleTimeout(ManagedChannelImplBuilder.IDLE_MODE_MAX_TIMEOUT_DAYS, TimeUnit.DAYS).disableRetry().build();
oob.getState(true);
ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(Helper.class);
verify(mockLoadBalancerProvider, times(2)).newLoadBalancer(helperCaptor.capture());
Helper oobHelper = helperCaptor.getValue();
subchannel = createSubchannelSafely(oobHelper, addressGroup, Attributes.EMPTY, subchannelStateListener);
requestConnectionSafely(oobHelper, subchannel);
transportInfo = transports.poll();
transportInfo.listener.transportReady();
SubchannelPicker mockPicker2 = mock(SubchannelPicker.class);
when(mockPicker2.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
updateBalancingStateSafely(oobHelper, READY, mockPicker2);
headers = new Metadata();
call = oob.newCall(method, callOptions);
call.start(mockCallListener2, headers);
// CallOptions may contain StreamTracerFactory for census that is added by default.
verify(transportInfo.transport).newStream(same(method), same(headers), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any());
assertThat(headers.getAll(metadataKey)).containsExactly(oobChannelCredValue, callCredValue).inOrder();
oob.shutdownNow();
}
Aggregations