Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: retry interceptor now closes previous response #332

Merged
merged 2 commits into from
Mar 15, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions aws-android-sdk-appsync/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ dependencies {
testImplementation 'org.mockito:mockito-core:3.2.4'
testImplementation "com.amazonaws:aws-android-sdk-cognitoidentityprovider:$aws_version"
testImplementation project(':aws-android-sdk-appsync-runtime')
testImplementation("com.squareup.okhttp3:mockwebserver:4.3.1")
implementation ("com.amazonaws:aws-android-sdk-mobile-client:$aws_version@aar") { transitive = true }
implementation ("com.amazonaws:aws-android-sdk-auth-userpools:$aws_version@aar") { transitive = true }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public Response intercept(Chain chain) throws IOException {
if (retryAfterHeaderValue != null) {
try {
waitMillis = Integer.parseInt(retryAfterHeaderValue) * 1000;
response.close();
continue;
} catch (NumberFormatException e) {
Log.w(TAG, "Could not parse Retry-After header: " + retryAfterHeaderValue);
Expand All @@ -69,6 +70,7 @@ public Response intercept(Chain chain) throws IOException {
if ((response.code() >= 500 && response.code() < 600)
|| response.code() == 429 ) {
waitMillis = calculateBackoff(retryCount);
response.close();
continue;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/**
* Copyright 2021 Amazon.com,,
* Inc. or its affiliates. All Rights Reserved.
* <p>
* SPDX-License-Identifier: Apache-2.0
*/

package com.amazonaws.mobileconnectors.appsync.retry;

import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;

import static org.junit.Assert.assertTrue;

/**
* Tests for retry interceptor.
*/
@RunWith(RobolectricTestRunner.class)
@Config(manifest = "AndroidManifest.xml")
public class RetryInterceptorTest {
public static final int TEST_TIMEOUT = 10;
private MockWebServer mockWebServer;
private OkHttpClient okHttpClient;

@Before
public void beforeEachTest() throws IOException {
mockWebServer = new MockWebServer();
mockWebServer.start(8888);

okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new RetryInterceptor())
.build();
}

@After
public void afterEachTest() throws IOException {
mockWebServer.shutdown();
}

/**
* Verify that everything works when the first attempt succeeds.
* @throws IOException Not expected
* @throws InterruptedException Not expected
*/
@Test
public void successfulRequestWithoutFailuresTest() throws IOException, InterruptedException {
mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\"result\":\"all good\""));

Request request = new Request.Builder()
.url("http://localhost:8888")
.method("POST", RequestBody.create("{}", MediaType.get("application/json")))
.build();

final AtomicBoolean successful = new AtomicBoolean(false);
final CountDownLatch requestLatch = new CountDownLatch(1);
okHttpClient.newCall(request).enqueue(new Callback() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we have the Await utility in this testcodebase? It would simplify cleanup this CountDownLatch/AtomicBoolean stuff.

(Same for the next test, too.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I started looking at that and unfortunately the Await utility is in the integration tests package. I was tinkering with moving it under the this package, but turned out to be more of a cluster than what it was worth. I'll leave it as is for now if that's OK

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can always just copy-paste it. It is unlikely to change so the code duplication is probably not worth optimizing for.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clipboard inheritance never fails me 🤣 The chain of callbacks made it a little 🤯 , but I think it looks a little cleaner.

2 line fix. 142 lines of unit tests. The CS gods are happy 😄

@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
requestLatch.countDown();
}

@Override
public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) throws IOException {
if (response.code() < 300) {
assertTrue(response.body().string().contains("all good"));
successful.set(true);
}
requestLatch.countDown();
}
});
requestLatch.await(TEST_TIMEOUT, TimeUnit.SECONDS);
assertTrue(successful.get());
}

/**
* Verify that retries happen successfully without leaving the previous response open.
* This test was created as a result of a Github issue
* https://github.com/awslabs/aws-mobile-appsync-sdk-android/issues/305.
* @throws IOException Not expected
* @throws InterruptedException Not expected
*/
@Test
public void successfulRequestWithFailuresTest() throws IOException, InterruptedException {
mockWebServer.enqueue(new MockResponse().setResponseCode(500).setBody("{\"error\":\"some exception\""));
mockWebServer.enqueue(new MockResponse().setResponseCode(501).setBody("{\"error\":\"another exception\"").setHeader("Retry-After", "1"));
mockWebServer.enqueue(new MockResponse().setResponseCode(500).setBody("{\"error\":\"some exception\""));
mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\"result\":\"all good\""));

Request request = new Request.Builder()
.url("http://localhost:8888")
.method("POST", RequestBody.create("{}", MediaType.get("application/json")))
.build();

final AtomicBoolean successful = new AtomicBoolean(false);
final CountDownLatch requestLatch = new CountDownLatch(1);
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
requestLatch.countDown();
}

@Override
public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) throws IOException {
if (response.code() < 300) {
assertTrue(response.body().string().contains("all good"));
successful.set(true);
}
requestLatch.countDown();
}
});
requestLatch.await(10, TimeUnit.SECONDS);
assertTrue(successful.get());
}
}