Java Code Examples for com.linecorp.armeria.client.Clients#newDerivedClient()

The following examples show how to use com.linecorp.armeria.client.Clients#newDerivedClient() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void maxOutboundSize_tooBig() throws Exception {
    // set at least one field to ensure the size is non-zero.
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                                      .build();
    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    GrpcClientOptions.MAX_OUTBOUND_MESSAGE_SIZE_BYTES.newValue(
                            request.getSerializedSize() - 1));
    final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
    assertThat(t).isInstanceOf(StatusRuntimeException.class);
    assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.CANCELLED);
    assertThat(Exceptions.traceText(t)).contains("message too large");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.params()).containsExactly(request);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.CANCELLED);
    });
}
 
Example 2
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void maxInboundSize_tooBig() throws Exception {
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                                      .build();
    final int size = blockingStub.streamingOutputCall(request).next().getSerializedSize();
    requestLogQueue.take();

    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    GrpcClientOptions.MAX_INBOUND_MESSAGE_SIZE_BYTES.newValue(size - 1));
    final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
    assertThat(t).isInstanceOf(StatusRuntimeException.class);
    assertThat(((StatusRuntimeException) t).getStatus().getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED);
    assertThat(Exceptions.traceText(t)).contains("exceeds maximum");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.params()).containsExactly(request);
        assertThat(grpcStatus).isNotNull();
        assertThat(grpcStatus.getCode()).isEqualTo(Code.RESOURCE_EXHAUSTED);
    });
}
 
Example 3
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void deadlineNotExceeded() {
    // warm up the channel and JVM
    blockingStub.emptyCall(Empty.getDefaultInstance());
    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    ClientOption.RESPONSE_TIMEOUT_MILLIS.newValue(
                            TimeUnit.SECONDS.toMillis(10)));
    stub
            .streamingOutputCall(
                    StreamingOutputCallRequest.newBuilder()
                                              .addResponseParameters(
                                                      ResponseParameters.newBuilder()
                                                                        .setIntervalUs(0))
                                              .build())
            .next();
}
 
Example 4
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void deadlineExceeded() throws Exception {
    // warm up the channel and JVM
    blockingStub.emptyCall(Empty.getDefaultInstance());
    requestLogQueue.take();

    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    ClientOption.RESPONSE_TIMEOUT_MILLIS.newValue(10L));
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(
                                              ResponseParameters.newBuilder()
                                                                .setIntervalUs(20000))
                                      .build();
    final Throwable t = catchThrowable(() -> stub.streamingOutputCall(request).next());
    assertThat(t).isInstanceOf(StatusRuntimeException.class);
    assertThat(((StatusRuntimeException) t).getStatus().getCode())
            .isEqualTo(Status.DEADLINE_EXCEEDED.getCode());

    checkRequestLogError((headers, rpcReq, cause) -> {
        assertThat(rpcReq).isNotNull();
        assertThat(rpcReq.params()).containsExactly(request);
        assertResponseTimeoutExceptionOrDeadlineExceeded(cause);
    });
}
 
Example 5
Source File: UnaryGrpcClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link UnaryGrpcClient} for the given {@link WebClient}.
 */
// TODO(anuraaga): We would ideally use our standard client building pattern, i.e.,
// Clients.builder(...).build(UnaryGrpcClient.class), but that requires mapping protocol schemes to media
// types, which cannot be duplicated. As this and normal gproto+ clients must use the same media type, we
// cannot currently implement this without rethinking / refactoring core and punt for now since this is an
// advanced API.
public UnaryGrpcClient(WebClient webClient) {
    this.webClient = Clients.newDerivedClient(
            webClient,
            ClientOption.DECORATION.newValue(
                    ClientDecoration.of(GrpcFramingDecorator::new)
            ));
}
 
