com.linecorp.armeria.client.ClientRequestContext Java Examples

The following examples show how to use com.linecorp.armeria.client.ClientRequestContext. 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: RetryRuleBuilder.java    From armeria with Apache License 2.0 6 votes vote down vote up
static RetryRule build(BiFunction<? super ClientRequestContext, ? super Throwable, Boolean> ruleFilter,
                       RetryDecision decision, boolean requiresResponseTrailers) {
    final CompletableFuture<RetryDecision> decisionFuture;
    if (decision == RetryDecision.DEFAULT) {
        decisionFuture = DEFAULT_DECISION;
    } else {
        decisionFuture = CompletableFuture.completedFuture(decision);
    }

    return new RetryRule() {
        @Override
        public CompletionStage<RetryDecision> shouldRetry(ClientRequestContext ctx,
                                                          @Nullable Throwable cause) {
            return ruleFilter.apply(ctx, cause) ? decisionFuture : NEXT_DECISION;
        }

        @Override
        public boolean requiresResponseTrailers() {
            return requiresResponseTrailers;
        }
    };
}
 
Example #2
Source File: ArmeriaCentralDogmaBuilder.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a newly-created {@link CentralDogma} instance.
 *
 * @throws UnknownHostException if failed to resolve the host names from the DNS servers
 */
public CentralDogma build() throws UnknownHostException {
    final EndpointGroup endpointGroup = endpointGroup();
    final String scheme = "none+" + (isUseTls() ? "https" : "http");
    final ClientBuilder builder =
            newClientBuilder(scheme, endpointGroup, cb -> cb.decorator(DecodingClient.newDecorator()), "/");
    final EventLoopGroup executor = clientFactory().eventLoopGroup();
    final int maxRetriesOnReplicationLag = maxNumRetriesOnReplicationLag();
    final CentralDogma dogma = new ArmeriaCentralDogma(executor,
                                                       builder.build(WebClient.class),
                                                       accessToken());
    if (maxRetriesOnReplicationLag <= 0) {
        return dogma;
    } else {
        return new ReplicationLagTolerantCentralDogma(
                executor, dogma, maxRetriesOnReplicationLag, retryIntervalOnReplicationLagMillis(),
                () -> {
                    // FIXME(trustin): Note that this will always return `null` due to a known limitation
                    //                 in Armeria: https://github.com/line/armeria/issues/760
                    final ClientRequestContext ctx = ClientRequestContext.currentOrNull();
                    return ctx != null ? ctx.remoteAddress() : null;
                });
    }
}
 
Example #3
Source File: CircuitBreakerRuleUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static CircuitBreakerRuleWithContent<HttpResponse>
withDuplicator(CircuitBreakerRuleWithContent<HttpResponse> ruleWithContent,
               HttpResponseDuplicator duplicator) {

    return new CircuitBreakerRuleWithContent<HttpResponse>() {
        @Override
        public CompletionStage<CircuitBreakerDecision> shouldReportAsSuccess(
                ClientRequestContext ctx, @Nullable HttpResponse response, @Nullable Throwable cause) {

            return ruleWithContent.shouldReportAsSuccess(ctx, duplicator.duplicate(), cause);
        }

        @Override
        public boolean requiresResponseTrailers() {
            return ruleWithContent.requiresResponseTrailers();
        }
    };
}
 
Example #4
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void onException() {
    final ClientRequestContext ctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final Backoff backoff1 = Backoff.fixed(1000);
    final Backoff backoff2 = Backoff.fixed(2000);
    final RetryRule rule = RetryRule.of(RetryRule.builder()
                                                 .onException(ClosedSessionException.class)
                                                 .thenBackoff(backoff1),
                                        RetryRule.builder()
                                                 .onException((unused, obj) -> {
                                                     return "/".equals(ctx.path()) &&
                                                            obj instanceof WriteTimeoutException;
                                                 })
                                                 .thenBackoff(backoff2));

    assertBackoff(rule.shouldRetry(ctx, ClosedSessionException.get())).isSameAs(backoff1);
    assertBackoff(rule.shouldRetry(ctx, new CompletionException(ClosedSessionException.get())))
            .isSameAs(backoff1);
    assertBackoff(rule.shouldRetry(ctx, WriteTimeoutException.get())).isSameAs(backoff2);
    assertBackoff(rule.shouldRetry(ctx, ResponseTimeoutException.get())).isNull();
    assertBackoff(rule.shouldRetry(ctx, null)).isNull();
}
 
