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

Exponential backoff api wrapper #328

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
55 changes: 55 additions & 0 deletions sdk/src/main/java/io/radar/sdk/RadarAPIRetryWrapper.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package io.radar.sdk

import android.content.Context
import android.os.Handler
import android.os.Looper
import org.json.JSONObject
import kotlin.math.pow
import kotlin.random.Random

internal class RadarAPIRetryWrapper(private var radarAPIHelper: RadarApiHelper) {
private val handler = Handler(Looper.getMainLooper())
private val maxRetries = 5
private val timeout = 200
private val timeoutBase = 2.0


internal fun requestWithRetry(context: Context,
method: String,
path: String,
headers: Map<String, String>?,
params: JSONObject?,
sleep: Boolean,
callback: RadarApiHelper.RadarApiCallback? = null,
extendedTimeout: Boolean = false,
stream: Boolean = false,
logPayload: Boolean = true,
verified: Boolean = false,
retriesLeft: Int = maxRetries) {
val retriesLeftSanitized = minOf(retriesLeft, maxRetries)
if (retriesLeftSanitized == 0) {
handler.post {
callback?.onComplete(Radar.RadarStatus.ERROR_UNKNOWN)
}
return
}
val newCallback = object : RadarApiHelper.RadarApiCallback {
override fun onComplete(status: Radar.RadarStatus, res: JSONObject?) {
if ((status !== Radar.RadarStatus.SUCCESS && retriesLeftSanitized === 1) || (status === Radar.RadarStatus.SUCCESS)) {
handler.post {
callback?.onComplete(status, res)
}
} else {
// Calculate retry duration with jitter.
val retryDuration = (timeout * timeoutBase.pow((maxRetries - retriesLeft + 1).toDouble()) + Random.nextInt(1000)).toLong()
Thread.sleep(retryDuration)
requestWithRetry(context, method, path, headers, params, sleep, callback, extendedTimeout, stream, logPayload, verified, retriesLeftSanitized - 1)
}
}
}
radarAPIHelper.request(context, method, path, headers, params, sleep, newCallback, extendedTimeout, stream, logPayload, verified)

}


}
5 changes: 3 additions & 2 deletions sdk/src/main/java/io/radar/sdk/RadarApiClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import java.util.*
internal class RadarApiClient(
private val context: Context,
private var logger: RadarLogger,
internal var apiHelper: RadarApiHelper = RadarApiHelper(logger)
internal var apiHelper: RadarApiHelper = RadarApiHelper(logger),
private var apiRetryWrapper: RadarAPIRetryWrapper = RadarAPIRetryWrapper(apiHelper)
) {

interface RadarTrackApiCallback {
Expand Down Expand Up @@ -126,7 +127,7 @@ internal class RadarApiClient(
val path = "v1/config?${queryParams}"
val headers = headers(publishableKey)

apiHelper.request(context, "GET", path, headers, null, false, object : RadarApiHelper.RadarApiCallback {
apiRetryWrapper.requestWithRetry(context, "GET", path, headers, null, false, object : RadarApiHelper.RadarApiCallback {
override fun onComplete(status: RadarStatus, res: JSONObject?) {
if (status == RadarStatus.SUCCESS) {
Radar.flushLogs()
Expand Down
24 changes: 24 additions & 0 deletions sdk/src/test/java/io/radar/sdk/RadarApiHelperMock.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ internal class RadarApiHelperMock : RadarApiHelper() {
*/
internal var mockResponses: MutableMap<String, JSONObject> = mutableMapOf()

var retryCounter = 0


override fun request(
context: Context,
method: String,
Expand All @@ -32,6 +35,27 @@ internal class RadarApiHelperMock : RadarApiHelper() {
logPayload: Boolean,
verified: Boolean
) {
// Use params to test for retry and backoff
if (params != null && params.has("retry")) {

val retry = params.get("retry")
if (retry is Int) {

retryCounter++
if (retryCounter < retry) {
callback?.onComplete(Radar.RadarStatus.ERROR_UNKNOWN)
return
} else {
val successJson = JSONObject()
successJson.put("successOn", retryCounter)
callback?.onComplete(Radar.RadarStatus.SUCCESS,successJson)
retryCounter = 0
return
}

}

}
// Use the entry in the mockResponses map, if any.
if (mockResponses.containsKey(path)) {
callback?.onComplete(mockStatus, mockResponses[path])
Expand Down
135 changes: 135 additions & 0 deletions sdk/src/test/java/io/radar/sdk/util/RadarAPIRetryTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package io.radar.sdk.util

import android.content.Context
import android.os.Build
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.radar.sdk.Radar
import io.radar.sdk.RadarAPIRetryWrapper
import io.radar.sdk.RadarApiHelper
import io.radar.sdk.RadarApiHelperMock
import io.radar.sdk.RadarTest
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowLooper
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

@RunWith(AndroidJUnit4::class)
@Config(sdk = [Build.VERSION_CODES.P])
class RadarAPIRetryTest {

companion object {
private val apiHelperMock = RadarApiHelperMock()
private val apiRetryWrapper = RadarAPIRetryWrapper(apiHelperMock)
private val context: Context = ApplicationProvider.getApplicationContext()

}

@Before
fun setUp() {
apiHelperMock.retryCounter = 0
}


@Test
fun testSuccessOnFirstTry() {
val latch = CountDownLatch(1)
val paramJson = JSONObject()
paramJson.put("retry", 1)
var callbackStatus: Radar.RadarStatus? = null
var successOn: Int? = null
val testCallback = object : RadarApiHelper.RadarApiCallback {
override fun onComplete(status: Radar.RadarStatus, res: JSONObject?) {
callbackStatus = status
successOn = res?.getInt("successOn")
latch.countDown()
}
}
apiRetryWrapper.requestWithRetry(context, "GET", "http://testPath", null, paramJson, false, testCallback)

ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
latch.await(RadarTest.LATCH_TIMEOUT, TimeUnit.SECONDS)
assertEquals(Radar.RadarStatus.SUCCESS, callbackStatus)
assertEquals(successOn,1)
}

@Test
fun testSuccessOnThirdTry() {
val latch = CountDownLatch(1)
val paramJson = JSONObject()
paramJson.put("retry", 3)
var callbackStatus: Radar.RadarStatus? = null
var successOn: Int? = null
val testCallback = object : RadarApiHelper.RadarApiCallback {
override fun onComplete(status: Radar.RadarStatus, res: JSONObject?) {
callbackStatus = status
successOn = res?.getInt("successOn")
latch.countDown()
}
}
apiRetryWrapper.requestWithRetry(context, "GET", "http://testPath", null, paramJson, false, testCallback)

ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
latch.await(RadarTest.LATCH_TIMEOUT, TimeUnit.SECONDS)
assertEquals(Radar.RadarStatus.SUCCESS, callbackStatus)
assertEquals(successOn,3)

}

@Test
fun testSuccessOnLastTry() {
val latch = CountDownLatch(1)
val paramJson = JSONObject()
paramJson.put("retry", 5)
var callbackStatus: Radar.RadarStatus? = null
var successOn: Int? = null
//create a mock callback
val testCallback = object : RadarApiHelper.RadarApiCallback {
override fun onComplete(status: Radar.RadarStatus, res: JSONObject?) {
callbackStatus = status
successOn = res?.getInt("successOn")
latch.countDown()
}
}
apiRetryWrapper.requestWithRetry(context, "GET", "http://testPath", null, paramJson, false, testCallback)

ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
latch.await(RadarTest.LATCH_TIMEOUT, TimeUnit.SECONDS)
assertEquals(Radar.RadarStatus.SUCCESS, callbackStatus)
assertEquals(successOn,5)

}

@Test
fun testFailure() {
val latch = CountDownLatch(1)
val paramJson = JSONObject()
paramJson.put("retry", 6)
var callbackStatus: Radar.RadarStatus? = null
var successOn: Int? = null
//create a mock callback
val testCallback = object : RadarApiHelper.RadarApiCallback {
override fun onComplete(status: Radar.RadarStatus, res: JSONObject?) {
callbackStatus = status
successOn = res?.getInt("successOn")
latch.countDown()
}
}
apiRetryWrapper.requestWithRetry(context, "GET", "http://testPath", null, paramJson, false, testCallback)

ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
latch.await(RadarTest.LATCH_TIMEOUT, TimeUnit.SECONDS)
assertEquals(Radar.RadarStatus.ERROR_UNKNOWN, callbackStatus)
assertNull(successOn)

}


}