Example 6
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void testDerivedClient(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final String AUTHORIZATION = "authorization";
    final String NO_TOKEN = "";
    final String TOKEN_A = "token 1234";
    final String TOKEN_B = "token 5678";

    final HeaderService.Iface client = Clients.builder(uri(Handlers.HEADER, format, protocol))
                                              .options(clientOptions)
                                              .build(Handlers.HEADER.iface());

    assertThat(client.header(AUTHORIZATION)).isEqualTo(NO_TOKEN);

    final HeaderService.Iface clientA =
            Clients.newDerivedClient(client,
                                     newHttpHeaderOption(HttpHeaderNames.of(AUTHORIZATION), TOKEN_A));

    final HeaderService.Iface clientB =
            Clients.newDerivedClient(client,
                                     newHttpHeaderOption(HttpHeaderNames.of(AUTHORIZATION), TOKEN_B));

    assertThat(clientA.header(AUTHORIZATION)).isEqualTo(TOKEN_A);
    assertThat(clientB.header(AUTHORIZATION)).isEqualTo(TOKEN_B);

    // Ensure that the parent client's HTTP_HEADERS option did not change:
    assertThat(client.header(AUTHORIZATION)).isEqualTo(NO_TOKEN);
}
 
Example 7
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
/** Start a fullDuplexCall which the server will not respond, and verify the deadline expires. */
@Test
void timeoutOnSleepingServer() throws Exception {
    final TestServiceStub stub = Clients.newDerivedClient(
            asyncStub,
            ClientOption.RESPONSE_TIMEOUT_MILLIS.newValue(1L));

    final StreamRecorder<StreamingOutputCallResponse> responseObserver = StreamRecorder.create();
    final StreamObserver<StreamingOutputCallRequest> requestObserver =
            stub.fullDuplexCall(responseObserver);

    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest
                    .newBuilder()
                    .setPayload(Payload.newBuilder()
                                       .setBody(ByteString.copyFrom(new byte[27182])))
                    .addResponseParameters(
                            ResponseParameters.newBuilder()
                                              .setIntervalUs((int) TimeUnit.SECONDS.toMicros(10)))
                    .build();
    try {
        requestObserver.onNext(request);
        // TODO(anuraag): Upstream test does not need to call onCompleted - response timeout is set at the
        // start of the stream, which seems to make sense. Figure out how to fix this timeout handling in
        // armeria.
        requestObserver.onCompleted();
    } catch (IllegalStateException expected) {
        // This can happen if the stream has already been terminated due to deadline exceeded.
    }

    responseObserver.awaitCompletion(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
    assertThat(responseObserver.getValues()).isEmpty();
    assertThat(responseObserver.getError()).isNotNull();
    // TODO(anuraag): As gRPC supports handling timeouts in the server or client due to the grpc-timeout
    // header, it's not guaranteed which is the source of this error.
    // Until https://github.com/line/armeria/issues/521 a server side timeout will not have the correct
    // status so we don't verify it for now.
    //assertThat(GrpcStatus.fromThrowable(responseObserver.getError()).getCode())
    //.isEqualTo(Status.DEADLINE_EXCEEDED.getCode());
}
 
Example 8
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void maxOutboundSize_exact() {
    // set at least one field to ensure the size is non-zero.
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                                      .build();
    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    GrpcClientOptions.MAX_OUTBOUND_MESSAGE_SIZE_BYTES.newValue(
                            request.getSerializedSize()));
    stub.streamingOutputCall(request).next();
}
 
Example 9
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void maxInboundSize_exact() {
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .addResponseParameters(ResponseParameters.newBuilder().setSize(1))
                                      .build();
    final int size = blockingStub.streamingOutputCall(request).next().getSerializedSize();

    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    GrpcClientOptions.MAX_INBOUND_MESSAGE_SIZE_BYTES.newValue(size));
    stub.streamingOutputCall(request).next();
}
 
Example 10
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void deadlineExceededServerStreaming() throws Exception {
    // warm up the channel and JVM
    blockingStub.emptyCall(Empty.getDefaultInstance());
    requestLogQueue.take();

    final ResponseParameters.Builder responseParameters = ResponseParameters.newBuilder()
                                                                            .setSize(1)
                                                                            .setIntervalUs(20000);
    final StreamingOutputCallRequest request =
            StreamingOutputCallRequest.newBuilder()
                                      .setResponseType(COMPRESSABLE)
                                      .addResponseParameters(responseParameters)
                                      .addResponseParameters(responseParameters)
                                      .addResponseParameters(responseParameters)
                                      .addResponseParameters(responseParameters)
                                      .build();
    final StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
    final TestServiceStub stub =
            Clients.newDerivedClient(
                    asyncStub,
                    ClientOption.RESPONSE_TIMEOUT_MILLIS.newValue(30L));
    stub.streamingOutputCall(request, recorder);
    recorder.awaitCompletion();

    assertThat(recorder.getError()).isNotNull();
    assertThat(GrpcStatus.fromThrowable(recorder.getError()).getCode())
            .isEqualTo(Status.DEADLINE_EXCEEDED.getCode());

    checkRequestLogError((headers, rpcReq, cause) -> {
        assertThat(rpcReq).isNotNull();
        assertThat(rpcReq.params()).containsExactly(request);
        assertResponseTimeoutExceptionOrDeadlineExceeded(cause);
    });
}
 