Example #5
Source File: LoggingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void sanitizeRequestHeaders() throws Exception {
    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.POST, "/hello/trustin",
                                                             HttpHeaderNames.SCHEME, "http",
                                                             HttpHeaderNames.AUTHORITY, "test.com"));

    final ClientRequestContext ctx = ClientRequestContext.of(req);

    // use default logger
    final LoggingClient defaultLoggerClient =
            LoggingClient.builder()
                         .requestLogLevel(LogLevel.INFO)
                         .successfulResponseLogLevel(LogLevel.INFO)
                         .requestHeadersSanitizer(RegexBasedSanitizer.of(
                                 Pattern.compile("trustin"),
                                 Pattern.compile("com")))
                         .build(delegate);

    // Pre sanitize step
    assertThat(ctx.logBuilder().toString()).contains("trustin");
    assertThat(ctx.logBuilder().toString()).contains("test.com");
    defaultLoggerClient.execute(ctx, req);
    // After the sanitize
    assertThat(ctx.logBuilder().toString()).doesNotContain("trustin");
    assertThat(ctx.logBuilder().toString()).doesNotContain("com");
}
 
Example #6
Source File: RetryRuleUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static <T extends Response> CompletionStage<RetryDecision> handle(
        ClientRequestContext ctx, @Nullable T response, @Nullable Throwable cause,
        RetryRuleWithContent<T> first, RetryRuleWithContent<T> second) {
    final CompletionStage<RetryDecision> decisionFuture = first.shouldRetry(ctx, response, cause);
    if (decisionFuture == DEFAULT_DECISION) {
        return decisionFuture;
    }
    if (decisionFuture == NEXT_DECISION) {
        return second.shouldRetry(ctx, response, cause);
    }
    return decisionFuture.thenCompose(decision -> {
        if (decision != RetryDecision.next()) {
            return decisionFuture;
        } else {
            return second.shouldRetry(ctx, response, cause);
        }
    });
}
 
Example #7
Source File: ConcurrencyLimitingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the request pattern  that does not exceed maxConcurrency.
 */
@Test
void testOrdinaryRequest() throws Exception {
    final HttpRequest req = newReq();
    final ClientRequestContext ctx = newContext();
    final HttpResponseWriter actualRes = HttpResponse.streaming();

    when(delegate.execute(ctx, req)).thenReturn(actualRes);

    final ConcurrencyLimitingClient client =
            newDecorator(1).apply(delegate);
    assertThat(client.numActiveRequests()).isZero();

    final HttpResponse res = client.execute(ctx, req);
    assertThat(res.isOpen()).isTrue();
    assertThat(client.numActiveRequests()).isEqualTo(1);

    closeAndDrain(actualRes, res);

    assertThat(res.isOpen()).isFalse();
    await().untilAsserted(() -> assertThat(client.numActiveRequests()).isZero());
}
 
Example #8
Source File: CircuitBreakerRuleUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
static <T extends Response> CircuitBreakerRuleWithContent<T> fromCircuitBreakerRule(
        CircuitBreakerRule circuitBreakerRule) {
    return new CircuitBreakerRuleWithContent<T>() {
        @Override
        public CompletionStage<CircuitBreakerDecision> shouldReportAsSuccess(ClientRequestContext ctx,
                                                                             @Nullable T response,
                                                                             @Nullable Throwable cause) {
            return circuitBreakerRule.shouldReportAsSuccess(ctx, cause);
        }

        @Override
        public boolean requiresResponseTrailers() {
            return circuitBreakerRule.requiresResponseTrailers();
        }
    };
}
 
Example #9
Source File: AbstractConcurrencyLimitingClient.java    From armeria with Apache License 2.0 6 votes vote down vote up
private O unlimitedExecute(ClientRequestContext ctx, I req) throws Exception {
    numActiveRequests.incrementAndGet();
    boolean success = false;
    try {
        final O res = unwrap().execute(ctx, req);
        res.whenComplete().handle((unused, cause) -> {
            numActiveRequests.decrementAndGet();
            return null;
        });
        success = true;
        return res;
    } finally {
        if (!success) {
            numActiveRequests.decrementAndGet();
        }
    }
}
 
