-
Notifications
You must be signed in to change notification settings - Fork 205
/
SessionTracker.java
361 lines (314 loc) · 13.6 KB
/
SessionTracker.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package com.bugsnag.android;
import static com.bugsnag.android.MapUtils.getStringFromMap;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
class SessionTracker extends Observable implements Application.ActivityLifecycleCallbacks {
private static final String KEY_LIFECYCLE_CALLBACK = "ActivityLifecycle";
private static final int DEFAULT_TIMEOUT_MS = 30000;
private final Collection<String>
foregroundActivities = new ConcurrentLinkedQueue<>();
private final long timeoutMs;
final Configuration configuration;
final Client client;
final SessionStore sessionStore;
// This most recent time an Activity was stopped.
private AtomicLong lastExitedForegroundMs = new AtomicLong(0);
// The first Activity in this 'session' was started at this time.
private AtomicLong lastEnteredForegroundMs = new AtomicLong(0);
private AtomicReference<Session> currentSession = new AtomicReference<>();
private Semaphore flushingRequest = new Semaphore(1);
SessionTracker(Configuration configuration, Client client, SessionStore sessionStore) {
this(configuration, client, DEFAULT_TIMEOUT_MS, sessionStore);
}
SessionTracker(Configuration configuration, Client client, long timeoutMs,
SessionStore sessionStore) {
this.configuration = configuration;
this.client = client;
this.timeoutMs = timeoutMs;
this.sessionStore = sessionStore;
}
/**
* Starts a new session with the given date and user.
* <p>
* A session will only be created if {@link Configuration#getAutoCaptureSessions()} returns
* true.
*
* @param date the session start date
* @param user the session user (if any)
*/
@Nullable Session startNewSession(@NonNull Date date, @Nullable User user,
boolean autoCaptured) {
if (configuration.getSessionEndpoint() == null) {
Logger.warn("The session tracking endpoint has not been set. "
+ "Session tracking is disabled");
return null;
}
Session session = new Session(UUID.randomUUID().toString(), date, user, autoCaptured);
currentSession.set(session);
trackSessionIfNeeded(session);
return session;
}
/**
* Cache details of a previously captured session.
* Append session details to all subsequent reports.
*
* @param date the session start date
* @param sessionId the unique session identifier
* @param user the session user (if any)
* @param unhandledCount the number of unhandled events which have occurred during the session
* @param handledCount the number of handled events which have occurred during the session
* @return the session
*/
@Nullable Session registerExistingSession(@Nullable Date date, @Nullable String sessionId,
@Nullable User user, int unhandledCount,
int handledCount) {
Session session = null;
if (date != null && sessionId != null) {
session = new Session(sessionId, date, user, unhandledCount, handledCount);
}
currentSession.set(session);
return session;
}
/**
* Determines whether or not a session should be tracked. If this is true, the session will be
* stored and sent to the Bugsnag API, otherwise no action will occur in this method.
*
* @param session the session
*/
private void trackSessionIfNeeded(final Session session) {
boolean notifyForRelease = configuration.shouldNotifyForReleaseStage(getReleaseStage());
if (notifyForRelease
&& (configuration.getAutoCaptureSessions() || !session.isAutoCaptured())
&& session.isTracked().compareAndSet(false, true)) {
try {
final String endpoint = configuration.getSessionEndpoint();
Async.run(new Runnable() {
@Override
public void run() {
//FUTURE:SM It would be good to optimise this
flushStoredSessions();
SessionTrackingPayload payload =
new SessionTrackingPayload(session, null,
client.appData, client.deviceData);
try {
configuration.getDelivery().deliver(payload, configuration);
} catch (DeliveryFailureException exception) { // store for later sending
Logger.warn("Storing session payload for future delivery", exception);
sessionStore.write(session);
} catch (Exception exception) {
Logger.warn("Dropping invalid session tracking payload", exception);
}
}
});
} catch (RejectedExecutionException exception) {
// This is on the current thread but there isn't much else we can do
sessionStore.write(session);
}
setChanged();
String startedAt = DateUtils.toIso8601(session.getStartedAt());
notifyObservers(new NativeInterface.Message(
NativeInterface.MessageType.START_SESSION,
Arrays.asList(session.getId(), startedAt)));
}
}
/**
* Track a new session when auto capture is enabled via config after initialisation.
*/
void onAutoCaptureEnabled() {
Session session = currentSession.get();
if (session != null && !foregroundActivities.isEmpty()) {
// If there is no session we will wait for one to be created
trackSessionIfNeeded(session);
}
}
private String getReleaseStage() {
return getStringFromMap("releaseStage", client.appData.getAppDataSummary());
}
@Nullable
Session getCurrentSession() {
return currentSession.get();
}
void incrementUnhandledError() {
Session session = currentSession.get();
if (session != null) {
session.incrementUnhandledErrCount();
}
}
void incrementHandledError() {
Session session = currentSession.get();
if (session != null) {
session.incrementHandledErrCount();
}
}
/**
* Attempts to flush session payloads stored on disk
*/
void flushStoredSessions() {
if (flushingRequest.tryAcquire(1)) {
try {
List<File> storedFiles;
storedFiles = sessionStore.findStoredFiles();
if (!storedFiles.isEmpty()) {
SessionTrackingPayload payload =
new SessionTrackingPayload(null, storedFiles,
client.appData, client.deviceData);
//FUTURE:SM Reduce duplication here and above
try {
configuration.getDelivery().deliver(payload, configuration);
sessionStore.deleteStoredFiles(storedFiles);
} catch (DeliveryFailureException exception) {
sessionStore.cancelQueuedFiles(storedFiles);
Logger.warn("Leaving session payload for future delivery", exception);
} catch (Exception exception) {
// drop bad data
Logger.warn("Deleting invalid session tracking payload", exception);
sessionStore.deleteStoredFiles(storedFiles);
}
}
} finally {
flushingRequest.release(1);
}
}
}
@Override
public void onActivityCreated(@NonNull Activity activity, Bundle savedInstanceState) {
leaveLifecycleBreadcrumb(getActivityName(activity), "onCreate()");
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
String activityName = getActivityName(activity);
leaveLifecycleBreadcrumb(activityName, "onStart()");
updateForegroundTracker(activityName, true, System.currentTimeMillis());
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
leaveLifecycleBreadcrumb(getActivityName(activity), "onResume()");
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
leaveLifecycleBreadcrumb(getActivityName(activity), "onPause()");
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
String activityName = getActivityName(activity);
leaveLifecycleBreadcrumb(activityName, "onStop()");
updateForegroundTracker(activityName, false, System.currentTimeMillis());
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, Bundle outState) {
leaveLifecycleBreadcrumb(getActivityName(activity), "onSaveInstanceState()");
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
leaveLifecycleBreadcrumb(getActivityName(activity), "onDestroy()");
}
private String getActivityName(@NonNull Activity activity) {
return activity.getClass().getSimpleName();
}
void leaveLifecycleBreadcrumb(String activityName, String lifecycleCallback) {
leaveBreadcrumb(activityName, lifecycleCallback);
}
private void leaveBreadcrumb(String activityName, String lifecycleCallback) {
if (configuration.isAutomaticallyCollectingBreadcrumbs()) {
Map<String, String> metadata = new HashMap<>();
metadata.put(KEY_LIFECYCLE_CALLBACK, lifecycleCallback);
try {
client.leaveBreadcrumb(activityName, BreadcrumbType.NAVIGATION, metadata);
} catch (Exception ex) {
Logger.warn("Failed to leave breadcrumb in SessionTracker: " + ex.getMessage());
}
}
}
/**
* Tracks a session if a session has not yet been captured,
* recording the session as auto-captured. Requires the current activity.
*
* @param activity the current activity
*/
void startFirstSession(Activity activity) {
Session session = currentSession.get();
if (session == null) {
long nowMs = System.currentTimeMillis();
lastEnteredForegroundMs.set(nowMs);
startNewSession(new Date(nowMs), client.getUser(), true);
foregroundActivities.add(getActivityName(activity));
}
}
/**
* Tracks whether an activity is in the foreground or not.
* <p>
* If an activity leaves the foreground, a timeout should be recorded (e.g. 30s), during which
* no new sessions should be automatically started.
* <p>
* If an activity comes to the foreground and is the only foreground activity, a new session
* should be started, unless the app is within a timeout period.
*
* @param activityName the activity name
* @param activityStarting whether the activity is being started or not
* @param nowMs The current time in ms
*/
void updateForegroundTracker(String activityName, boolean activityStarting, long nowMs) {
if (activityStarting) {
long noActivityRunningForMs = nowMs - lastExitedForegroundMs.get();
//FUTURE:SM Race condition between isEmpty and put
if (foregroundActivities.isEmpty()) {
lastEnteredForegroundMs.set(nowMs);
if (noActivityRunningForMs >= timeoutMs
&& configuration.getAutoCaptureSessions()) {
startNewSession(new Date(nowMs), client.getUser(), true);
}
}
foregroundActivities.add(activityName);
} else {
foregroundActivities.remove(activityName);
if (foregroundActivities.isEmpty()) {
lastExitedForegroundMs.set(nowMs);
}
}
setChanged();
notifyObservers(new NativeInterface.Message(
NativeInterface.MessageType.UPDATE_IN_FOREGROUND,
Arrays.asList(!foregroundActivities.isEmpty(), getContextActivity())));
}
boolean isInForeground() {
return !foregroundActivities.isEmpty();
}
//FUTURE:SM This shouldnt be here
long getDurationInForegroundMs(long nowMs) {
long durationMs = 0;
long sessionStartTimeMs = lastEnteredForegroundMs.get();
if (isInForeground() && sessionStartTimeMs != 0) {
durationMs = nowMs - sessionStartTimeMs;
}
return durationMs > 0 ? durationMs : 0;
}
@Nullable
String getContextActivity() {
if (foregroundActivities.isEmpty()) {
return null;
} else {
// linked hash set retains order of added activity and ensures uniqueness
// therefore obtain the most recently added
int size = foregroundActivities.size();
String[] activities = foregroundActivities.toArray(new String[size]);
return activities[size - 1];
}
}
}