Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -752,67 +752,18 @@ void retryableError_tooManyAttempts() {
assertThat(attempts).hasValue(2);
}

@Test
void retryableError_retryAfterHonored() {
addHttpResponse(502, "0");

// Configure a large enough initial backoff so the elapsed time proves Retry-After is honored
// instead of waiting for the retry policy delay.
try (TelemetryExporter<T> exporter =
exporterBuilder()
.setEndpoint(server.httpUri() + path)
.setRetryPolicy(
RetryPolicy.builder()
.setMaxAttempts(2)
.setInitialBackoff(Duration.ofSeconds(1))
.setMaxBackoff(Duration.ofSeconds(1))
.build())
.build()) {
long startTimeNanos = System.nanoTime();
assertThat(
exporter
.export(Collections.singletonList(generateFakeTelemetry()))
.join(10, TimeUnit.SECONDS)
.isSuccess())
.isTrue();
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTimeNanos);

assertThat(attempts).hasValue(2);
assertThat(elapsedMillis).isLessThan(750L);
}
}

@Test
void retryableError_malformedRetryAfterFallsBack() {
addHttpResponse(503, "not-a-retry-after");
@ParameterizedTest
@ValueSource(strings = {"0", "not-a-retry-after"})
void retryableError_retryAfter(String retryAfter) {
addHttpResponse(502, retryAfter);

// Configure a large enough initial backoff so the elapsed time proves we fell back to the
// retry policy rather than the (malformed) Retry-After header.
try (TelemetryExporter<T> exporter =
exporterBuilder()
.setEndpoint(server.httpUri() + path)
.setRetryPolicy(
RetryPolicy.builder()
.setMaxAttempts(2)
.setInitialBackoff(Duration.ofMillis(300))
.setMaxBackoff(Duration.ofMillis(300))
.build())
.build()) {
long startTimeNanos = System.nanoTime();
assertThat(
exporter
.export(Collections.singletonList(generateFakeTelemetry()))
.join(10, TimeUnit.SECONDS)
.isSuccess())
.isTrue();
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTimeNanos);

assertThat(attempts).hasValue(2);
// The malformed Retry-After header should be ignored, so the retry must wait at least a
// noticeable portion of the configured 300ms backoff. Keep a generous upper bound to avoid
// flaking in slow CI environments.
assertThat(elapsedMillis).isBetween(100L, 2_000L);
}
assertThat(
exporter
.export(Collections.singletonList(generateFakeTelemetry()))
.join(10, TimeUnit.SECONDS)
.isSuccess())
.isTrue();
assertThat(attempts).hasValue(2);
}