Example #10
Source File: LoggingRpcClient.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new instance that logs {@link Request}s and {@link Response}s at the specified
 * {@link LogLevel}s with the specified sanitizers.
 * If the logger is null, it means that the default logger is used.
 */
LoggingRpcClient(
        RpcClient delegate,
        @Nullable Logger logger,
        Function<? super RequestOnlyLog, LogLevel> requestLogLevelMapper,
        Function<? super RequestLog, LogLevel> responseLogLevelMapper,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> requestHeadersSanitizer,
        BiFunction<? super RequestContext, Object, ?> requestContentSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> requestTrailersSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> responseHeadersSanitizer,
        BiFunction<? super RequestContext, Object, ?> responseContentSanitizer,
        BiFunction<? super RequestContext, ? super HttpHeaders, ?> responseTrailersSanitizer,
        BiFunction<? super RequestContext, ? super Throwable, ?> responseCauseSanitizer,
        Sampler<? super ClientRequestContext> sampler) {

    super(delegate, logger, requestLogLevelMapper, responseLogLevelMapper,
          requestHeadersSanitizer, requestContentSanitizer, requestTrailersSanitizer,
          responseHeadersSanitizer, responseContentSanitizer, responseTrailersSanitizer,
          responseCauseSanitizer, sampler);
}
 
Example #11
Source File: AbstractConcurrencyLimitingClient.java    From armeria with Apache License 2.0 6 votes vote down vote up
private O limitedExecute(ClientRequestContext ctx, I req) throws Exception {
    final CompletableFuture<O> resFuture = new CompletableFuture<>();
    final O deferred = newDeferredResponse(ctx, resFuture);
    final PendingTask currentTask = new PendingTask(ctx, req, resFuture);

    pendingRequests.add(currentTask);
    drain();

    if (!currentTask.isRun() && timeoutMillis != 0) {
        // Current request was not delegated. Schedule a timeout.
        final ScheduledFuture<?> timeoutFuture = ctx.eventLoop().schedule(
                () -> resFuture.completeExceptionally(
                        UnprocessedRequestException.of(RequestTimeoutException.get())),
                timeoutMillis, TimeUnit.MILLISECONDS);
        currentTask.set(timeoutFuture);
    }

    return deferred;
}
 
Example #12
Source File: ServiceRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void current() {
    assertThatThrownBy(ServiceRequestContext::current).isInstanceOf(IllegalStateException.class)
                                                      .hasMessageContaining("unavailable");

    final ServiceRequestContext sctx = serviceRequestContext();
    try (SafeCloseable unused = sctx.push()) {
        assertThat(ServiceRequestContext.current()).isSameAs(sctx);
        final ClientRequestContext cctx = clientRequestContext();
        try (SafeCloseable unused1 = cctx.push()) {
            assertThat(ServiceRequestContext.current()).isSameAs(sctx);
            assertThat(ClientRequestContext.current()).isSameAs(cctx);
            assertThat((ClientRequestContext) RequestContext.current()).isSameAs(cctx);
        }
        assertCurrentCtx(sctx);
    }
    assertCurrentCtx(null);

    try (SafeCloseable unused = clientRequestContext().push()) {
        assertThatThrownBy(ServiceRequestContext::current)
                .isInstanceOf(IllegalStateException.class)
                .hasMessageContaining("not a server-side context");
    }
}
 
Example #13
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void httpFailure() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ClientRequestContext ctx = setupClientRequestCtx(registry);

    ctx.logBuilder().requestFirstBytesTransferred();
    ctx.logBuilder().responseHeaders(ResponseHeaders.of(500));
    ctx.logBuilder().responseFirstBytesTransferred();
    ctx.logBuilder().responseLength(456);
    ctx.logBuilder().endRequest();
    ctx.logBuilder().endResponse();

    final Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements)
            .containsEntry("foo.active.requests#value{method=POST}", 0.0)
            .containsEntry("foo.requests#count{http.status=500,method=POST,result=success}", 0.0)
            .containsEntry("foo.requests#count{http.status=500,method=POST,result=failure}", 1.0)
            .containsEntry("foo.response.duration#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.response.length#count{http.status=500,method=POST}", 1.0)
            .containsEntry("foo.total.duration#count{http.status=500,method=POST}", 1.0);
}
 