Example 11
Source File: ContentCompressionTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void thrift() throws Exception {
    final com.linecorp.centraldogma.internal.thrift.Revision head =
            new com.linecorp.centraldogma.internal.thrift.Revision(-1, 0);
    final Query query = new Query(PATH, QueryType.IDENTITY, ImmutableList.of());

    // Should fail to decode without the decompressor.
    final Iface clientWithoutDecompressor = Clients
            .builder("ttext+http", Endpoint.of("127.0.0.1", dogma.serverAddress().getPort()),
                     "/cd/thrift/v1")
            .setHttpHeader(HttpHeaderNames.AUTHORIZATION, "Bearer " + CsrfToken.ANONYMOUS)
            .setHttpHeader(HttpHeaderNames.ACCEPT_ENCODING, "deflate")
            .build(Iface.class);

    assertThatThrownBy(() -> clientWithoutDecompressor.getFile(PROJ, REPO, head, query))
            .isInstanceOf(TException.class)
            .hasCauseInstanceOf(JsonParseException.class);

    // Should succeed to decode with the decompressor.
    final Iface clientWithDecompressor = Clients.newDerivedClient(
            clientWithoutDecompressor,
            options -> options.toBuilder()
                              .decorator(DecodingClient.newDecorator())
                              .build());

    final GetFileResult result = clientWithDecompressor.getFile(PROJ, REPO, head, query);
    assertThat(result.getContent()).contains(CONTENT);
}
 
Example 12
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void sendsTimeoutHeader() {
    final long configuredTimeoutMinutes = 100;
    final TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    ClientOption.RESPONSE_TIMEOUT_MILLIS.newValue(
                            TimeUnit.MINUTES.toMillis(configuredTimeoutMinutes)));
    stub.emptyCall(EMPTY);
    final long transferredTimeoutMinutes = TimeUnit.NANOSECONDS.toMinutes(
            TimeoutHeaderUtil.fromHeaderValue(
                    CLIENT_HEADERS_CAPTURE.get().get(GrpcHeaderNames.GRPC_TIMEOUT)));
    assertThat(transferredTimeoutMinutes).isEqualTo(configuredTimeoutMinutes);
}
 
Example 13
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void exchangeHeadersUnaryCall_armeriaHeaders() throws Exception {
    TestServiceBlockingStub stub =
            Clients.newDerivedClient(
                    blockingStub,
                    ClientOption.HTTP_HEADERS.newValue(
                            HttpHeaders.of(TestServiceImpl.EXTRA_HEADER_NAME, "dog")));

    final AtomicReference<Metadata> headers = new AtomicReference<>();
    final AtomicReference<Metadata> trailers = new AtomicReference<>();
    stub = MetadataUtils.captureMetadata(stub, headers, trailers);

    assertThat(stub.emptyCall(EMPTY)).isNotNull();

    // Assert that our side channel object is echoed back in both headers and trailers
    assertThat(CLIENT_HEADERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog");
    assertThat(SERVER_TRAILERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog");

    assertThat(headers.get()).isNull();
    assertThat(trailers.get().get(TestServiceImpl.EXTRA_HEADER_KEY)).isEqualTo("dog");
    assertThat(trailers.get().getAll(TestServiceImpl.STRING_VALUE_KEY)).containsExactly(
            StringValue.newBuilder().setValue("hello").build(),
            StringValue.newBuilder().setValue("world").build());

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.params()).containsExactly(EMPTY);
        assertThat(rpcRes.get()).isEqualTo(EMPTY);
    });
}
 
Example 14
Source File: GcloudModule.java    From curiostack with MIT License 5 votes vote down vote up
@Provides
@Singleton
@RetryingGoogleApis
public static WebClient retryingGoogleApisClient(@GoogleApis WebClient googleApisClient) {
  return Clients.newDerivedClient(
      googleApisClient,
      ClientOption.DECORATION.newValue(
          ClientDecoration.of(RetryingClient.newDecorator(RetryRule.onServerErrorStatus()))));
}
 
