Java Code Examples for com.linecorp.armeria.client.ClientRequestContext#of()

The following examples show how to use com.linecorp.armeria.client.ClientRequestContext#of() . 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: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void noDelay() {
    final int maxAttempts = 10;
    final RetryRule rule = RetryRule.builder()
                                    .onStatus((unused, status) -> status == HttpStatus.BAD_REQUEST ||
                                                                  status == HttpStatus.TOO_MANY_REQUESTS)
                                    .thenBackoff(Backoff.withoutDelay().withMaxAttempts(maxAttempts));

    for (int i = 1; i < maxAttempts; i++) {
        final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
        ctx1.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.BAD_REQUEST));
        assertThat(rule.shouldRetry(ctx1, null).toCompletableFuture().join()
                       .backoff().nextDelayMillis(i))
                .isEqualTo(0);

        final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
        ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR));
        assertBackoff(rule.shouldRetry(ctx2, null)).isNull();
    }

    final ClientRequestContext ctx3 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx3.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.BAD_REQUEST));
    assertThat(rule.shouldRetry(ctx3, null).toCompletableFuture().join()
                   .backoff().nextDelayMillis(maxAttempts + 1))
            .isEqualTo(-1);
}
 
Example 2
Source File: AbstractEndpointSelectorTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void timeout() {
    final DynamicEndpointGroup group = new DynamicEndpointGroup();
    final ClientRequestContext ctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final CompletableFuture<Endpoint> future =
            newSelector(group).select(ctx, ctx.eventLoop(), 1000)
                              .handle((res, cause) -> {
                                  // Must be invoked from the event loop thread.
                                  assertThat(ctx.eventLoop().inEventLoop()).isTrue();

                                  if (cause != null) {
                                      Exceptions.throwUnsafely(cause);
                                  }

                                  return res;
                              });
    assertThat(future).isNotDone();

    final Stopwatch stopwatch = Stopwatch.createStarted();
    assertThat(future.join()).isNull();
    assertThat(stopwatch.elapsed(TimeUnit.MILLISECONDS)).isGreaterThan(900);
}
 
Example 3
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 4
Source File: RequestContextExporterTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUseOwnAttrToStoreInternalState() {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext rootCtx = ServiceRequestContext.of(req);
    final RequestContextExporter exporter = RequestContextExporter.builder().build();

    // Create an internal state.
    exporter.export(rootCtx);
    final Object rootState = rootCtx.attr(RequestContextExporter.STATE);
    assertThat(rootState).isNotNull();

    // Create a child context.
    final ClientRequestContext childCtx;
    try (SafeCloseable unused = rootCtx.push()) {
        childCtx = ClientRequestContext.of(req);
    }
    assertThat(childCtx.root()).isSameAs(rootCtx);
    assertThat(childCtx.attr(RequestContextExporter.STATE)).isSameAs(rootState);
    assertThat(childCtx.ownAttr(RequestContextExporter.STATE)).isNull();

    // Make sure a new internal state object is created.
    exporter.export(childCtx);
    final Object childState = childCtx.attr(RequestContextExporter.STATE);
    assertThat(childState).isNotNull().isNotSameAs(rootState);
}
 
Example 5
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 6
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void onStatus() {
    final Backoff backoff500 = Backoff.fixed(1000);
    final Backoff backoff502 = Backoff.fixed(1000);
    final RetryRule rule =
            RetryRule.builder()
                     .onStatus(HttpStatus.INTERNAL_SERVER_ERROR)
                     .thenBackoff(backoff500)
                     .orElse(RetryRule.builder()
                                      .onStatus((unused, status) -> HttpStatus.BAD_GATEWAY.equals(status))
                                      .thenBackoff(backoff502));

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

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.BAD_GATEWAY));
    assertBackoff(rule.shouldRetry(ctx2, null)).isSameAs(backoff502);

    final ClientRequestContext ctx3 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx3.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.GATEWAY_TIMEOUT));
    assertBackoff(rule.shouldRetry(ctx3, null)).isNull();
}
 
Example 7
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void onStatusErrorStatus() {
    final Backoff backoff = Backoff.fixed(2000);
    final RetryRule rule = RetryRule.builder().onServerErrorStatus().thenBackoff(backoff);

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

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.BAD_REQUEST));
    assertBackoff(rule.shouldRetry(ctx2, null)).isNull();
}
 
Example 8
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void noRetry() {
    final RetryRule rule = RetryRule.builder(HttpMethod.POST).thenNoRetry()
                                    .orElse(RetryRule.onException());

    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    assertBackoff(rule.shouldRetry(ctx1, new RuntimeException())).isSameAs(Backoff.ofDefault());

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.POST, "/"));
    assertBackoff(rule.shouldRetry(ctx2, new RuntimeException())).isNull();
}
 
