Skip to content
Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
- Remove the deprecated `Instrumenter` enum, option, span context property, and `startChild` overloads ([#6252](https://github.com/getsentry/sentry-java/pull/6252))
- Remove deprecated OpenTelemetry integration classes and the legacy `SentrySpanStorage` ([#6243](https://github.com/getsentry/sentry-java/pull/6243))
- Decide whether foregrounding the app starts a new session on a monotonic clock instead of the wall clock, so that a device time change no longer starts a session that should have been resumed, or resumes one that should have ended. This affects session counts ([#6096](https://github.com/getsentry/sentry-java/pull/6096))
- Decide whether the session started by SDK init is stale on a monotonic clock instead of the wall clock, so that a device time change between `Sentry.init` and the first foreground no longer starts an extra session or keeps a stale one. This affects session counts ([#6688](https://github.com/getsentry/sentry-java/pull/6688))
- `SentryUserFeedbackForm` now extends `android.app.Dialog` instead of `android.app.AlertDialog` ([#6338](https://github.com/getsentry/sentry-java/pull/6338))
- The form never used `AlertDialog` features. Code that calls `AlertDialog`-only methods on it, such as `setButton` or `setMessage`, no longer compiles.
- Raise the minimum supported Android API level (`minSdk`) of all Android modules from 21 to 24. Apps with a lower `minSdk` must raise it or stay on 8.x ([#6518](https://github.com/getsentry/sentry-java/pull/6518))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions
this.options.getSessionTrackingIntervalMillis(),
this.options.isEnableAutoSessionTracking(),
this.options.isEnableAppLifecycleBreadcrumbs(),
this.options.getMonotonicTicker(),
this.options.getEpochClock());
this.options.getMonotonicTicker());

AppState.getInstance().addAppStateListener(watcher);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
import io.sentry.SentryLevel;
import io.sentry.Session;
import io.sentry.time.Deadline;
import io.sentry.time.EpochClock;
import io.sentry.time.MonotonicTicker;
import io.sentry.time.Stopwatch;
import io.sentry.util.AutoClosableReentrantLock;
import java.util.Date;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
Expand All @@ -36,21 +35,18 @@ final class LifecycleWatcher implements AppState.AppStateListener {
private final boolean enableAppLifecycleBreadcrumbs;

private final @NotNull MonotonicTicker ticker;
private final @NotNull EpochClock epochClock;

LifecycleWatcher(
final @NotNull IScopes scopes,
final long sessionIntervalMillis,
final boolean enableSessionTracking,
final boolean enableAppLifecycleBreadcrumbs,
final @NotNull MonotonicTicker ticker,
final @NotNull EpochClock epochClock) {
final @NotNull MonotonicTicker ticker) {
this.sessionIntervalMillis = sessionIntervalMillis;
this.enableSessionTracking = enableSessionTracking;
this.enableAppLifecycleBreadcrumbs = enableAppLifecycleBreadcrumbs;
this.scopes = scopes;
this.ticker = ticker;
this.epochClock = epochClock;
}

@Override
Expand All @@ -76,24 +72,16 @@ private void startSession() {
* Whether the session on the scope is too old to resume, so foregrounding should start a new one.
*
* <p>Used when no background window is pending, which means the session was started by SDK init
* rather than by leaving and returning to the app. Nothing captured a tick back then, and the
* only record of when the session started is {@link Session#getStarted()} — a wall-clock instant,
* because it is sent to Sentry. So this check stays on the wall clock, clock steps included.
*
* <p>TODO [MAJOR]: let a session remember the tick it started on, so this can use a {@link
* Deadline} too. That tick must not be serialized.
* rather than by leaving and returning to the app.
*/
// Session#getStarted() is a Date, see above.
@SuppressWarnings("JavaUtilDate")
private boolean isSessionOnScopeStale() {
final long nowMillis = TimeUnit.NANOSECONDS.toMillis(epochClock.now().epochNanos());
// No session, or one that never recorded a start, leaves nothing to resume.
// No session, or one without a monotonic start, leaves nothing to resume.
final @NotNull AtomicBoolean stale = new AtomicBoolean(true);
scopes.configureScope(scope -> {
final @Nullable Session session = scope.getSession();
final @Nullable Date started = session == null ? null : session.getStarted();
if (started != null) {
stale.set(started.getTime() + sessionIntervalMillis <= nowMillis);
final @Nullable Stopwatch sinceStarted = session == null ? null : session.getSinceStarted();
if (sinceStarted != null) {
stale.set(sinceStarted.elapsed(TimeUnit.MILLISECONDS) >= sessionIntervalMillis);
}
});
return stale.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@ import io.sentry.SentryLevel
import io.sentry.SentryOptions
import io.sentry.Session
import io.sentry.Session.State
import io.sentry.time.EpochClock
import io.sentry.time.Stopwatch
import io.sentry.time.TestMonotonicTicker
import io.sentry.time.Timestamp
import java.util.Date
import java.util.concurrent.TimeUnit.HOURS
import java.util.concurrent.TimeUnit.MILLISECONDS
import java.util.concurrent.atomic.AtomicLong
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
Expand All @@ -38,9 +37,6 @@ class LifecycleWatcherTest {
private class Fixture {
val scopes = mock<IScopes>()
val ticker = TestMonotonicTicker()
// the wall clock, which only the staleness of a session already on the scope depends on
val nowMillis = AtomicLong(0L)
val epochClock = EpochClock { Timestamp.ofEpochNanos(MILLISECONDS.toNanos(nowMillis.get())) }
// a real executor so scheduled end-session tasks actually run
val options = SentryOptions().apply { setTimerExecutorService(SentryExecutorService(this)) }
val replayController = mock<ReplayController>()
Expand Down Expand Up @@ -69,9 +65,27 @@ class LifecycleWatcherTest {
enableAutoSessionTracking,
enableAppLifecycleBreadcrumbs,
ticker,
epochClock,
)
}

fun createSession(started: Date): Session =
Session(
State.Ok,
started,
started,
0,
"abc",
"3c1ffc32-f68f-4af2-a1ee-dd72f4d62d17",
true,
0,
10.0,
null,
null,
null,
"release",
null,
)
.apply { sinceStarted = Stopwatch.started(ticker) }
}

private val fixture = Fixture()
Expand Down Expand Up @@ -118,39 +132,6 @@ class LifecycleWatcherTest {
verify(fixture.replayController).onAppForegrounded(false)
}

@Test
fun `a wall clock stepping forward during the background window does not rotate the session`() {
val watcher =
fixture.getSUT(sessionIntervalMillis = 30000L, enableAppLifecycleBreadcrumbs = false)
watcher.onForeground()
watcher.onBackground()

// the device syncs its clock an hour forward, which two wall-clock reads used to report as an
// hour spent in the background
fixture.nowMillis.addAndGet(HOURS.toMillis(1))
fixture.ticker.advance(1, MILLISECONDS)
watcher.onForeground()

verify(fixture.scopes).startSession()
verify(fixture.replayController).onAppForegrounded(false)
}

@Test
fun `a wall clock stepping backwards during the background window still rotates the session`() {
val watcher =
fixture.getSUT(sessionIntervalMillis = 30000L, enableAppLifecycleBreadcrumbs = false)
fixture.nowMillis.set(HOURS.toMillis(1))
watcher.onForeground()
watcher.onBackground()

fixture.nowMillis.set(0L)
fixture.ticker.advance(30000, MILLISECONDS)
watcher.onForeground()

verify(fixture.scopes, times(2)).startSession()
verify(fixture.replayController, times(2)).onAppForegrounded(true)
}

@Test
fun `if app goes to background, end session after interval`() {
val watcher = fixture.getSUT(enableAppLifecycleBreadcrumbs = false)
Expand Down Expand Up @@ -243,54 +224,77 @@ class LifecycleWatcherTest {
fun `if the scopes has already a fresh session running, don't start new one`() {
val watcher =
fixture.getSUT(
sessionIntervalMillis = 30000L,
enableAppLifecycleBreadcrumbs = false,
session = fixture.createSession(DateUtils.getCurrentDateTime()),
)
fixture.ticker.advance(29999, MILLISECONDS)

watcher.onForeground()
verify(fixture.scopes, never()).startSession()
verify(fixture.replayController).onAppForegrounded(false)
}

@Test
fun `if the scopes has a long running session, start new one`() {
val watcher =
fixture.getSUT(
sessionIntervalMillis = 30000L,
enableAppLifecycleBreadcrumbs = false,
session = fixture.createSession(DateUtils.getCurrentDateTime()),
)
fixture.ticker.advance(30000, MILLISECONDS)

watcher.onForeground()
verify(fixture.scopes).startSession()
verify(fixture.replayController).onAppForegrounded(true)
}

@Test
fun `a wall clock stepping forward after the session started does not rotate it`() {
val watcher =
fixture.getSUT(
sessionIntervalMillis = 30000L,
enableAppLifecycleBreadcrumbs = false,
session =
Session(
State.Ok,
DateUtils.getCurrentDateTime(),
DateUtils.getCurrentDateTime(),
0,
"abc",
"3c1ffc32-f68f-4af2-a1ee-dd72f4d62d17",
true,
0,
10.0,
null,
null,
null,
"release",
null,
fixture.createSession(
DateUtils.getDateTime(System.currentTimeMillis() - HOURS.toMillis(1)),
),
)
fixture.ticker.advance(1, MILLISECONDS)

watcher.onForeground()
verify(fixture.scopes, never()).startSession()
verify(fixture.replayController).onAppForegrounded(false)
}

@Test
fun `if the scopes has a long running session, start new one`() {
fun `a wall clock stepping backwards after the session started still rotates it`() {
val watcher =
fixture.getSUT(
sessionIntervalMillis = 30000L,
enableAppLifecycleBreadcrumbs = false,
session =
Session(
State.Ok,
DateUtils.getDateTime(-1),
DateUtils.getDateTime(-1),
0,
"abc",
"3c1ffc32-f68f-4af2-a1ee-dd72f4d62d17",
true,
0,
10.0,
null,
null,
null,
"release",
null,
fixture.createSession(
DateUtils.getDateTime(System.currentTimeMillis() + HOURS.toMillis(1)),
),
)
fixture.ticker.advance(30000, MILLISECONDS)

watcher.onForeground()
verify(fixture.scopes).startSession()
verify(fixture.replayController).onAppForegrounded(true)
}

@Test
fun `if the session on the scope has no monotonic start, start new one`() {
val watcher =
fixture.getSUT(
sessionIntervalMillis = 30000L,
enableAppLifecycleBreadcrumbs = false,
session =
fixture.createSession(DateUtils.getCurrentDateTime()).apply { sinceStarted = null },
)

watcher.onForeground()
verify(fixture.scopes).startSession()
Expand Down
2 changes: 2 additions & 0 deletions sentry/api/sentry.api
Original file line number Diff line number Diff line change
Expand Up @@ -4184,6 +4184,7 @@ public final class io/sentry/Session : io/sentry/JsonSerializable, io/sentry/Jso
public fun getRelease ()Ljava/lang/String;
public fun getSequence ()Ljava/lang/Long;
public fun getSessionId ()Ljava/lang/String;
public fun getSinceStarted ()Lio/sentry/time/Stopwatch;
public fun getStarted ()Ljava/util/Date;
public fun getStatus ()Lio/sentry/Session$State;
public fun getTimestamp ()Ljava/util/Date;
Expand All @@ -4194,6 +4195,7 @@ public final class io/sentry/Session : io/sentry/JsonSerializable, io/sentry/Jso
public fun recordNonTerminatingUnhandledError ()Z
public fun serialize (Lio/sentry/ObjectWriter;Lio/sentry/ILogger;)V
public fun setInitAsTrue ()V
public fun setSinceStarted (Lio/sentry/time/Stopwatch;)V
public fun setUnknown (Ljava/util/Map;)V
public fun update (Lio/sentry/Session$State;Ljava/lang/String;Z)Z
public fun update (Lio/sentry/Session$State;Ljava/lang/String;ZLjava/lang/String;)Z
Expand Down
2 changes: 2 additions & 0 deletions sentry/src/main/java/io/sentry/Scope.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import io.sentry.protocol.SentryId;
import io.sentry.protocol.TransactionNameSource;
import io.sentry.protocol.User;
import io.sentry.time.Stopwatch;
import io.sentry.util.AutoClosableReentrantLock;
import io.sentry.util.CollectionUtils;
import io.sentry.util.EventProcessorUtils;
Expand Down Expand Up @@ -1086,6 +1087,7 @@ SessionPair startSession(final @Nullable String sessionEnvironment) {
user,
sessionEnvironment != null ? sessionEnvironment : options.getEnvironment(),
options.getRelease());
session.setSinceStarted(Stopwatch.started(options.getMonotonicTicker()));

final Session previousClone = previousSession != null ? previousSession.clone() : null;
pair = new SessionPair(session.clone(), previousClone);
Expand Down
15 changes: 15 additions & 0 deletions sentry/src/main/java/io/sentry/Session.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.sentry;

import io.sentry.protocol.User;
import io.sentry.time.Stopwatch;
import io.sentry.util.AutoClosableReentrantLock;
import io.sentry.util.StringUtils;
import io.sentry.vendor.gson.stream.JsonToken;
Expand Down Expand Up @@ -75,6 +76,9 @@ public enum State {
/** Whether an unhandled error occurred that did not terminate the process */
private boolean hasNonTerminatingUnhandledError;

/** Time since the session started, on a monotonic clock. In memory only, never serialized */
private @Nullable Stopwatch sinceStarted;

/** The session lock, ops should be atomic */
private final @NotNull AutoClosableReentrantLock sessionLock = new AutoClosableReentrantLock();

Expand Down Expand Up @@ -197,6 +201,16 @@ public int errorCount() {
return abnormalMechanism;
}

@ApiStatus.Internal
public @Nullable Stopwatch getSinceStarted() {
return sinceStarted;
}

@ApiStatus.Internal
public void setSinceStarted(final @Nullable Stopwatch sinceStarted) {
this.sinceStarted = sinceStarted;
}

/**
* 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
Expand Down Expand Up @@ -389,6 +403,7 @@ private long getSequenceTimestamp(final @NotNull Date timestamp) {
release,
abnormalMechanism);
session.hasNonTerminatingUnhandledError = hasNonTerminatingUnhandledError;
session.sinceStarted = sinceStarted;
return session;
}

Expand Down
11 changes: 11 additions & 0 deletions sentry/src/test/java/io/sentry/ScopeTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,17 @@ class ScopeTest {
assertNotNull(sessionPair) { assertEquals("scope-env", it.current.environment) }
}

@Test
fun `Scope starts a new session with a monotonic start`() {
val options = SentryOptions().apply { release = "rel" }
val scope = Scope(options)

val sessionPair = scope.startSession()

assertNotNull(sessionPair) { assertThat(it.current.sinceStarted).isNotNull() }
assertThat(scope.session?.sinceStarted).isNotNull()
}

@Test
fun `Scope ends a session and returns it if theres one`() {
val options = SentryOptions().apply { release = "0.0.1" }
Expand Down
Loading