Repository navigation
Expand file tree
/
Copy pathSession.java
More file actions
626 lines (562 loc) · 19.1 KB
/
Copy pathSession.java
File metadata and controls
626 lines (562 loc) · 19.1 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
package io.sentry;
import io.sentry.protocol.User;
import io.sentry.util.AutoClosableReentrantLock;
import io.sentry.util.StringUtils;
import io.sentry.vendor.gson.stream.JsonToken;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class Session implements JsonUnknown, JsonSerializable {
/** Session state */
public enum State {
Ok,
Exited,
Crashed,
Abnormal,
/**
* Final status when an unhandled error did not kill the process, such as a Flutter exception.
* The session stays {@link #Ok} until {@link Session#end()}. Native crashes still end as {@link
* #Crashed}.
*/
Unhandled
}
/** started timestamp */
private final @NotNull Date started;
/** the timestamp */
private @Nullable Date timestamp;
/** the number of errors on the session */
private final @NotNull AtomicInteger errorCount;
/** The distinctId, did */
private final @Nullable String distinctId;
/** the SessionId, sid */
private final @Nullable String sessionId;
/** The session init flag */
private @Nullable Boolean init;
/** The session state */
private @NotNull State status;
/** The session sequence */
private @Nullable Long sequence;
/** The session duration (timestamp - started) */
private @Nullable Double duration;
/** the user's ip address */
private final @Nullable String ipAddress;
/** the user Agent */
private @Nullable String userAgent;
/** the environment */
private final @Nullable String environment;
/** the App's release */
private final @NotNull String release;
/** the Abnormal mechanism, e.g. what was the reason for session to become abnormal (ANR) */
private @Nullable String abnormalMechanism;
/** Whether an unhandled error occurred that did not terminate the process */
private boolean hasNonTerminatingUnhandledError;
/** The session lock, ops should be atomic */
private final @NotNull AutoClosableReentrantLock sessionLock = new AutoClosableReentrantLock();
@SuppressWarnings("unused")
private @Nullable Map<String, Object> unknown;
public Session(
final @NotNull State status,
final @NotNull Date started,
final @Nullable Date timestamp,
final int errorCount,
final @Nullable String distinctId,
final @Nullable String sessionId,
final @Nullable Boolean init,
final @Nullable Long sequence,
final @Nullable Double duration,
final @Nullable String ipAddress,
final @Nullable String userAgent,
final @Nullable String environment,
final @NotNull String release,
final @Nullable String abnormalMechanism) {
this.status = status;
this.started = started;
this.timestamp = timestamp;
this.errorCount = new AtomicInteger(errorCount);
this.distinctId = distinctId;
this.sessionId = sessionId;
this.init = init;
this.sequence = sequence;
this.duration = duration;
this.ipAddress = ipAddress;
this.userAgent = userAgent;
this.environment = environment;
this.release = release;
this.abnormalMechanism = abnormalMechanism;
}
public Session(
@Nullable String distinctId,
final @Nullable User user,
final @Nullable String environment,
final @NotNull String release) {
this(
State.Ok,
DateUtils.getCurrentDateTime(),
DateUtils.getCurrentDateTime(),
0,
distinctId,
SentryUUID.generateSentryId(),
true,
null,
null,
(user != null ? user.getIpAddress() : null),
null,
environment,
release,
null);
}
public boolean isTerminated() {
return status != State.Ok;
}
@SuppressWarnings({"JdkObsolete", "JavaUtilDate"})
public @Nullable Date getStarted() {
return started;
}
public @Nullable String getDistinctId() {
return distinctId;
}
public @Nullable String getSessionId() {
return sessionId;
}
public @Nullable String getIpAddress() {
return ipAddress;
}
public @Nullable String getUserAgent() {
return userAgent;
}
public @Nullable String getEnvironment() {
return environment;
}
public @NotNull String getRelease() {
return release;
}
public @Nullable Boolean getInit() {
return init;
}
/** Used for migrating the init flag when an session is gonna be deleted. */
@ApiStatus.Internal
public void setInitAsTrue() {
this.init = true;
}
public int errorCount() {
return errorCount.get();
}
public @NotNull State getStatus() {
return status;
}
public @Nullable Long getSequence() {
return sequence;
}
public @Nullable Double getDuration() {
return duration;
}
public @Nullable String getAbnormalMechanism() {
return abnormalMechanism;
}
/**
* Whether the session experienced an unhandled error that did <em>not</em> terminate the process,
* e.g. an unhandled Flutter exception, and so finalizes as {@link State#Unhandled} rather than
* {@link State#Exited}. A native crash is also unhandled, but it kills the process and ends the
* session as {@link State#Crashed} instead.
*
* <p>Never sent as a status while the session is alive; it is only persisted with the session.
*/
@ApiStatus.Internal
public boolean hasNonTerminatingUnhandledError() {
return hasNonTerminatingUnhandledError;
}
/**
* Records that an active session experienced an unhandled error which did not terminate the
* process, counting the error and advancing the session's sequence without ending it. On {@link
* #end()} the session is finalized as {@link State#Unhandled} unless a terminal status such as
* {@link State#Crashed} or {@link State#Abnormal} took over first.
*
* <p>Hybrid SDKs whose unhandled errors do not kill the process. Native Java/Android capture
* should not call this.
*
* @return whether the session was updated, i.e. false if it had already reached a terminal state
*/
@ApiStatus.Internal
public boolean recordNonTerminatingUnhandledError() {
try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) {
if (status != State.Ok) {
return false;
}
hasNonTerminatingUnhandledError = true;
errorCount.incrementAndGet();
init = null;
timestamp = DateUtils.getCurrentDateTime();
sequence = getSequenceTimestamp(timestamp);
return true;
}
}
@SuppressWarnings({"JdkObsolete", "JavaUtilDate"})
public @Nullable Date getTimestamp() {
return timestamp;
}
/** Ends a session and update its values */
public void end() {
end(DateUtils.getCurrentDateTime());
}
/**
* Ends a session and update its values
*
* @param timestamp the timestamp or null
*/
public void end(final @Nullable Date timestamp) {
try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) {
init = null;
// at this state it might be Crashed already, so we don't check for it.
if (status == State.Ok) {
status = hasNonTerminatingUnhandledError ? State.Unhandled : State.Exited;
}
if (timestamp != null) {
this.timestamp = timestamp;
} else {
this.timestamp = DateUtils.getCurrentDateTime();
}
if (this.timestamp != null) {
duration = calculateDurationTime(this.timestamp);
sequence = getSequenceTimestamp(this.timestamp);
}
}
}
/**
* Calculates the duration time in seconds timestamp (last update) - started
*
* @param timestamp the timestamp
* @return duration in seconds
*/
@SuppressWarnings({"JdkObsolete", "JavaUtilDate"})
private double calculateDurationTime(final @NotNull Date timestamp) {
long diff = Math.abs(timestamp.getTime() - started.getTime());
return (double) diff / 1000; // duration in seconds
}
public boolean update(
final @Nullable State status,
final @Nullable String userAgent,
final boolean addErrorsCount) {
return update(status, userAgent, addErrorsCount, null);
}
/**
* Updates the current session and set its values
*
* @param status the status
* @param userAgent the userAgent
* @param addErrorsCount true if should increase error count or not
* @param abnormalMechanism the mechanism which caused the session to be abnormal
* @return if the session has been updated
*/
public boolean update(
final @Nullable State status,
final @Nullable String userAgent,
final boolean addErrorsCount,
final @Nullable String abnormalMechanism) {
try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) {
// TODO(buenaflor): should we reject updates if we are already in a terminal status?
boolean sessionHasBeenUpdated = false;
if (status != null) {
this.status = status;
// a terminal status makes the flag meaningless, so drop it rather than serialize a crashed
// session that claims it did not terminate
if (status != State.Ok) {
hasNonTerminatingUnhandledError = false;
}
sessionHasBeenUpdated = true;
}
if (userAgent != null) {
this.userAgent = userAgent;
sessionHasBeenUpdated = true;
}
if (addErrorsCount) {
errorCount.addAndGet(1);
sessionHasBeenUpdated = true;
}
// if the session has experienced an Abnormal status at least once, it should count towards
// the
// Abnormal rate, therefore we do not want to overwrite it with `null`, even if it has
// recovered
if (abnormalMechanism != null) {
this.abnormalMechanism = abnormalMechanism;
sessionHasBeenUpdated = true;
}
if (sessionHasBeenUpdated) {
init = null;
timestamp = DateUtils.getCurrentDateTime();
if (timestamp != null) {
sequence = getSequenceTimestamp(timestamp);
}
}
return sessionHasBeenUpdated;
}
}
/**
* Returns a logical clock.
*
* @param timestamp The timestamp
* @return time stamp in milliseconds UTC
*/
@SuppressWarnings({"JdkObsolete", "JavaUtilDate"})
private long getSequenceTimestamp(final @NotNull Date timestamp) {
long sequence = timestamp.getTime();
// if device has wrong date and time and it is nearly at the beginning of the epoch time.
// when converting GMT to UTC may give a negative value.
if (sequence < 0) {
sequence = Math.abs(sequence);
}
return sequence;
}
/**
* Ctor copy of the Session
*
* @return a copy of the Session
*/
@SuppressWarnings("MissingOverride")
public @NotNull Session clone() {
final @NotNull Session session =
new Session(
status,
started,
timestamp,
errorCount.get(),
distinctId,
sessionId,
init,
sequence,
duration,
ipAddress,
userAgent,
environment,
release,
abnormalMechanism);
session.hasNonTerminatingUnhandledError = hasNonTerminatingUnhandledError;
return session;
}
// JsonSerializable
public static final class JsonKeys {
public static final String SID = "sid";
public static final String DID = "did";
public static final String INIT = "init";
public static final String STARTED = "started";
public static final String STATUS = "status";
public static final String SEQ = "seq";
public static final String ERRORS = "errors";
public static final String DURATION = "duration";
public static final String TIMESTAMP = "timestamp";
public static final String ATTRS = "attrs";
public static final String RELEASE = "release";
public static final String ENVIRONMENT = "environment";
public static final String IP_ADDRESS = "ip_address";
public static final String USER_AGENT = "user_agent";
public static final String ABNORMAL_MECHANISM = "abnormal_mechanism";
public static final String NON_TERMINATING_UNHANDLED_ERROR = "non_terminating_unhandled_error";
}
@Override
public void serialize(final @NotNull ObjectWriter writer, final @NotNull ILogger logger)
throws IOException {
writer.beginObject();
if (sessionId != null) {
writer.name(JsonKeys.SID).value(sessionId);
}
if (distinctId != null) {
writer.name(JsonKeys.DID).value(distinctId);
}
if (init != null) {
writer.name(JsonKeys.INIT).value(init);
}
writer.name(JsonKeys.STARTED).value(logger, started);
writer.name(JsonKeys.STATUS).value(logger, status.name().toLowerCase(Locale.ROOT));
if (sequence != null) {
writer.name(JsonKeys.SEQ).value(sequence);
}
writer.name(JsonKeys.ERRORS).value(errorCount.intValue());
if (duration != null) {
writer.name(JsonKeys.DURATION).value(duration);
}
if (timestamp != null) {
writer.name(JsonKeys.TIMESTAMP).value(logger, timestamp);
}
if (abnormalMechanism != null) {
writer.name(JsonKeys.ABNORMAL_MECHANISM).value(logger, abnormalMechanism);
}
if (hasNonTerminatingUnhandledError) {
writer.name(JsonKeys.NON_TERMINATING_UNHANDLED_ERROR).value(hasNonTerminatingUnhandledError);
}
writer.name(JsonKeys.ATTRS);
writer.beginObject();
writer.name(JsonKeys.RELEASE).value(logger, release);
if (environment != null) {
writer.name(JsonKeys.ENVIRONMENT).value(logger, environment);
}
if (ipAddress != null) {
writer.name(JsonKeys.IP_ADDRESS).value(logger, ipAddress);
}
if (userAgent != null) {
writer.name(JsonKeys.USER_AGENT).value(logger, userAgent);
}
writer.endObject();
if (unknown != null) {
for (String key : unknown.keySet()) {
Object value = unknown.get(key);
writer.name(key);
writer.value(logger, value);
}
}
writer.endObject();
}
@Nullable
@Override
public Map<String, Object> getUnknown() {
return unknown;
}
@Override
public void setUnknown(@Nullable Map<String, Object> unknown) {
this.unknown = unknown;
}
public static final class Deserializer implements JsonDeserializer<Session> {
@SuppressWarnings("unchecked")
@Override
public @NotNull Session deserialize(@NotNull ObjectReader reader, @NotNull ILogger logger)
throws Exception {
reader.beginObject();
Date started = null; // @NotNull
Date timestamp = null;
Integer errorCount = null; // @NotNull
String distinctId = null;
String sessionId = null;
Boolean init = null;
State status = null; // @NotNull
Long sequence = null;
Double duration = null;
String ipAddress = null;
String userAgent = null;
String environment = null;
String release = null; // @NotNull
String abnormalMechanism = null;
boolean hasNonTerminatingUnhandledError = false;
Map<String, Object> unknown = null;
while (reader.peek() == JsonToken.NAME) {
final String nextName = reader.nextName();
switch (nextName) {
case JsonKeys.SID:
String sid = reader.nextStringOrNull();
if (sid != null && (sid.length() == 36 || sid.length() == 32)) {
sessionId = sid;
} else {
logger.log(SentryLevel.ERROR, "%s sid is not valid.", sid);
}
break;
case JsonKeys.DID:
distinctId = reader.nextStringOrNull();
break;
case JsonKeys.INIT:
init = reader.nextBooleanOrNull();
break;
case JsonKeys.STARTED:
started = reader.nextDateOrNull(logger);
break;
case JsonKeys.STATUS:
String statusValue = StringUtils.capitalize(reader.nextStringOrNull());
if (statusValue != null) {
status = State.valueOf(statusValue);
}
break;
case JsonKeys.SEQ:
sequence = reader.nextLongOrNull();
break;
case JsonKeys.ERRORS:
errorCount = reader.nextIntegerOrNull();
break;
case JsonKeys.DURATION:
duration = reader.nextDoubleOrNull();
break;
case JsonKeys.TIMESTAMP:
timestamp = reader.nextDateOrNull(logger);
break;
case JsonKeys.ABNORMAL_MECHANISM:
abnormalMechanism = reader.nextStringOrNull();
break;
case JsonKeys.NON_TERMINATING_UNHANDLED_ERROR:
final Boolean hasNonTerminatingUnhandledErrorValue = reader.nextBooleanOrNull();
hasNonTerminatingUnhandledError =
hasNonTerminatingUnhandledErrorValue != null
&& hasNonTerminatingUnhandledErrorValue;
break;
case JsonKeys.ATTRS:
reader.beginObject();
while (reader.peek() == JsonToken.NAME) {
final String nextAttrName = reader.nextName();
switch (nextAttrName) {
case JsonKeys.RELEASE:
release = reader.nextStringOrNull();
break;
case JsonKeys.ENVIRONMENT:
environment = reader.nextStringOrNull();
break;
case JsonKeys.IP_ADDRESS:
ipAddress = reader.nextStringOrNull();
break;
case JsonKeys.USER_AGENT:
userAgent = reader.nextStringOrNull();
break;
default:
reader.skipValue(); // Ignore unknown properties in attrs, as this is flattend
}
}
reader.endObject();
break;
default:
if (unknown == null) {
unknown = new ConcurrentHashMap<>();
}
reader.nextUnknown(logger, unknown, nextName);
break;
}
}
if (status == null) {
throw missingRequiredFieldException(JsonKeys.STATUS, logger);
}
if (started == null) {
throw missingRequiredFieldException(JsonKeys.STARTED, logger);
}
if (errorCount == null) {
throw missingRequiredFieldException(JsonKeys.ERRORS, logger);
}
if (release == null) {
throw missingRequiredFieldException(JsonKeys.RELEASE, logger);
}
Session session =
new Session(
status,
started,
timestamp,
errorCount,
distinctId,
sessionId,
init,
sequence,
duration,
ipAddress,
userAgent,
environment,
release,
abnormalMechanism);
session.hasNonTerminatingUnhandledError = hasNonTerminatingUnhandledError;
session.setUnknown(unknown);
reader.endObject();
return session;
}
private Exception missingRequiredFieldException(String field, ILogger logger) {
String message = "Missing required field \"" + field + "\"";
Exception exception = new IllegalStateException(message);
logger.log(SentryLevel.ERROR, message, exception);
return exception;
}
}
}