Skip to content

Commit d3dc925

Browse files
markvdouwMansi-mParticle
authored andcommitted
Changes for identity cache
1 parent 4172ee6 commit d3dc925

4 files changed

Lines changed: 86 additions & 23 deletions

File tree

android-core/src/main/java/com/mparticle/identity/IdentityApi.java

Lines changed: 48 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.mparticle.identity;
22

3-
import static com.mparticle.identity.MParticleIdentityClientImpl.IDENTITY_TIMEOUT;
4-
53
import android.annotation.SuppressLint;
64
import android.content.Context;
75
import android.os.Handler;
@@ -50,13 +48,18 @@ public class IdentityApi {
5048
MessageManager mMessageManager;
5149
KitManager mKitManager;
5250
private Internal mInternal = new Internal();
51+
private long timeoutSeconds = 0L;
5352

5453
MParticleUserDelegate mUserDelegate;
5554
private MParticleIdentityClient mApiClient;
5655

5756
Set<IdentityStateListener> identityStateListeners = new HashSet<IdentityStateListener>();
5857
private static Object lock = new Object();
5958

59+
public static final String LOGIN_CALL = "login";
60+
public static final String IDENTIFY_CALL = "identify";
61+
public static final String LOGOUT_CALL = "logout";
62+
6063
protected IdentityApi() {
6164
}
6265

@@ -169,6 +172,7 @@ public MParticleTask<IdentityApiResult> logout() {
169172
*/
170173
@NonNull
171174
public MParticleTask<IdentityApiResult> logout(@Nullable final IdentityApiRequest logoutRequest) {
175+
resetCache();
172176
return makeIdentityRequest(logoutRequest, new IdentityNetworkRequestRunnable() {
173177
@Override
174178
public IdentityHttpResponse request(IdentityApiRequest request) throws Exception {
@@ -179,7 +183,7 @@ public IdentityHttpResponse request(IdentityApiRequest request) throws Exception
179183
public void onPostExecute(IdentityApiResult result) {
180184
mKitManager.onLogoutCompleted(result.getUser(), logoutRequest);
181185
}
182-
}, false);
186+
}, false, LOGOUT_CALL);
183187
}
184188

185189
/**
@@ -207,14 +211,17 @@ public MParticleTask<IdentityApiResult> login(@Nullable final IdentityApiRequest
207211
return makeIdentityRequest(loginRequest, new IdentityNetworkRequestRunnable() {
208212
@Override
209213
public IdentityHttpResponse request(IdentityApiRequest request) throws Exception {
210-
return getApiClient().login(request);
214+
IdentityHttpResponse response = getApiClient().login(request);
215+
timeoutSeconds = response.getTimeout();
216+
Logger.debug("TIMEOUT - IDENTITY TIMEOUT SET (SEC): "+ timeoutSeconds);
217+
return response;
211218
}
212219

213220
@Override
214221
public void onPostExecute(IdentityApiResult result) {
215222
mKitManager.onLoginCompleted(result.getUser(), loginRequest);
216223
}
217-
}, true);
224+
}, true, LOGIN_CALL);
218225
}
219226

220227
/**
@@ -230,14 +237,17 @@ public MParticleTask<IdentityApiResult> identify(@Nullable final IdentityApiRequ
230237
return makeIdentityRequest(identifyRequest, new IdentityNetworkRequestRunnable() {
231238
@Override
232239
public IdentityHttpResponse request(IdentityApiRequest request) throws Exception {
233-
return getApiClient().identify(request);
240+
IdentityHttpResponse response = getApiClient().identify(request);
241+
timeoutSeconds = response.getTimeout();
242+
Logger.debug("TIMEOUT - IDENTITY TIMEOUT SET (SEC): "+ timeoutSeconds);
243+
return response;
234244
}
235245

236246
@Override
237247
public void onPostExecute(IdentityApiResult result) {
238248
mKitManager.onIdentifyCompleted(result.getUser(), identifyRequest);
239249
}
240-
}, true);
250+
}, true, IDENTIFY_CALL);
241251
}
242252

243253
/**
@@ -256,6 +266,7 @@ public BaseIdentityTask modify(@NonNull final IdentityApiRequest updateRequest)
256266
if (updateRequest.mpid == null) {
257267
updateRequest.mpid = mConfigManager.getMpid();
258268
}
269+
259270
if (Constants.TEMPORARY_MPID.equals(updateRequest.mpid)) {
260271
String message = "modify() requires a non-zero MPID, please make sure a MParticleUser is present before making a modify request.";
261272
if (devMode) {
@@ -270,10 +281,12 @@ public BaseIdentityTask modify(@NonNull final IdentityApiRequest updateRequest)
270281
@Override
271282
public void run() {
272283
try {
284+
resetCache();
273285
final IdentityHttpResponse result = getApiClient().modify(updateRequest);
274286
if (!result.isSuccessful()) {
275287
task.setFailed(result);
276288
} else {
289+
timeoutSeconds = result.getTimeout();
277290
MParticleUserDelegate.setUserIdentities(mUserDelegate, updateRequest.getUserIdentities(), updateRequest.mpid);
278291
task.setSuccessful(new IdentityApiResult(MParticleUserImpl.getInstance(mContext, updateRequest.mpid, mUserDelegate), null));
279292
new Handler(Looper.getMainLooper()).post(new Runnable() {
@@ -352,17 +365,25 @@ private void reset() {
352365
}
353366
}
354367

355-
private boolean shouldMakeRequest(IdentityApiRequest identityRequest, boolean acceptCachedResponse) {
368+
private boolean shouldMakeRequest(IdentityApiRequest identityRequest, boolean acceptCachedResponse, long lastIdentityCall) {
356369
if (!acceptCachedResponse) {
370+
Logger.debug("TIMEOUT - SHOULD MAKE REQUEST: TRUE");
357371
return true;
358372
}
359-
long lastIdentityCall = 0l;// TODO get from prefs
360-
boolean hasTimedOut = lastIdentityCall < System.currentTimeMillis() - IDENTITY_TIMEOUT; //TODO Check if the timeout should be dynamic based on server header
361-
MParticleUser user = getUser(identityRequest.mpid);
362-
if (hasTimedOut || isRequestDifferent(user, identityRequest)) {
363-
return true;
373+
boolean hasTimedOut = lastIdentityCall==-1L || (lastIdentityCall + (timeoutSeconds * 1000) > System.currentTimeMillis()) ;
374+
Logger.debug("TIMEOUT - REQUEST TIMED OUT: " + hasTimedOut);
375+
if (identityRequest != null && identityRequest.mpid != null) {
376+
MParticleUser user = getUser(identityRequest.mpid);
377+
if (hasTimedOut || isRequestDifferent(user, identityRequest)) {
378+
Logger.debug("TIMEOUT - SHOULD MAKE REQUEST: TRUE");
379+
return true;
380+
} else {
381+
Logger.debug("TIMEOUT - SHOULD MAKE REQUEST: FALSE");
382+
return false;
383+
}
364384
} else {
365-
return false;
385+
Logger.debug("TIMEOUT - SHOULD MAKE REQUEST: TRUE");
386+
return true;
366387
}
367388
}
368389

@@ -379,19 +400,27 @@ private boolean areIdentitiesDifferent(MParticleUser user, IdentityApiRequest id
379400
if (user != null) {
380401
Map<MParticle.IdentityType, String> userIdentities = user.getUserIdentities() != null ? user.getUserIdentities() : new HashMap<>();
381402
Map<MParticle.IdentityType, String> requestUserIdentities = identityApiRequest.getUserIdentities() != null ? identityApiRequest.getUserIdentities() : new HashMap<>();
403+
Logger.debug("TIMEOUT - USER IDENTITIES: " +userIdentities);
404+
Logger.debug("TIMEOUT - REQUEST USER IDENTITIES: " +requestUserIdentities);
405+
Logger.debug("TIMEOUT - RESULT DIFFERENT: " + !userIdentities.equals(requestUserIdentities));
382406
return !userIdentities.equals(requestUserIdentities);
383407
} else {
384408
return true;
385409
}
386410
}
387411

388-
private BaseIdentityTask makeIdentityRequest(IdentityApiRequest request, final IdentityNetworkRequestRunnable networkRequest, boolean acceptCachedResponse) {
412+
private void resetCache() {
413+
mConfigManager.resetIdentityTypeCall();
414+
}
415+
416+
private BaseIdentityTask makeIdentityRequest(IdentityApiRequest request, final IdentityNetworkRequestRunnable networkRequest, boolean acceptCachedResponse, String call) {
417+
long lastIdentityCallTime = mConfigManager.getLastIdentityTypeCall(call);
389418
if (request == null) {
390419
request = IdentityApiRequest.withEmptyUser().build();
391420
}
392421
final BaseIdentityTask task = new BaseIdentityTask();
393422
final IdentityApiRequest identityApiRequest = request;
394-
if (!shouldMakeRequest(identityApiRequest, acceptCachedResponse)) {
423+
if (!shouldMakeRequest(identityApiRequest, acceptCachedResponse, lastIdentityCallTime)) {
395424
//Set both current and prev user as the current one, no request was done.
396425
task.setSuccessful(new IdentityApiResult(getUser(identityApiRequest.mpid), getCurrentUser()));
397426
Logger.debug("Identity -Returning current user from cache");
@@ -419,6 +448,9 @@ public void run() {
419448
ConfigManager.setIdentityRequestInProgress(false);
420449
mUserDelegate.setUser(mContext, startingMpid, newMpid, identityApiRequest.getUserIdentities(), identityApiRequest.getUserAliasHandler(), isLoggedIn);
421450
final MParticleUser previousUser = startingMpid != newMpid ? getUser(startingMpid) : null;
451+
if (acceptCachedResponse) {
452+
mConfigManager.setLastIdentityTypeCall(call);
453+
}
422454
task.setSuccessful(new IdentityApiResult(MParticleUserImpl.getInstance(mContext, newMpid, mUserDelegate), previousUser));
423455
new Handler(Looper.getMainLooper()).post(new Runnable() {
424456
@Override

android-core/src/main/java/com/mparticle/identity/IdentityHttpResponse.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ public final class IdentityHttpResponse {
1818
private String context;
1919
private int httpCode;
2020
private boolean loggedIn;
21+
private long timeout = 0L;
2122

2223
@NonNull
2324
public static final String MPID = "mpid";
@@ -50,8 +51,9 @@ public IdentityHttpResponse(int code, @NonNull String errorString) {
5051
this.errors.add(new Error(UNKNOWN, errorString));
5152
}
5253

53-
public IdentityHttpResponse(int httpCode, @Nullable JSONObject jsonObject) throws JSONException {
54+
public IdentityHttpResponse(int httpCode, @Nullable JSONObject jsonObject, long identityTimeout) throws JSONException {
5455
this.httpCode = httpCode;
56+
this.timeout = identityTimeout;
5557
if (!MPUtility.isEmpty(jsonObject)) {
5658
if (jsonObject.has(MPID)) {
5759
this.mpId = Long.valueOf(jsonObject.getString(MPID));
@@ -92,6 +94,10 @@ public long getMpId() {
9294
return mpId;
9395
}
9496

97+
public long getTimeout() {
98+
return 30L;
99+
}
100+
95101
@Nullable
96102
public String getContext() {
97103
return context;

android-core/src/main/java/com/mparticle/identity/MParticleIdentityClientImpl.java

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ public class MParticleIdentityClientImpl extends MParticleBaseClientImpl impleme
5252
static final String DEVICE_APPLICATION_STAMP = "device_application_stamp";
5353
static final String KNOWN_IDENTITIES = "known_identities";
5454
static final String PREVIOUS_MPID = "previous_mpid";
55+
static final String IDENTITY_HEADER_TIMEOUT = "X-MP-Max-Age";
5556

5657
static final String NEW_VALUE = "new_value";
5758
static final String OLD_VALUE = "old_value";
@@ -81,10 +82,11 @@ public IdentityHttpResponse login(IdentityApiRequest request) throws JSONExcepti
8182
String url = connection.getURL().toString();
8283
InternalListenerManager.getListener().onNetworkRequestStarted(SdkListener.Endpoint.IDENTITY_LOGIN, url, jsonObject, request);
8384
connection = makeUrlRequest(Endpoint.IDENTITY, connection, jsonObject.toString(), false);
85+
String headerField = connection.getHeaderField(IDENTITY_HEADER_TIMEOUT);
8486
int responseCode = connection.getResponseCode();
8587
JSONObject response = MPUtility.getJsonResponse(connection);
8688
InternalListenerManager.getListener().onNetworkRequestFinished(SdkListener.Endpoint.IDENTITY_LOGIN, url, response, responseCode);
87-
return parseIdentityResponse(responseCode, response);
89+
return parseIdentityResponse(responseCode, response, headerField);
8890
}
8991

9092
public IdentityHttpResponse logout(IdentityApiRequest request) throws JSONException, IOException {
@@ -97,7 +99,7 @@ public IdentityHttpResponse logout(IdentityApiRequest request) throws JSONExcept
9799
int responseCode = connection.getResponseCode();
98100
JSONObject response = MPUtility.getJsonResponse(connection);
99101
InternalListenerManager.getListener().onNetworkRequestFinished(SdkListener.Endpoint.IDENTITY_LOGOUT, url, response, responseCode);
100-
return parseIdentityResponse(responseCode, response);
102+
return parseIdentityResponse(responseCode, response, "0");
101103
}
102104

103105
public IdentityHttpResponse identify(IdentityApiRequest request) throws JSONException, IOException {
@@ -107,10 +109,11 @@ public IdentityHttpResponse identify(IdentityApiRequest request) throws JSONExce
107109
String url = connection.getURL().toString();
108110
InternalListenerManager.getListener().onNetworkRequestStarted(SdkListener.Endpoint.IDENTITY_IDENTIFY, url, jsonObject, request);
109111
connection = makeUrlRequest(Endpoint.IDENTITY, connection, jsonObject.toString(), false);
112+
String headerField = connection.getHeaderField(IDENTITY_HEADER_TIMEOUT);
110113
int responseCode = connection.getResponseCode();
111114
JSONObject response = MPUtility.getJsonResponse(connection);
112115
InternalListenerManager.getListener().onNetworkRequestFinished(SdkListener.Endpoint.IDENTITY_IDENTIFY, url, response, responseCode);
113-
return parseIdentityResponse(responseCode, response);
116+
return parseIdentityResponse(responseCode, response, headerField);
114117
}
115118

116119
public IdentityHttpResponse modify(IdentityApiRequest request) throws JSONException, IOException {
@@ -125,9 +128,10 @@ public IdentityHttpResponse modify(IdentityApiRequest request) throws JSONExcept
125128
InternalListenerManager.getListener().onNetworkRequestStarted(SdkListener.Endpoint.IDENTITY_MODIFY, url, jsonObject, request);
126129
connection = makeUrlRequest(Endpoint.IDENTITY, connection, jsonObject.toString(), false);
127130
int responseCode = connection.getResponseCode();
131+
String headerField = connection.getHeaderField(IDENTITY_HEADER_TIMEOUT);
128132
JSONObject response = MPUtility.getJsonResponse(connection);
129133
InternalListenerManager.getListener().onNetworkRequestFinished(SdkListener.Endpoint.IDENTITY_MODIFY, url, response, responseCode);
130-
return parseIdentityResponse(responseCode, response);
134+
return parseIdentityResponse(responseCode, response, headerField);
131135
}
132136

133137
private JSONObject getBaseJson() throws JSONException {
@@ -239,13 +243,18 @@ private JSONObject getChangeJson(IdentityApiRequest request) throws JSONExceptio
239243
return jsonObject;
240244
}
241245

242-
private IdentityHttpResponse parseIdentityResponse(int httpCode, JSONObject jsonObject) {
246+
private IdentityHttpResponse parseIdentityResponse(int httpCode, JSONObject jsonObject, String identityTimeoutHeader) {
247+
long timeoutHeader = 0L;
243248
try {
244249
Logger.verbose("Identity response code: " + httpCode);
245250
if (jsonObject != null) {
246251
Logger.verbose("Identity result: " + jsonObject.toString());
247252
}
248-
IdentityHttpResponse httpResponse = new IdentityHttpResponse(httpCode, jsonObject);
253+
try {
254+
timeoutHeader = Long.parseLong(identityTimeoutHeader);
255+
} catch (Exception e) {
256+
}
257+
IdentityHttpResponse httpResponse = new IdentityHttpResponse(httpCode, jsonObject, timeoutHeader);
249258
if (!MPUtility.isEmpty(httpResponse.getContext())) {
250259
mConfigManager.setIdentityApiContext(httpResponse.getContext());
251260
}

android-core/src/main/java/com/mparticle/internal/ConfigManager.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1251,6 +1251,22 @@ public int getIdentityConnectionTimeout() {
12511251
return sPreferences.getInt(Constants.PrefKeys.IDENTITY_CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_SECONDS) * 1000;
12521252
}
12531253

1254+
public long getLastIdentityTypeCall(String call) {
1255+
return sPreferences.getLong(call, 0L);
1256+
}
1257+
1258+
public void resetIdentityTypeCall() {
1259+
SharedPreferences.Editor editor = sPreferences.edit();
1260+
editor.putLong(IdentityApi.LOGIN_CALL, -1);
1261+
editor.putLong(IdentityApi.IDENTIFY_CALL, -1);
1262+
editor.apply();
1263+
}
1264+
1265+
public void setLastIdentityTypeCall(String call) {
1266+
Logger.debug("TIMEOUT - SET LAST IDENTITY TIME CALL FOR " + call + " : " + System.currentTimeMillis());
1267+
sPreferences.edit().putLong(call, System.currentTimeMillis()).apply();
1268+
}
1269+
12541270
public int getConnectionTimeout() {
12551271
return DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000;
12561272
}

0 commit comments

Comments
 (0)