Example #14
Source File: LegacyCentralDogmaTimeoutScheduler.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public RpcResponse execute(ClientRequestContext ctx, RpcRequest req) throws Exception {
    final long responseTimeoutMillis = ctx.responseTimeoutMillis();
    if (responseTimeoutMillis > 0) {
        final String method = req.method();
        if ("watchFile".equals(method) || "watchRepository".equals(method)) {
            final List<Object> params = req.params();
            final long timeout = (Long) params.get(params.size() - 1);
            if (timeout > 0) {
                ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND,
                                             WatchTimeout.availableTimeout(timeout, responseTimeoutMillis));
            }
        }
    }
    return delegate().execute(ctx, req);
}
 
Example #15
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void onResponseTrailers() {
    final Backoff backoff = Backoff.fixed(1000);
    final RetryRule rule =
            RetryRule.builder()
                     .onResponseTrailers((unused, trailers) -> trailers.containsInt("grpc-status", 3))
                     .thenBackoff(backoff);

    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().responseTrailers(HttpHeaders.of("grpc-status", 3));
    assertBackoff(rule.shouldRetry(ctx1, null)).isSameAs(backoff);

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().responseTrailers(HttpHeaders.of("grpc-status", 0));
    assertBackoff(rule.shouldRetry(ctx2, null)).isNull();
}
 
Example #16
Source File: ClientRequestContextPushedOnCallbackTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void pushedContextOnAsyncMethodCallback() throws Exception {
    final AtomicReference<ClientRequestContext> ctxHolder = new AtomicReference<>();
    final AsyncIface client = Clients.newClient(server.httpUri(BINARY) + "/hello", AsyncIface.class);

    final ClientRequestContext ctx;
    final CountDownLatch latch = new CountDownLatch(1);
    try (ClientRequestContextCaptor captor = Clients.newContextCaptor()) {
        client.hello("foo", new AsyncMethodCallback<String>() {
            @Override
            public void onComplete(String response) {
                assertThat(response).isEqualTo("Hello, foo!");
                ctxHolder.set(RequestContext.currentOrNull());
                latch.countDown();
            }

            @Override
            public void onError(Exception exception) {}
        });
        ctx = captor.get();
    }

    latch.await();
    assertThat(ctx).isSameAs(ctxHolder.get());
}
 
Example #17
Source File: ConcurrencyLimitingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the case where a delegate raises an exception rather than returning a response.
 */
@Test
void testFaultyDelegate() throws Exception {
    final ClientRequestContext ctx = newContext();
    final HttpRequest req = newReq();

    when(delegate.execute(ctx, req)).thenThrow(Exception.class);

    final ConcurrencyLimitingClient client = newDecorator(1).apply(delegate);
    assertThat(client.numActiveRequests()).isZero();

    final HttpResponse res = client.execute(ctx, req);

    // Consume everything from the returned response so its close future is completed.
    res.subscribe(NoopSubscriber.get());

    assertThat(res.isOpen()).isFalse();
    assertThatThrownBy(() -> res.whenComplete().get()).hasCauseInstanceOf(Exception.class);
    await().untilAsserted(() -> assertThat(client.numActiveRequests()).isZero());
}
 
Example #18
Source File: LoggingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void sanitizeRequestContent() throws Exception {

    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.POST, "/hello/trustin",
                                                             HttpHeaderNames.SCHEME, "http",
                                                             HttpHeaderNames.AUTHORITY, "test.com"));

    final ClientRequestContext ctx = ClientRequestContext.of(req);
    ctx.logBuilder().requestContent("Virginia 333-490-4499", "Virginia 333-490-4499");

    // use default logger
    final LoggingClient defaultLoggerClient =
            LoggingClient.builder()
                         .requestLogLevel(LogLevel.INFO)
                         .successfulResponseLogLevel(LogLevel.INFO)
                         .requestContentSanitizer(RegexBasedSanitizer.of(
                                 Pattern.compile("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")))
                         .build(delegate);

    // Before sanitize content
    assertThat(ctx.logBuilder().toString()).contains("333-490-4499");
    defaultLoggerClient.execute(ctx, req);
    // Ensure sanitize the request content of the phone number 333-490-4499
    assertThat(ctx.logBuilder().toString()).doesNotContain("333-490-4499");
}
 