@ParameterizedTest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,11 @@ private static Throwable unwrap(Throwable throwable) {

// Visible for testing
HttpResponse sendInternal(MessageWriter requestBodyWriter) throws IOException {
return sendInternal(requestBodyWriter, TimeUnit.NANOSECONDS::sleep);
}

// Visible for testing
HttpResponse sendInternal(MessageWriter requestBodyWriter, Sleeper sleeper) throws IOException {
long startTimeNanos = System.nanoTime();
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder().uri(endpoint).timeout(timeout);
Map<String, List<String>> headers = headerSupplier.get();
Expand Down Expand Up @@ -263,7 +268,7 @@ HttpResponse sendInternal(MessageWriter requestBodyWriter) throws IOException {
nextBackoffNanos = (long) (currentBackoffNanos * retryPolicy.getBackoffMultiplier());
retryDelayNanos = OptionalLong.empty();
try {
TimeUnit.NANOSECONDS.sleep(backoffNanos);
sleeper.sleep(backoffNanos);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break; // Break out and return response or throw
Expand Down Expand Up @@ -505,4 +510,9 @@ private CompletableResultCode closeClient() {
}
return CompletableResultCode.ofSuccess();
}

@FunctionalInterface
interface Sleeper {
void sleep(long delayNanos) throws InterruptedException;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,17 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import javax.net.ssl.SSLException;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
Expand All @@ -63,6 +68,7 @@ class JdkHttpSenderTest {
private final HttpClient realHttpClient =
HttpClient.newBuilder().connectTimeout(Duration.ofMillis(10)).build();
@Mock private HttpClient mockHttpClient;
@Mock private JdkHttpSender.Sleeper sleeper;
private JdkHttpSender sender;

@BeforeEach
Expand Down Expand Up @@ -205,6 +211,63 @@ void sendInternal_RetryableIoException() throws IOException, InterruptedExceptio
verify(mockHttpClient, times(2)).send(any(), any());
}

@ParameterizedTest
@MethodSource("retryAfterArgs")
@SuppressWarnings("unchecked")
void sendInternal_retryAfter(String retryAfter, long minDelayNanos, long maxDelayNanos)
throws IOException, InterruptedException {
java.net.http.HttpResponse<InputStream> retryableResponse =
mock(java.net.http.HttpResponse.class);
when(retryableResponse.statusCode()).thenReturn(502);
when(retryableResponse.body()).thenReturn(new ByteArrayInputStream(new byte[0]));
when(retryableResponse.headers())
.thenReturn(
HttpHeaders.of(
Collections.singletonMap("Retry-After", Collections.singletonList(retryAfter)),
(a, b) -> true));
java.net.http.HttpResponse<InputStream> successResponse =
mock(java.net.http.HttpResponse.class);
when(successResponse.statusCode()).thenReturn(200);
when(successResponse.body()).thenReturn(new ByteArrayInputStream(new byte[0]));
when(successResponse.headers())
.thenReturn(HttpHeaders.of(Collections.emptyMap(), (a, b) -> true));
doReturn(retryableResponse, successResponse).when(mockHttpClient).send(any(), any());

JdkHttpSender testSender =
new JdkHttpSender(
mockHttpClient,
URI.create("http://localhost"),
"text/plain",
null,
Duration.ofMinutes(1),
Collections::emptyMap,
RetryPolicy.builder()
.setMaxAttempts(2)
.setInitialBackoff(Duration.ofSeconds(1))
.setMaxBackoff(Duration.ofSeconds(1))
.build(),
null,
Long.MAX_VALUE);
try {
assertThat(testSender.sendInternal(new NoOpRequestBodyWriter(), sleeper).getStatusCode())
.isEqualTo(200);
verify(mockHttpClient, times(2)).send(any(), any());
ArgumentCaptor<Long> delayNanos = ArgumentCaptor.forClass(Long.class);
verify(sleeper).sleep(delayNanos.capture());
assertThat(delayNanos.getValue()).isBetween(minDelayNanos, maxDelayNanos);
} finally {
testSender.shutdown();
}
}

private static Stream<Arguments> retryAfterArgs() {
return Stream.of(
Arguments.argumentSet("zero delay", "0", 0L, 0L),
Arguments.argumentSet("nonzero delay", "2", 2_000_000_000L, 2_000_000_000L),
Arguments.argumentSet(
"malformed header", "not-a-retry-after", 800_000_000L, 1_200_000_000L));
}

@Test
void sendInternal_NonRetryableException() throws IOException, InterruptedException {
doThrow(new SSLException("unknown error")).when(mockHttpClient).send(any(), any());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ public OkHttpHttpSender(
this.maxResponseBodySize = maxResponseBodySize;
}

private static OptionalLong retryDelayNanos(Response response) {
// Visible for testing
static OptionalLong retryDelayNanos(Response response) {
return RetryUtil.retryAfterNanos(response.header("Retry-After"));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension;
import io.opentelemetry.sdk.common.export.RetryPolicy;
import java.io.IOException;
Expand Down Expand Up @@ -204,33 +205,42 @@ public Void answer(InvocationOnMock invocation) throws Throwable {
}
}

@Test
void retryDelayOverride() throws Exception {
succeedOnAttempt(2);
doNothing().when(sleeper).sleep(anyLong());
@ParameterizedTest
@MethodSource("retryAfterArgs")
void retryAfter(String retryAfter, long expectedDelayNanos) throws Exception {
server.enqueue(
HttpResponse.of(
ResponseHeaders.builder(HttpStatus.BAD_GATEWAY)
.add("Retry-After", retryAfter)
.build()));
server.enqueue(HttpResponse.of(HttpStatus.OK));

RetryInterceptor retryInterceptor =
new RetryInterceptor(
RetryPolicy.builder()
.setBackoffMultiplier(1.6)
.setInitialBackoff(Duration.ofSeconds(1))
.setMaxBackoff(Duration.ofSeconds(2))
.setMaxAttempts(5)
.setRetryExceptionPredicate(retryExceptionPredicate)
.setMaxBackoff(Duration.ofSeconds(1))
.setMaxAttempts(2)
.build(),
r -> !r.isSuccessful(),
response -> OptionalLong.of(123L),
OkHttpHttpSender::isRetryable,
OkHttpHttpSender::retryDelayNanos,
retryExceptionPredicate,
sleeper,
random);
() -> 1.0d);
client = new OkHttpClient.Builder().addInterceptor(retryInterceptor).build();

try (Response response = sendRequest()) {
assertThat(response.isSuccessful()).isTrue();
}

verify(sleeper).sleep(123L);
verifyNoInteractions(random);
verify(sleeper).sleep(expectedDelayNanos);
}

private static Stream<Arguments> retryAfterArgs() {
return Stream.of(
Arguments.argumentSet("zero delay", "0", 0L),
Arguments.argumentSet("nonzero delay", "2", 2_000_000_000L),
Arguments.argumentSet("malformed header", "not-a-retry-after", 1_000_000_000L));
}

@Test
Expand Down
Loading