Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class IterableApi {

final IterableRemoteRetryConfig remoteRetryConfig = new IterableRemoteRetryConfig();
IterableApiClient apiClient = new IterableApiClient(new IterableApiAuthProvider(),
IterableRequestDispatchers.sdk(), remoteRetryConfig);
IterableRequestDispatchers.sdk(), remoteRetryConfig, () -> config.networkRetryPolicy);
final ApiEndpointClassification apiEndpointClassification = new ApiEndpointClassification();
private static final UnknownUserMerge unknownUserMerge = new UnknownUserMerge();
private @Nullable UnknownUserManager unknownUserManager;
Expand Down Expand Up @@ -207,13 +207,6 @@ static void loadLastSavedConfiguration(Context context) {
sharedInstance.remoteRetryConfig.setAutoRetryEnabled(sharedPref.getBoolean(IterableConstants.SHARED_PREFS_AUTO_RETRY_KEY, false));
}

/**
* Returns whether auto-retry on JWT failure is enabled, as determined by remote configuration.
*/
boolean isAutoRetryOnJwtFailure() {
return remoteRetryConfig.isAutoRetryEnabled();
}

/**
* Set the notification icon with the given iconName.
* @param context
Expand Down Expand Up @@ -990,7 +983,7 @@ static void initializeForPush(@Nullable Context context) {
void setRequestDispatcher(IterableRequestDispatcher requestDispatcher) {
apiClient = new IterableApiClient(new IterableApiAuthProvider(),
IterableRequestDispatchers.same(Objects.requireNonNull(requestDispatcher)),
remoteRetryConfig);
remoteRetryConfig, () -> config.networkRetryPolicy);
}
//endregion

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class IterableApiClient {
private final @NonNull AuthProvider authProvider;
private final @NonNull IterableRequestDispatchers requestDispatchers;
private final @NonNull IterableRemoteRetryConfig remoteRetryConfig;
private final @NonNull NetworkRetryPolicyProvider networkRetryPolicyProvider;
private final OnlineRequestProcessor pushRegistrationRequestProcessor;
// A newer push action invalidates retries from earlier registration or disable requests.
private final AtomicLong pushRegistrationRequestGeneration = new AtomicLong();
Expand All @@ -47,16 +48,26 @@ interface AuthProvider {
void resetAuth();
}

interface NetworkRetryPolicyProvider {
@NonNull
IterableNetworkRetryPolicy getNetworkRetryPolicy();
}

IterableApiClient(
@NonNull AuthProvider authProvider,
@NonNull IterableRequestDispatchers requestDispatchers,
@NonNull IterableRemoteRetryConfig remoteRetryConfig
@NonNull IterableRemoteRetryConfig remoteRetryConfig,
@NonNull NetworkRetryPolicyProvider networkRetryPolicyProvider
) {
this.authProvider = authProvider;
this.requestDispatchers = requestDispatchers;
this.remoteRetryConfig = remoteRetryConfig;
pushRegistrationRequestProcessor =
new OnlineRequestProcessor(requestDispatchers.push());
this.networkRetryPolicyProvider = networkRetryPolicyProvider;
pushRegistrationRequestProcessor = newOnlineRequestProcessor(requestDispatchers.push());
}

private OnlineRequestProcessor newOnlineRequestProcessor(IterableRequestDispatcher dispatcher) {
return new OnlineRequestProcessor(dispatcher, networkRetryPolicyProvider, remoteRetryConfig);
}

@NonNull
Expand All @@ -66,7 +77,7 @@ IterableRemoteRetryConfig getRemoteRetryConfig() {

private synchronized RequestProcessor getRequestProcessor() {
if (requestProcessor == null) {
requestProcessor = new OnlineRequestProcessor(requestDispatchers.online());
requestProcessor = newOnlineRequestProcessor(requestDispatchers.online());
}
return requestProcessor;
}
Expand All @@ -76,7 +87,7 @@ synchronized void setOfflineProcessingEnabled(boolean offlineMode) {
&& offlineRequestProcessor == null
&& !hasPendingOfflineRequests()) {
if (!(requestProcessor instanceof OnlineRequestProcessor)) {
requestProcessor = new OnlineRequestProcessor(requestDispatchers.online());
requestProcessor = newOnlineRequestProcessor(requestDispatchers.online());
}
return;
}
Expand All @@ -89,7 +100,7 @@ synchronized void setOfflineProcessingEnabled(boolean offlineMode) {
if (offlineMode) {
requestProcessor = persistentOfflineRequestProcessor;
} else if (!(requestProcessor instanceof OnlineRequestProcessor)) {
requestProcessor = new OnlineRequestProcessor(requestDispatchers.online());
requestProcessor = newOnlineRequestProcessor(requestDispatchers.online());
}
}

Expand All @@ -98,7 +109,9 @@ private OfflineRequestProcessor getOfflineRequestProcessor() {
offlineRequestProcessor = new OfflineRequestProcessor(
authProvider.getContext(),
requestDispatchers.offlineImmediate(),
requestDispatchers.offlineStored()
requestDispatchers.offlineStored(),
remoteRetryConfig,
networkRetryPolicyProvider
Comment thread
franco-zalamena-iterable marked this conversation as resolved.
Resolved
);
}
return offlineRequestProcessor;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;

class IterableNetworkRetryClassifier {
static final String ERROR_CODE_INVALID_JWT_PAYLOAD = "InvalidJwtPayload";
static final String ERROR_CODE_MISSING_JWT_PAYLOAD = "BadAuthorizationHeader";
static final String ERROR_CODE_JWT_USER_IDENTIFIERS_MISMATCHED = "JwtUserIdentifiersMismatched";

enum Outcome {
SUCCESS,
Expand All @@ -30,7 +34,7 @@ static Outcome classify(int responseCode, @Nullable JSONObject json) {
if (responseCode == 0 || (responseCode >= 500 && responseCode < 600)) {
return Outcome.RETRIABLE;
}
if (responseCode == 401 && IterableRequestTask.matchesJWTErrorCodes(json)) {
if (responseCode == 401 && matchesJWTErrorCodes(json)) {
return Outcome.AUTH;
}
return Outcome.TERMINAL;
Expand Down Expand Up @@ -62,4 +66,18 @@ boolean shouldRetry(@NonNull Outcome outcome, int failedAttempt, long firstAttem
long delayMillis() {
return policy.getBackoffPolicy().delayMillis();
}

static boolean matchesJWTErrorCodes(@Nullable JSONObject json) {
return matchesErrorCode(json, ERROR_CODE_INVALID_JWT_PAYLOAD)
|| matchesErrorCode(json, ERROR_CODE_MISSING_JWT_PAYLOAD)
|| matchesErrorCode(json, ERROR_CODE_JWT_USER_IDENTIFIERS_MISMATCHED);
}

private static boolean matchesErrorCode(@Nullable JSONObject json, String errorCode) {
try {
return json != null && json.has("code") && json.getString("code").equals(errorCode);
} catch (JSONException e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
Expand All @@ -19,6 +20,10 @@ interface ResponseHandler {
void onResponse(IterableApiResponse response);
}

interface Clock {
long elapsedRealtimeMillis();
}

private static final RetryScheduler SDK_RETRY_SCHEDULER =
(runnable, delayMs) ->
new Handler(Looper.getMainLooper()).postDelayed(runnable, delayMs);
Expand All @@ -38,6 +43,7 @@ interface ResponseHandler {
private final Executor retryExecutor;
private final Executor callbackExecutor;
private final RetryScheduler retryScheduler;
private final Clock clock;

static IterableRequestDispatcher online() {
return ONLINE_DISPATCHER;
Expand Down Expand Up @@ -68,11 +74,26 @@ static IterableRequestDispatcher offlineStored() {
Executor retryExecutor,
Executor callbackExecutor,
RetryScheduler retryScheduler
) {
this(requestExecutor, retryExecutor, callbackExecutor, retryScheduler, SystemClock::elapsedRealtime);
}

IterableRequestDispatcher(
Executor requestExecutor,
Executor retryExecutor,
Executor callbackExecutor,
RetryScheduler retryScheduler,
Clock clock
) {
this.requestExecutor = requestExecutor;
this.retryExecutor = retryExecutor;
this.callbackExecutor = callbackExecutor;
this.retryScheduler = retryScheduler;
this.clock = clock;
}

long elapsedRealtimeMillis() {
return clock.elapsedRealtimeMillis();
}

void execute(IterableApiRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,6 @@ class IterableRequestTask implements Runnable {
static final long RETRY_DELAY_MS = 2000; //2 seconds
static final int MAX_RETRY_COUNT = 5;

static final String ERROR_CODE_INVALID_JWT_PAYLOAD = "InvalidJwtPayload";
static final String ERROR_CODE_MISSING_JWT_PAYLOAD = "BadAuthorizationHeader";
static final String ERROR_CODE_JWT_USER_IDENTIFIERS_MISMATCHED = "JwtUserIdentifiersMismatched";
private final int retryCount;
private final IterableApiRequest iterableApiRequest;
private final IterableRequestDispatcher requestDispatcher;
Expand Down Expand Up @@ -229,13 +226,13 @@ static IterableApiResponse executeApiRequest(
// If getResponseCode() returned -1 (e.g. due to network inspector
// interference) but the response body contains JWT error codes,
// we can infer the actual response was a 401.
if (responseCode == -1 && matchesJWTErrorCodes(jsonResponse)) {
if (responseCode == -1 && IterableNetworkRetryClassifier.matchesJWTErrorCodes(jsonResponse)) {
responseCode = 401;
}

// Handle HTTP status codes
if (responseCode == 401) {
if (matchesJWTErrorCodes(jsonResponse)) {
if (IterableNetworkRetryClassifier.matchesJWTErrorCodes(jsonResponse)) {
apiResponse = IterableApiResponse.failure(responseCode, requestResult, jsonResponse, "JWT Authorization header error");
IterableApi.getInstance().getAuthManager().handleAuthFailure(iterableApiRequest.authToken, getMappedErrorCodeForMessage(jsonResponse));

Expand Down Expand Up @@ -303,7 +300,7 @@ private static void handleJwtAuthRetry(
IterableApiRequest iterableApiRequest,
IterableRequestDispatcher requestDispatcher
) {
boolean autoRetry = IterableApi.getInstance().isAutoRetryOnJwtFailure();
boolean autoRetry = iterableApiRequest.isAutoRetryOnJwtFailure();
if (autoRetry && iterableApiRequest.getProcessorType() == IterableApiRequest.ProcessorType.OFFLINE) {
IterableAuthManager authManager = IterableApi.getInstance().getAuthManager();
authManager.setIsLastAuthTokenValid(false);
Expand All @@ -330,14 +327,6 @@ private static String getBaseUrl() {
return baseUrl;
}

private static boolean matchesErrorCode(JSONObject jsonResponse, String errorCode) {
try {
return jsonResponse != null && jsonResponse.has("code") && jsonResponse.getString("code").equals(errorCode);
} catch (JSONException e) {
return false;
}
}

private static AuthFailureReason getMappedErrorCodeForMessage(JSONObject jsonResponse) {
try {
if (jsonResponse == null || !jsonResponse.has("msg")) {
Expand Down Expand Up @@ -372,10 +361,6 @@ private static AuthFailureReason getMappedErrorCodeForMessage(JSONObject jsonRes
}
}

static boolean matchesJWTErrorCodes(JSONObject jsonResponse) {
return matchesErrorCode(jsonResponse, ERROR_CODE_INVALID_JWT_PAYLOAD) || matchesErrorCode(jsonResponse, ERROR_CODE_MISSING_JWT_PAYLOAD) || matchesErrorCode(jsonResponse, ERROR_CODE_JWT_USER_IDENTIFIERS_MISMATCHED);
}

private static void logError(IterableApiRequest iterableApiRequest, String baseUrl, Exception e) {
IterableLogger.e(TAG, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" +
"Exception occurred for : " + baseUrl + iterableApiRequest.resourcePath);
Expand Down Expand Up @@ -490,6 +475,7 @@ class IterableApiRequest {
final String requestType;
final String authToken;
private @Nullable IterableRequestRetryState retryState;
private @Nullable IterableRemoteRetryConfig remoteRetryConfig;

private ProcessorType processorType = ProcessorType.ONLINE;
IterableHelper.IterableActionHandler legacyCallback;
Expand Down Expand Up @@ -529,6 +515,14 @@ void copyRetryStateFrom(@NonNull IterableApiRequest request) {
setRetryState(request.retryState);
}

void setRemoteRetryConfig(@Nullable IterableRemoteRetryConfig remoteRetryConfig) {
this.remoteRetryConfig = remoteRetryConfig;
}

boolean isAutoRetryOnJwtFailure() {
return remoteRetryConfig != null && remoteRetryConfig.isAutoRetryEnabled();
}

boolean canRetry() {
return retryState == null || retryState.canRetry();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class IterableTaskRunner implements IterableTaskStorage.TaskCreatedListener, Han
private HealthMonitor healthMonitor;
private ApiEndpointClassification classification;
private final IterableRequestDispatcher requestDispatcher;
private final IterableRemoteRetryConfig remoteRetryConfig;

private static final int RETRY_INTERVAL_SECONDS = 60;

Expand Down Expand Up @@ -51,13 +52,15 @@ interface TaskCompletedListener {
IterableNetworkConnectivityManager networkConnectivityManager,
HealthMonitor healthMonitor,
ApiEndpointClassification classification,
IterableRequestDispatcher requestDispatcher) {
IterableRequestDispatcher requestDispatcher,
IterableRemoteRetryConfig remoteRetryConfig) {
this.taskStorage = taskStorage;
this.activityMonitor = activityMonitor;
this.networkConnectivityManager = networkConnectivityManager;
this.healthMonitor = healthMonitor;
this.classification = classification;
this.requestDispatcher = requestDispatcher;
this.remoteRetryConfig = remoteRetryConfig;
networkThread.start();
handler = new Handler(networkThread.getLooper(), this);
taskStorage.addTaskCreatedListener(this);
Expand Down Expand Up @@ -165,7 +168,7 @@ private void processTasks() {
return;
}

boolean autoRetry = IterableApi.getInstance().isAutoRetryOnJwtFailure();
boolean autoRetry = remoteRetryConfig.isAutoRetryEnabled();

if (!networkConnectivityManager.isConnected()) {
return;
Expand Down Expand Up @@ -212,6 +215,7 @@ private void processTask(@NonNull IterableTask task, boolean autoRetry) {
null
);
request.setProcessorType(IterableApiRequest.ProcessorType.OFFLINE);
request.setRemoteRetryConfig(remoteRetryConfig);
requestInFlight = true;
requestDispatcher.executeForResponse(
request,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class OfflineRequestProcessor implements RequestProcessor {
private IterableTaskStorage taskStorage;
private HealthMonitor healthMonitor;
private final IterableRequestDispatcher immediateRequestDispatcher;
private final IterableApiClient.NetworkRetryPolicyProvider networkRetryPolicyProvider;
private final IterableRemoteRetryConfig remoteRetryConfig;

private static final Set<String> offlineApiSet = new HashSet<>(Arrays.asList(
IterableConstants.ENDPOINT_TRACK,
Expand All @@ -40,9 +42,13 @@ class OfflineRequestProcessor implements RequestProcessor {
OfflineRequestProcessor(
Context context,
IterableRequestDispatcher immediateRequestDispatcher,
IterableRequestDispatcher offlineRequestDispatcher
IterableRequestDispatcher offlineRequestDispatcher,
IterableRemoteRetryConfig remoteRetryConfig,
IterableApiClient.NetworkRetryPolicyProvider networkRetryPolicyProvider
) {
this.immediateRequestDispatcher = immediateRequestDispatcher;
this.networkRetryPolicyProvider = networkRetryPolicyProvider;
this.remoteRetryConfig = remoteRetryConfig;
IterableNetworkConnectivityManager networkConnectivityManager = IterableNetworkConnectivityManager.sharedInstance(context);
taskStorage = IterableTaskStorage.sharedInstance(context);
healthMonitor = new HealthMonitor(taskStorage);
Expand All @@ -52,7 +58,8 @@ class OfflineRequestProcessor implements RequestProcessor {
networkConnectivityManager,
healthMonitor,
classification,
offlineRequestDispatcher);
offlineRequestDispatcher,
remoteRetryConfig);
taskScheduler = new TaskScheduler(
taskStorage,
taskRunner,
Expand Down Expand Up @@ -86,13 +93,17 @@ void dispose() {
IterableTaskRunner iterableTaskRunner,
IterableTaskStorage storage,
HealthMonitor mockHealthMonitor,
IterableRequestDispatcher immediateRequestDispatcher
IterableRequestDispatcher immediateRequestDispatcher,
IterableRemoteRetryConfig remoteRetryConfig,
IterableApiClient.NetworkRetryPolicyProvider networkRetryPolicyProvider
) {
taskRunner = iterableTaskRunner;
taskScheduler = scheduler;
taskStorage = storage;
healthMonitor = mockHealthMonitor;
this.immediateRequestDispatcher = immediateRequestDispatcher;
this.networkRetryPolicyProvider = networkRetryPolicyProvider;
this.remoteRetryConfig = remoteRetryConfig;
}

@Override
Expand All @@ -112,6 +123,8 @@ public void processPostRequest(@Nullable String apiKey, @NonNull String resource
IterableApiRequest request = new IterableApiRequest(apiKey, resourcePath, json, IterableApiRequest.POST, authToken, onSuccess, onFailure);
if (isRequestOfflineCompatible(request.resourcePath) && healthMonitor.canSchedule()) {
request.setProcessorType(IterableApiRequest.ProcessorType.OFFLINE);
// TaskScheduler sends this request directly if it cannot be stored.
request.setRemoteRetryConfig(remoteRetryConfig);
taskScheduler.scheduleTask(request, onSuccess, onFailure);
} else {
immediateRequestDispatcher.execute(request);
Expand Down
Loading
Loading