Example #19
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void contextCaptorSync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final HelloService.Iface client = Clients.builder(uri(Handlers.HELLO, format, protocol))
                                             .options(clientOptions)
                                             .build(Handlers.HELLO.iface());
    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        client.hello("kukuman");
        final ClientRequestContext ctx = ctxCaptor.get();
        final RpcRequest rpcReq = ctx.rpcRequest();
        assertThat(rpcReq).isNotNull();
        assertThat(rpcReq.method()).isEqualTo("hello");
        assertThat(rpcReq.params()).containsExactly("kukuman");
    }
}
 
Example #20
Source File: ThriftOverHttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ParametersProvider.class)
void contextCaptorAsync(
        ClientOptions clientOptions, SerializationFormat format, SessionProtocol protocol)
        throws Exception {
    final HelloService.AsyncIface client =
            Clients.builder(uri(Handlers.HELLO, format, protocol))
                   .options(clientOptions)
                   .build(Handlers.HELLO.asyncIface());

    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        client.hello("kukuman", new ThriftFuture<>());
        final ClientRequestContext ctx = ctxCaptor.get();
        final RpcRequest rpcReq = ctx.rpcRequest();
        assertThat(rpcReq).isNotNull();
        assertThat(rpcReq.method()).isEqualTo("hello");
        assertThat(rpcReq.params()).containsExactly("kukuman");
    }
}
 
Example #21
Source File: ConcurrencyLimitingClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testUnlimitedRequest() throws Exception {
    final ClientRequestContext ctx = newContext();
    final HttpRequest req = newReq();
    final HttpResponseWriter actualRes = HttpResponse.streaming();

    when(delegate.execute(ctx, req)).thenReturn(actualRes);

    final ConcurrencyLimitingClient client =
            newDecorator(0).apply(delegate);

    // A request should be delegated immediately, creating no deferred response.
    final HttpResponse res = client.execute(ctx, req);
    verify(delegate).execute(ctx, req);
    assertThat(res.isOpen()).isTrue();
    assertThat(client.numActiveRequests()).isEqualTo(1);

    // Complete the response, leaving no active requests.
    closeAndDrain(actualRes, res);
    await().untilAsserted(() -> assertThat(client.numActiveRequests()).isZero());
}
 
Example #22
Source File: ArmeriaHttpClientParser.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void parse(brave.http.HttpRequest request, TraceContext context, SpanCustomizer span) {
    HttpRequestParser.DEFAULT.parse(request, context, span);

    final Object unwrapped = request.unwrap();
    if (!(unwrapped instanceof ClientRequestContext)) {
        return;
    }

    final ClientRequestContext ctx = (ClientRequestContext) unwrapped;
    final HttpRequest httpReq = ctx.request();
    if (httpReq == null) {
        // Should never reach here because BraveClient is an HTTP-level decorator.
        return;
    }

    span.tag(SpanTags.TAG_HTTP_HOST, httpReq.authority())
        .tag(SpanTags.TAG_HTTP_URL, httpReq.uri().toString());
}
 
Example #23
Source File: RequestMetricSupportTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void responseTimedOutInClientSide() {
    final MeterRegistry registry = PrometheusMeterRegistries.newRegistry();
    final ClientRequestContext ctx = setupClientRequestCtx(registry);

    ctx.logBuilder().requestFirstBytesTransferred();
    ctx.logBuilder().endRequest();
    ctx.logBuilder().endResponse(ResponseTimeoutException.get());

    final Map<String, Double> measurements = measureAll(registry);
    assertThat(measurements)
            .containsEntry("foo.active.requests#value{method=POST}", 0.0)
            .containsEntry("foo.requests#count{http.status=0,method=POST,result=success}", 0.0)
            .containsEntry("foo.requests#count{http.status=0,method=POST,result=failure}", 1.0)
            .containsEntry("foo.timeouts#count{cause=WriteTimeoutException,http.status=0,method=POST}", 0.0)
            .containsEntry("foo.timeouts#count{cause=ResponseTimeoutException," +
                           "http.status=0,method=POST}", 1.0)
            .containsEntry("foo.response.duration#count{http.status=0,method=POST}", 1.0)
            .containsEntry("foo.response.length#count{http.status=0,method=POST}", 1.0)
            .containsEntry("foo.total.duration#count{http.status=0,method=POST}", 1.0);
}
 
