diff --git a/CHANGELOG.md b/CHANGELOG.md index d25f300090..35fac66be6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)) diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppLifecycleIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppLifecycleIntegration.java index 5817dae47c..8675d87be4 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppLifecycleIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppLifecycleIntegration.java @@ -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); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java b/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java index 0534e9ba53..e5b0b863e1 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java @@ -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; @@ -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 @@ -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. * *

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. - * - *

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(); diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/LifecycleWatcherTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/LifecycleWatcherTest.kt index 8053531160..f84b85745d 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/LifecycleWatcherTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/LifecycleWatcherTest.kt @@ -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 @@ -38,9 +37,6 @@ class LifecycleWatcherTest { private class Fixture { val scopes = mock() 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() @@ -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() @@ -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) @@ -243,25 +224,44 @@ 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() @@ -269,28 +269,32 @@ class LifecycleWatcherTest { } @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() diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index aef699711a..317eda7a51 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -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; @@ -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 diff --git a/sentry/src/main/java/io/sentry/Scope.java b/sentry/src/main/java/io/sentry/Scope.java index b05e4d9d05..965fdf0618 100644 --- a/sentry/src/main/java/io/sentry/Scope.java +++ b/sentry/src/main/java/io/sentry/Scope.java @@ -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; @@ -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); diff --git a/sentry/src/main/java/io/sentry/Session.java b/sentry/src/main/java/io/sentry/Session.java index 598fe994fd..779d291de4 100644 --- a/sentry/src/main/java/io/sentry/Session.java +++ b/sentry/src/main/java/io/sentry/Session.java @@ -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; @@ -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(); @@ -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 not terminate the process, * e.g. an unhandled Flutter exception, and so finalizes as {@link State#Unhandled} rather than @@ -389,6 +403,7 @@ private long getSequenceTimestamp(final @NotNull Date timestamp) { release, abnormalMechanism); session.hasNonTerminatingUnhandledError = hasNonTerminatingUnhandledError; + session.sinceStarted = sinceStarted; return session; } diff --git a/sentry/src/test/java/io/sentry/ScopeTest.kt b/sentry/src/test/java/io/sentry/ScopeTest.kt index 536f869ebc..fa06bf1c70 100644 --- a/sentry/src/test/java/io/sentry/ScopeTest.kt +++ b/sentry/src/test/java/io/sentry/ScopeTest.kt @@ -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" }