Refine search
@Test public void messageReadAfterClose_byteBuf() { call.close(Status.ABORTED, new Metadata()); // messageRead is always called from the event loop. eventLoop.get().submit(() -> { call.messageRead(new ByteBufOrStream(GrpcTestUtil.requestByteBuf())); verify(listener, never()).onMessage(any()); }).syncUninterruptibly(); }
switch (Status.fromThrowable(e).getCode()) { case ABORTED: alluxioStatus = alluxio.exception.status.Status.ABORTED; if (e.getTrailers() != null && e.getTrailers().containsKey(sInnerCauseKey)) { try { cause = (Throwable) SerializationUtils.deserialize(e.getTrailers().get(sInnerCauseKey)); } catch (Exception exc) { LOG.warn("Failed to deserialize the cause: {}", exc);
Metadata newMetadata(String resourceTokenTemplate, String defaultResourceToken) { Metadata metadata = new Metadata(); for (Map.Entry<Metadata.Key<String>, String> header : headers.entrySet()) { metadata.put(header.getKey(), header.getValue()); } metadata.put( Key.of(resourceHeaderKey, Metadata.ASCII_STRING_MARSHALLER), getResourceHeaderValue(resourceTokenTemplate, defaultResourceToken)); return metadata; }
static long extractRetryDelay(Throwable cause) { if (cause != null) { Metadata trailers = Status.trailersFromThrowable(cause); if (trailers != null && trailers.containsKey(KEY_RETRY_INFO)) { RetryInfo retryInfo = trailers.get(KEY_RETRY_INFO); if (retryInfo.hasRetryDelay()) { return Durations.toMillis(retryInfo.getRetryDelay()); } } } return -1L; } }
private DefaultRequest getBaseMotanRequest(Metadata headers) { DefaultRequest request = new DefaultRequest(); request.setMethodName(methodName); request.setParamtersDesc(paramsDesc); request.setInterfaceName(provider.getInterface().getName()); String rid = headers.get(REQUEST_ID); if (rid == null) { rid = headers.get(Metadata.Key.of(URLParamType.requestIdFromClient.getName().toLowerCase(), Metadata.ASCII_STRING_MARSHALLER)); } if (rid != null) { request.setAttachment(URLParamType.requestIdFromClient.getName(), rid); } // fill attachment info from headers Set<String> keys = headers.keys(); for (String key : keys) { String value = headers.get(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER)); if (value != null) { request.setAttachment(key, value); } } return request; }
@Test public void testTimeoutToDeadlineConversion() { MethodDescriptor<Color, Money> descriptor = FakeServiceGrpc.METHOD_RECOGNIZE; @SuppressWarnings("unchecked") ClientCall<Color, Money> mockClientCall = Mockito.mock(ClientCall.class); @SuppressWarnings("unchecked") ClientCall.Listener<Money> mockListener = Mockito.mock(ClientCall.Listener.class); @SuppressWarnings("unchecked") Channel mockChannel = Mockito.mock(ManagedChannel.class); ArgumentCaptor<CallOptions> capturedCallOptions = ArgumentCaptor.forClass(CallOptions.class); Mockito.when(mockChannel.newCall(Mockito.eq(descriptor), capturedCallOptions.capture())) .thenReturn(mockClientCall); Duration timeout = Duration.ofSeconds(10); Deadline minExpectedDeadline = Deadline.after(timeout.getSeconds(), TimeUnit.SECONDS); GrpcCallContext context = GrpcCallContext.createDefault().withChannel(mockChannel).withTimeout(timeout); GrpcClientCalls.newCall(descriptor, context).start(mockListener, new Metadata()); Deadline maxExpectedDeadline = Deadline.after(timeout.getSeconds(), TimeUnit.SECONDS); Truth.assertThat(capturedCallOptions.getValue().getDeadline()).isAtLeast(minExpectedDeadline); Truth.assertThat(capturedCallOptions.getValue().getDeadline()).isAtMost(maxExpectedDeadline); }
@Test public void testExtraHeaders() { Metadata emptyHeaders = new Metadata(); final Map<String, List<String>> extraHeaders = new HashMap<>(); extraHeaders.put( ClientCall<Color, Money> mockClientCall = Mockito.mock(ClientCall.class); ClientCall.Listener<Money> mockListener = Mockito.mock(ClientCall.Listener.class); Channel mockChannel = Mockito.mock(ManagedChannel.class); Mockito.doAnswer(
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); ManagedChannel channel = NettyChannelBuilder.forTarget("localhost").build(); Metadata headers = new Metadata(); assertFalse(headers.containsKey(RPCTracingHelpers.DESCRIPTOR_HEADER)); assertFalse(headers.containsKey(RPCTracingHelpers.ID_HEADER)); .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 public void testInterceptor() { Map<String, String> data = Collections.singletonMap("x-goog-api-client", "abcd"); GrpcHeaderInterceptor interceptor = new GrpcHeaderInterceptor(data); Channel intercepted = ClientInterceptors.intercept(channel, interceptor); @SuppressWarnings("unchecked") ClientCall.Listener<Integer> listener = mock(ClientCall.Listener.class); ClientCall<String, Integer> interceptedCall = intercepted.newCall(method, CallOptions.DEFAULT); // start() on the intercepted call will eventually reach the call created by the real channel interceptedCall.start(listener, new Metadata()); // The headers passed to the real channel call will contain the information inserted by the // interceptor. ArgumentCaptor<Metadata> captor = ArgumentCaptor.forClass(Metadata.class); verify(call).start(same(listener), captor.capture()); final Metadata.Key<String> headerKey = Metadata.Key.of("x-goog-api-client", Metadata.ASCII_STRING_MARSHALLER); assertEquals("abcd", captor.getValue().get(headerKey)); } }
Channel intercepted = ClientInterceptors.intercept(channel, interceptor); @SuppressWarnings("unchecked") ClientCall.Listener<Integer> listener = mock(ClientCall.Listener.class); interceptedCall.start(listener, new Metadata()); ArgumentCaptor<ClientCall.Listener> captor = ArgumentCaptor.forClass(ClientCall.Listener.class); ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class); verify(call).start(captor.capture(), metadataCaptor.capture()); assertFalse(trailingMetadataHandlerCalled.value); captor.getValue().onHeaders(new Metadata()); assertFalse(trailingMetadataHandlerCalled.value); captor.getValue().onClose(Status.fromCodeValue(0), new Metadata());
/** * Close the call with {@link Status#PERMISSION_DENIED}. * * @param call The call to close. * @param aex The exception that was the cause. */ protected void closeCallAccessDenied(final ServerCall<?, ?> call, final AccessDeniedException aex) { call.close(Status.PERMISSION_DENIED.withCause(aex).withDescription(ACCESS_DENIED_DESCRIPTION), new Metadata()); }
Metadata metadata = new Metadata(); metadata.put(STATUS_DETAILS_KEY, DebugInfo.newBuilder() .addAllStackEntries(Arrays.asList(frames)) .withDescription(t.getMessage()) .withCause(t) .asException(metadata);
public static GrpcError throwableToStatus(Throwable t) { Status status = Status.fromThrowable(t); if (t instanceof InvalidProtocolBufferException) { status = Status.INVALID_ARGUMENT.withCause(t); } Metadata trailer = Status.trailersFromThrowable(t); int statusCode = grpcToHttpStatus(status); com.google.rpc.Status.Builder payload = com.google.rpc.Status.newBuilder(); payload.setCode(status.getCode().value()); StringBuilder errorMessage = new StringBuilder( "HTTP " + statusCode + " (gRPC: " + status.getCode().name() + ")"); if (!Strings.isNullOrEmpty(status.getDescription())) { errorMessage.append(": ").append(Strings.nullToEmpty(status.getDescription())); } payload.setMessage(errorMessage.toString()); if (trailer != null) { if (trailer.containsKey(RETRY_INFO_KEY)) { RetryInfo retryInfo = trailer.get(RETRY_INFO_KEY); payload.addDetails(Any.pack(retryInfo)); } if (trailer.containsKey(DEBUG_INFO_KEY)) { DebugInfo debugInfo = trailer.get(DEBUG_INFO_KEY); payload.addDetails(Any.pack(debugInfo)); } } return new GrpcError( status, payload.build() ); }
@Override public void onError(Throwable t) { Metadata metadata = Status.trailersFromThrowable(t); if (metadata == null) { metadata = new Metadata(); } if (t instanceof MotanBizException) { call.close(Status.INTERNAL.withDescription(t.getMessage()).withCause(t), metadata); } else { call.close(Status.UNAVAILABLE.withDescription(t.getMessage()).withCause(t), metadata); } }
Context context = Context.current() .withValues( REQUEST_HEADERS, toMultimapFromHeaders(headers.get(HEADERS_KEY)), RESPONSE_HEADERS, HashMultimap.create()); boolean sideChannelOn = headers.containsKey(HEADERS_KEY); ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> simpleForwardingServerCall = new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
@Test public void resourceExhaustedWithBackoff() { Status status = Status.fromCodeValue(Status.Code.RESOURCE_EXHAUSTED.value()) .withDescription("Memory pushback"); Metadata trailers = new Metadata(); Metadata.Key<RetryInfo> key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); RetryInfo retryInfo = RetryInfo.newBuilder() .setRetryDelay(Duration.newBuilder().setNanos(1000000).setSeconds(1L)) .build(); trailers.put(key, retryInfo); SpannerException e = SpannerExceptionFactory.newSpannerException(new StatusRuntimeException(status, trailers)); assertThat(e.isRetryable()).isTrue(); assertThat(e.getRetryDelayInMillis()).isEqualTo(1001); }
/** * Partition the limit by a request header. * @return Chainable builder */ public GrpcServerLimiterBuilder partitionByHeader(Metadata.Key<String> header) { return partitionResolver(context -> context.getHeaders().get(header)); }
@Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( final ServerCall<ReqT, RespT> call, final Metadata headers, final ServerCallHandler<ReqT, RespT> next ) { if (!headers.containsKey(tokenKey)) { call.close(Status.PERMISSION_DENIED.withDescription("no authorization token"), new Metadata()); return new ServerCall.Listener<ReqT>(){}; } final String authToken = headers.get(tokenKey); LOGGER.debug("Got authentication token (" + authToken + ")"); return next.startCall(call, headers); } }
@Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { if (headers.containsKey(TenantTokenClientInterceptor.TENANT_ID_KEY)) { String tenantId = headers.get(TenantTokenClientInterceptor.TENANT_ID_KEY); LOGGER.trace("Server received tenant id key: " + tenantId); Context ctx = Context.current().withValue(GrpcContextKeys.TENANT_ID_KEY, tenantId); return Contexts.interceptCall(ctx, call, headers, next); } else { call.close(Status.UNAUTHENTICATED.withDescription("Tenant token not passed in metadata."), headers); return new ServerCall.Listener<ReqT>() { }; } }
Metadata trailers = new Metadata(); trailers.put(sInnerCauseKey, SerializationUtils.serialize(cause)); } catch (Exception exc) { LOG.warn("Could not serialize the cause: {}. Failed with: {}", cause, exc); return Status.fromCode(code).asException(trailers);