Skip to content

Commit

Permalink
Addressed multiple review comments from Ketan
Browse files Browse the repository at this point in the history
  • Loading branch information
rahulrvp committed Jul 29, 2024
1 parent 864dea0 commit cd58b8a
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 71 deletions.
36 changes: 7 additions & 29 deletions android-sdk/src/main/java/com/blueshift/Blueshift.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,8 @@
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
Expand Down Expand Up @@ -394,21 +392,14 @@ public void initialize(@NonNull Configuration configuration) {
handleAppOpenEvent(mContext);

InAppMessageIconFont.getInstance(mContext).updateFont(mContext);

handleInAppSync(mContext, mConfiguration);
InAppManager.fetchInAppFromServer(mContext, null);
}

void doNetworkConfigurations(Configuration configuration) {
BlueshiftNetworkConfiguration.INSTANCE.configureBasicAuthentication(configuration.getApiKey(), "");
BlueshiftNetworkConfiguration.INSTANCE.setDatacenter(configuration.getRegion());
}

void handleInAppSync(Context context, @NonNull Configuration configuration) {
if (!configuration.isInAppManualTriggerEnabled()) {
InAppManager.fetchInAppFromServer(context, null);
}
}

void handleAppOpenEvent(Context context) {
boolean isAutoAppOpenEnabled = BlueshiftUtils.isAutomaticAppOpenFiringEnabled(context);
boolean canSendAppOpenNow = BlueshiftUtils.canAutomaticAppOpenBeSentNow(context);
Expand Down Expand Up @@ -501,24 +492,6 @@ private boolean hasValidCredentials() {
return true;
}

/**
* Private method that receives params and send to server using request queue.
*
* @param params hash-map filled with parameters required for api call
* @param canBatchThisEvent flag to indicate if this event can be sent in bulk event API
* @return true if everything works fine, else false
*/
boolean sendEvent(String eventName, HashMap<String, Object> params, boolean canBatchThisEvent) {
String apiKey = BlueshiftUtils.getApiKey(mContext);
if (apiKey == null || apiKey.isEmpty()) {
BlueshiftLogger.e(LOG_TAG, "Please set a valid API key in your configuration object before initialization.");
return false;
} else {
BlueshiftEventManager.INSTANCE.trackEventWithData(mContext, eventName, params, canBatchThisEvent);
return true;
}
}

/**
* Method to send generic events
*
Expand All @@ -529,7 +502,12 @@ boolean sendEvent(String eventName, HashMap<String, Object> params, boolean canB
@SuppressWarnings("WeakerAccess")
public void trackEvent(@NonNull final String eventName, final HashMap<String, Object> params, final boolean canBatchThisEvent) {
if (Blueshift.isTrackingEnabled(mContext)) {
sendEvent(eventName, params, canBatchThisEvent);
String apiKey = BlueshiftUtils.getApiKey(mContext);
if (apiKey == null || apiKey.isEmpty()) {
BlueshiftLogger.e(LOG_TAG, "Please set a valid API key in your configuration object before initialization.");
} else {
BlueshiftEventManager.INSTANCE.trackEventWithData(mContext, eventName, params, canBatchThisEvent);
}
} else {
BlueshiftLogger.i(LOG_TAG, "Blueshift SDK's event tracking is disabled. Dropping event: " + eventName);
}
Expand Down
3 changes: 3 additions & 0 deletions android-sdk/src/main/java/com/blueshift/BlueshiftLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ public class BlueshiftLogger {

public static void setLogLevel(int logLevel) {
sLogLevel = logLevel;
if (logLevel > 0) {
com.blueshift.core.common.BlueshiftLogger.INSTANCE.setEnabled(true);
}
}

private static String prepareMessage(String tag, String message) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ object BlueshiftEventManager {

val isConnected = NetworkUtils.isConnected(context)
val blueshiftEvent = BlueshiftEvent(
eventName = eventName,
eventParams = eventParams,
timestamp = System.currentTimeMillis()
eventName = eventName, eventParams = eventParams, timestamp = System.currentTimeMillis()
)

// We should insert an event as batch event in two cases.
Expand Down Expand Up @@ -135,7 +133,6 @@ object BlueshiftEventManager {

val request = BlueshiftNetworkRequest(
url = BlueshiftAPI.bulkEventsURL(),
authorization = BlueshiftNetworkConfiguration.authorization,
authorizationRequired = true,
method = BlueshiftNetworkRequest.Method.POST,
body = bulkEventPayload,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,52 +42,66 @@ object BlueshiftNetworkRequestQueueManager {
}

suspend fun sync() {
// Prevent concurrent access to the sync method.
if (!isSyncing.compareAndSet(false, true)) {
BlueshiftLogger.d("$TAG: Sync is in-progress... Skipping the duplicate sync call.")
return
}
// Do not initiate the sync process if the authorization value is not available.
//
// Reason: If the authorization value is not set, it means that the SDK is not initialized
// properly. Without proper event api key in place, most of the events api calls would fail.
// So, we should not start the sync process until we get the authorization value set.
//
// Note: The campaign events doesn't require an event API key. However, syncing them without
// initializing the SDK would cause compliance issues. Hence we're blocking the sync completely
// until we get the authorization value set.
BlueshiftNetworkConfiguration.authorization?.let { basicAuth ->
// Prevent concurrent access to the sync method.
if (!isSyncing.compareAndSet(false, true)) {
BlueshiftLogger.d("$TAG: Sync is in-progress... Skipping the duplicate sync call.")
return
}

try {
while (true) {
// break the look when networkRequest is null.
val networkRequest = readNextRequest() ?: break
BlueshiftLogger.d("$TAG: Dequeue -> (Request ID: ${networkRequest.id})")
try {
while (true) {
// break the look when networkRequest is null.
val networkRequest = readNextRequest() ?: break
BlueshiftLogger.d("$TAG: Dequeue -> (Request ID: ${networkRequest.id})")

if (networkRequest.authorizationRequired) {
networkRequest.authorization = BlueshiftNetworkConfiguration.authorization
}
if (networkRequest.authorizationRequired) {
networkRequest.authorization = basicAuth
}

val response = networkRepository.makeNetworkRequest(networkRequest = networkRequest)
if (response.responseCode == HTTP_OK) {
BlueshiftLogger.d("$TAG: Remove -> (Request ID: ${networkRequest.id})")
deleteRequest(networkRequest)
} else if (response.responseCode == 0) {
BlueshiftLogger.d("$TAG: No internet connection. Pause sync!")
break
} else {
networkRequest.retryAttemptBalance--
val response = networkRepository.makeNetworkRequest(
networkRequest = networkRequest
)

if (networkRequest.retryAttemptBalance > 0) {
val intervalMs =
BlueshiftNetworkConfiguration.requestRetryIntervalInMilliseconds
if (response.responseCode == HTTP_OK) {
BlueshiftLogger.d("$TAG: Remove -> (Request ID: ${networkRequest.id})")
deleteRequest(networkRequest)
} else if (response.responseCode == 0) {
BlueshiftLogger.d("$TAG: No internet connection. Pause sync!")
break
} else {
networkRequest.retryAttemptBalance--

networkRequest.retryAttemptTimestamp =
System.currentTimeMillis() + intervalMs
if (networkRequest.retryAttemptBalance > 0) {
val intervalMs =
BlueshiftNetworkConfiguration.requestRetryIntervalInMilliseconds

// reset authorization to avoid storing it in db
networkRequest.authorization = null
networkRequest.retryAttemptTimestamp =
System.currentTimeMillis() + intervalMs

BlueshiftLogger.d("$TAG: Retry later -> (Request ID: ${networkRequest.id})")
updateRequest(networkRequest)
} else {
BlueshiftLogger.d("$TAG: Retry limit exceeded! Remove -> (Request ID: ${networkRequest.id})")
deleteRequest(networkRequest)
// reset authorization to avoid storing it in db
networkRequest.authorization = null

BlueshiftLogger.d("$TAG: Retry later -> (Request ID: ${networkRequest.id})")
updateRequest(networkRequest)
} else {
BlueshiftLogger.d("$TAG: Retry limit exceeded! Remove -> (Request ID: ${networkRequest.id})")
deleteRequest(networkRequest)
}
}
}
} finally {
isSyncing.set(false)
}
} finally {
isSyncing.set(false)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import android.util.Log

object BlueshiftLogger {
private const val TAG = "Blueshift"
var enabled = true
var enabled = false

fun d(message: String) {
if (enabled) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.blueshift.core

import android.util.Log
import com.blueshift.core.network.BlueshiftNetworkConfiguration
import com.blueshift.core.network.BlueshiftNetworkRequest
import com.blueshift.core.network.FakeNetworkRepoWithAPIError
import com.blueshift.core.network.FakeNetworkRepoWithAPISuccess
Expand Down Expand Up @@ -33,6 +34,8 @@ class BlueshiftNetworkRequestQueueManagerTest {

networkRequestRepo.insertRequest(networkRequest = networkRequest)
}

BlueshiftNetworkConfiguration.authorization = "basicAuth"
}

@After
Expand Down Expand Up @@ -137,4 +140,19 @@ class BlueshiftNetworkRequestQueueManagerTest {

assert(networkRequestRepo.requests.filter { it.retryAttemptTimestamp != 0L }.size == REQUEST_COUNT)
}

@Test
fun sync_ShouldNotMakeAnyChangesToTheQueueWhenAuthorizationIsNull() = runBlocking {
mockkStatic(Log::class)
every { Log.d(any(), any()) } returns 0

BlueshiftNetworkConfiguration.authorization = null

val requestQueueManager = BlueshiftNetworkRequestQueueManager
requestQueueManager.initialize(networkRequestRepo, FakeNetworkRepoWithAPISuccess())

requestQueueManager.sync()

assert(networkRequestRepo.requests.size == REQUEST_COUNT)
}
}

0 comments on commit cd58b8a

Please sign in to comment.