Example 15
Source File: GcloudAuthModule.java    From curiostack with MIT License 5 votes vote down vote up
private static WebClient authenticated(
    WebClient client, GoogleCredentialsDecoratingClient.Factory credentialsDecorator) {
  return Clients.newDerivedClient(
      client,
      ClientOption.DECORATION.newValue(
          ClientDecoration.of(credentialsDecorator.newAccessTokenDecorator())));
}
 
Example 16
Source File: StorageModule.java    From curiostack with MIT License 5 votes vote down vote up
@Provides
@ForStorage
@Singleton
static WebClient metricClient(@RetryingAuthenticatedGoogleApis WebClient httpClient) {
  return Clients.newDerivedClient(
      httpClient,
      ClientOption.DECORATION.newValue(
          ClientDecoration.of(
              MetricCollectingClient.newDecorator(MetricLabels.storageRequestLabeler()))));
}
 
Example 17
Source File: Subscriber.java    From curiostack with MIT License 5 votes vote down vote up
public Subscriber(
    @Provided SubscriberStub stub,
    @Provided Optional<MeterRegistry> meterRegistry,
    @Provided Tracing tracing,
    SubscriberOptions options) {
  this.stub =
      options.getUnsafeWrapBuffers()
          ? Clients.newDerivedClient(
              stub, GrpcClientOptions.UNSAFE_WRAP_RESPONSE_BUFFERS.newValue(true))
          : stub;
  this.options = options;

  MeterRegistry registry = meterRegistry.orElse(NoopMeterRegistry.get());

  List<Tag> tags = ImmutableList.of(Tag.of("subscription", options.getSubscription()));

  receivedMessages = registry.counter("subscriber-received-messages", tags);
  ackedMessages = registry.counter("subscriber-acked-messages", tags);
  nackedMessages = registry.counter("subscriber-nacked-messages", tags);
  registry.gauge("reconnect-backoff-millis", tags, streamReconnectBackoff, Duration::toMillis);

  messageProcessingTime =
      MoreMeters.newTimer(registry, "subscriber-message-processing-time", tags);

  tracer = tracing.tracer();
  traceExtractor =
      tracing
          .propagation()
          .extractor((message, key) -> message.getAttributesOrDefault(key, null));
}
 
Example 18
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void exchangeHeadersStreamingCall() throws Exception {
    final TestServiceStub stub =
            Clients.newDerivedClient(
                    asyncStub,
                    ClientOption.HTTP_HEADERS.newValue(
                            HttpHeaders.of(TestServiceImpl.EXTRA_HEADER_NAME, "dog")));

    final List<Integer> responseSizes = Arrays.asList(50, 100, 150, 200);
    final StreamingOutputCallRequest.Builder streamingOutputBuilder =
            StreamingOutputCallRequest.newBuilder();
    streamingOutputBuilder.setResponseType(COMPRESSABLE);
    for (Integer size : responseSizes) {
        streamingOutputBuilder.addResponseParametersBuilder().setSize(size).setIntervalUs(0);
    }
    final StreamingOutputCallRequest request = streamingOutputBuilder.build();

    final StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
    final StreamObserver<StreamingOutputCallRequest> requestStream =
            stub.fullDuplexCall(recorder);

    final int numRequests = 10;
    final List<StreamingOutputCallRequest> requests = new ArrayList<>(numRequests);

    for (int ix = numRequests; ix > 0; --ix) {
        requests.add(request);
        requestStream.onNext(request);
    }
    requestStream.onCompleted();
    recorder.awaitCompletion();
    assertSuccess(recorder);
    assertThat(recorder.getValues()).hasSize(responseSizes.size() * numRequests);

    final HttpHeaders clientHeaders = CLIENT_HEADERS_CAPTURE.get();
    assertThat(clientHeaders.get(HttpHeaderNames.TE))
            .isEqualTo(HttpHeaderValues.TRAILERS.toString());

    // Assert that our side channel object is echoed back in both headers and trailers
    assertThat(clientHeaders.get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog");
    assertThat(SERVER_TRAILERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog");

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.params()).containsExactly(requests.get(0));
        assertThat(rpcRes.get()).isEqualTo(recorder.getValues().get(0));
    });
}