Example 9
Source File: RetryRuleBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void buildFluently() {
    final Backoff idempotentBackoff = Backoff.fixed(100);
    final Backoff unprocessedBackoff = Backoff.fixed(200);
    final RetryRule retryRule =
            RetryRule.of(RetryRule.builder(HttpMethod.idempotentMethods())
                                  .onStatus(HttpStatus.INTERNAL_SERVER_ERROR)
                                  .onException(ClosedChannelException.class)
                                  .onStatusClass(HttpStatusClass.CLIENT_ERROR)
                                  .thenBackoff(idempotentBackoff),
                         RetryRule.builder()
                                  .onUnprocessed()
                                  .thenBackoff(unprocessedBackoff));

    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR));

    assertBackoff(retryRule.shouldRetry(ctx1, null)).isSameAs(idempotentBackoff);

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.POST, "/"));
    ctx2.logBuilder().responseHeaders(ResponseHeaders.of(HttpStatus.INTERNAL_SERVER_ERROR));
    assertBackoff(retryRule.shouldRetry(ctx2, null)).isNull();

    final ClientRequestContext ctx3 = ClientRequestContext.of(HttpRequest.of(HttpMethod.PUT, "/"));
    assertBackoff(retryRule.shouldRetry(ctx3, new ClosedChannelException())).isSameAs(idempotentBackoff);

    final ClientRequestContext ctx4 = ClientRequestContext.of(HttpRequest.of(HttpMethod.PUT, "/"));
    assertBackoff(retryRule.shouldRetry(ctx4,
                                        UnprocessedRequestException.of(new ClosedChannelException())))
            .isSameAs(unprocessedBackoff);
}
 
Example 10
Source File: RequestScopedMdcTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void get() {
    final ServiceRequestContext ctx = newContext();
    RequestScopedMdc.put(ctx, "foo", "1");
    assertThat(RequestScopedMdc.get(ctx, "foo")).isEqualTo("1");
    assertThat(MDC.get("foo")).isNull();

    try (SafeCloseable ignored = ctx.push()) {
        assertThat(MDC.get("foo")).isEqualTo("1");
        // Request-scoped property should have priority over thread-local one.
        MDC.put("foo", "2");
        assertThat(MDC.get("foo")).isEqualTo("1");

        // A client context should expose the properties from the root context.
        final ClientRequestContext cctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
        assertThat(cctx.root()).isSameAs(ctx);
        assertThat(RequestScopedMdc.get(cctx, "foo")).isEqualTo("1");

        // A client context can override the property from the root context,
        // but it shouldn't affect the root context's own property.
        RequestScopedMdc.put(cctx, "foo", "3");
        assertThat(RequestScopedMdc.get(ctx, "foo")).isEqualTo("1");
        assertThat(RequestScopedMdc.get(cctx, "foo")).isEqualTo("3");

        try (SafeCloseable ignored2 = cctx.push()) {
            // If both ctx and cctx do not have 'foo' set, thread-local property should be retrieved.
            RequestScopedMdc.remove(ctx, "foo");
            RequestScopedMdc.remove(cctx, "foo");
            assertThat(MDC.get("foo")).isEqualTo("2");
        }
    }
}
 
Example 11
Source File: DefaultRequestLogTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void setParentIdWhileAddingChild() {
    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    assertThat(ctx2.log().parent()).isNull();
    ctx1.logBuilder().addChild(ctx2.log());
    assertThat(ctx2.log().parent()).isEqualTo(ctx1.log());
    assertThat(ctx2.log().parent().context().id()).isEqualTo(ctx1.id());
}
 
Example 12
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 13
Source File: ClientRequestContextAdapterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void requestHeader() {
    final ClientRequestContext ctx = ClientRequestContext.of(
                    HttpRequest.of(RequestHeaders.of(HttpMethod.GET, "/", "foo", "bar")));
    ctx.logBuilder().endRequest();
    ctx.logBuilder().endResponse();

    final HttpClientRequest braveReq =
            ClientRequestContextAdapter.asHttpClientRequest(ctx,
                                                            ctx.request().headers().toBuilder());
    assertThat(braveReq.header("foo")).isEqualTo("bar");
    assertThat(braveReq.header("bar")).isNull();
}
 
Example 14
Source File: ClientRequestContextAdapterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void serializationFormat() {
    final ClientRequestContext ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx1.logBuilder().serializationFormat(SerializationFormat.UNKNOWN);
    ctx1.logBuilder().endRequest();
    ctx1.logBuilder().endResponse();

    assertThat(ClientRequestContextAdapter.serializationFormat(ctx1.log().ensureComplete()))
            .isEqualTo("unknown");

    final ClientRequestContext ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2.logBuilder().endRequest();
    ctx2.logBuilder().endResponse();
    assertThat(ClientRequestContextAdapter.serializationFormat(ctx2.log().ensureComplete())).isNull();
}
 
Example 15
Source File: AbstractEndpointSelectorTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void delayedSelection() {
    final DynamicEndpointGroup group = new DynamicEndpointGroup();
    final ClientRequestContext ctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final CompletableFuture<Endpoint> future = newSelector(group).select(ctx, ctx.eventLoop(),
                                                                         Long.MAX_VALUE);
    assertThat(future).isNotDone();

    final Endpoint endpoint = Endpoint.of("foo");
    group.addEndpoint(endpoint);
    assertThat(future.join()).isSameAs(endpoint);
}
 
Example 16
Source File: LegacyCentralDogmaTimeoutSchedulerTest.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
private static ClientRequestContext newClientContext(RpcRequest req) {
    final ClientRequestContext ctx = ClientRequestContext.of(
            HttpRequest.of(HttpMethod.POST, "/cd/thrift/v1"));
    return ctx;
}
 
Example 17
Source File: RetryRuleWithContentBuilderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void setUp() {
    ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
}
 
Example 18
Source File: StickyEndpointSelectionStrategyTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static ClientRequestContext contextWithHeader(String k, String v) {
    return ClientRequestContext.of(HttpRequest.of(RequestHeaders.of(HttpMethod.GET, "/",
                                                                    HttpHeaderNames.of(k), v)));
}
 
Example 19
Source File: CircuitBreakerRuleWithContentBuilderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void setUp() {
    ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
}
 
Example 20
Source File: CircuitBreakerRuleBuilderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void setUp() {
    ctx1 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    ctx2 = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
}