Example #24
Source File: RetryingClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<RetryDecision> shouldRetry(ClientRequestContext ctx,
                                                  @Nullable HttpResponse response,
                                                  @Nullable Throwable cause) {
    final CompletableFuture<AggregatedHttpResponse> future = response.aggregate();
    return future.handle((aggregatedResponse, unused) -> {
        if (aggregatedResponse != null &&
            aggregatedResponse.contentUtf8().equalsIgnoreCase(retryContent)) {
            return decision;
        }
        return null;
    });
}
 
Example #25
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void onStatusClass() {
    final RetryRule rule = RetryRule.onStatusClass(HttpStatusClass.CLIENT_ERROR);

    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.BAD_REQUEST));
    assertBackoff(rule.shouldRetry(ctx1, null)).isSameAs(Backoff.ofDefault());

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.OK));
    assertBackoff(rule.shouldRetry(ctx2, null)).isNull();
}
 
Example #26
Source File: ClientUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
public static <I extends Request, O extends Response, U extends Client<I, O>>
O executeWithFallback(U delegate, ClientRequestContext ctx,
                      BiFunction<ClientRequestContext, Throwable, O> errorResponseFactory) {

    requireNonNull(delegate, "delegate");
    requireNonNull(ctx, "ctx");
    requireNonNull(errorResponseFactory, "errorResponseFactory");

    try {
        return pushAndExecute(delegate, ctx);
    } catch (Throwable cause) {
        fail(ctx, cause);
        return errorResponseFactory.apply(ctx, cause);
    }
}
 
Example #27
Source File: RetryingClientWithLoggingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private Function<? super HttpClient, ? extends HttpClient> loggingDecorator() {
    return delegate -> new SimpleDecoratingHttpClient(delegate) {
        @Override
        public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception {
            ctx.log().whenRequestComplete().thenAccept(log -> listener.accept(log.partial()));
            ctx.log().whenComplete().thenAccept(listener);
            return unwrap().execute(ctx, req);
        }
    };
}
 
Example #28
Source File: THttpClientDelegate.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static String fullMethod(ClientRequestContext ctx, String method) {
    final String service = ctx.fragment();
    if (Strings.isNullOrEmpty(service)) {
        return method;
    } else {
        return service + ':' + method;
    }
}
 
Example #29
Source File: AbstractRetryingClient.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Resets the {@link ClientRequestContext#responseTimeoutMillis()}.
 *
 * @return {@code true} if the response timeout is set, {@code false} if it can't be set due to the timeout
 */
@SuppressWarnings("MethodMayBeStatic") // Intentionally left non-static for better user experience.
protected final boolean setResponseTimeout(ClientRequestContext ctx) {
    requireNonNull(ctx, "ctx");
    final long responseTimeoutMillis = ctx.attr(STATE).responseTimeoutMillis();
    if (responseTimeoutMillis < 0) {
        return false;
    } else if (responseTimeoutMillis == 0) {
        ctx.clearResponseTimeout();
        return true;
    } else {
        ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, responseTimeoutMillis);
        return true;
    }
}
 
Example #30
Source File: RetryRuleUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
static <T extends Response> RetryRuleWithContent<T> fromRetryRule(RetryRule retryRule) {
    return new RetryRuleWithContent<T>() {
        @Override
        public CompletionStage<RetryDecision> shouldRetry(ClientRequestContext ctx, @Nullable T response,
                                                          @Nullable Throwable cause) {
            return retryRule.shouldRetry(ctx, cause);
        }

        @Override
        public boolean requiresResponseTrailers() {
            return retryRule.requiresResponseTrailers();
        }
    };
}