diff --git a/CHANGELOG.md b/CHANGELOG.md index 482f613041b..1948d3bc63b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - Android: Out-of-process crash reporting now supports Android 5.0 (API level 21) and later, previously required Android 11 (API level 30) ([#6614](https://github.com/getsentry/sentry-java/pull/6614)) - Android profiling: Uploading a Perfetto profile chunk now keeps the trace in memory once instead of up to three times, lowering peak memory use for traces up to 50 MB ([#6743](https://github.com/getsentry/sentry-java/pull/6743)) - Stop a transaction's CPU and memory collection 30 seconds after it starts even when the device's wall clock changes in between ([#6739](https://github.com/getsentry/sentry-java/pull/6739)) +- Hybrid SDKs: A session written right after `Sentry.init` is no longer sent as the previous run's session while it is still in progress, and the previous run's session is no longer lost ([#6800](https://github.com/getsentry/sentry-java/pull/6800)) ### Dependencies diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index d3f473cfbc9..2b2b6ac8729 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -82,6 +82,13 @@ public class EnvelopeCache extends CacheStrategy implements IEnvelopeCache { */ private @Nullable String lastPersistedSessionId; + /** + * Whether this process already moved the last run's session out of the current session file. + * After that, the current session file holds a session of this process, so the init-time {@link + * #movePreviousSession(File, File)} must not move it. + */ + private boolean previousSessionMoved; + public static @NotNull IEnvelopeCache create(final @NotNull SentryOptions options) { final String cacheDirPath = options.getCacheDirPath(); final int maxCacheItems = options.getMaxCacheItems(); @@ -141,9 +148,10 @@ private boolean storeInternal(final @NotNull SentryEnvelope envelope, final @Not try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { final @Nullable Session startingSession = readSessionFromEnvelope(envelope); if (!isAlreadyPersisted(startingSession)) { - movePreviousSession(currentSessionFile, previousSessionFile); - if (startingSession != null) { - writeSessionToDisk(currentSessionFile, startingSession); + moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); + if (startingSession != null && writeSessionToDisk(currentSessionFile, startingSession)) { + // even if the move failed, the file now holds this session and not the last run's + previousSessionMoved = true; } } } @@ -388,10 +396,25 @@ private boolean writeSessionToDisk(final @NotNull File file, final @NotNull Sess @ApiStatus.Internal public void persistCurrentSession(final @NotNull Session session) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { - final boolean written = - writeSessionToDisk( - getCurrentSessionFile(directory.getOrCreate().getAbsolutePath()), session); - // a failed write truncates the file, so there is no good copy left to protect + final String directoryPath = directory.getOrCreate().getAbsolutePath(); + final File currentSessionFile = getCurrentSessionFile(directoryPath); + // this can run before the init-time move, so move the last run's session first instead of + // overwriting it + if (!previousSessionMoved) { + moveCurrentToPreviousSession(currentSessionFile, getPreviousSessionFile(directoryPath)); + } + final boolean written = writeSessionToDisk(currentSessionFile, session); + // A written file holds this session, even if the move failed, so the init-time move must + // skip it. After a failed write, delete the truncated file only if the move worked: then it + // is ours, and a later move must not put it over the last run's session. If the move failed, + // the file can still hold the last run's session, so it stays for a later move to retry. + if (written) { + previousSessionMoved = true; + } else if (previousSessionMoved && !currentSessionFile.delete()) { + options + .getLogger() + .log(WARNING, "Unable to delete the current session file after a failed write."); + } lastPersistedSessionId = written ? session.getSessionId() : null; } } @@ -506,10 +529,28 @@ public void flushPreviousSession() { previousSessionLatch.countDown(); } + /** + * Moves the last run's session to the previous session file. Does nothing if this process already + * did that, because the current session file then holds the live session. + */ public void movePreviousSession( final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { + try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { + if (previousSessionMoved) { + options + .getLogger() + .log(DEBUG, "Previous session was already moved, not moving the live session."); + return; + } + moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); + } + } + + private void moveCurrentToPreviousSession( + final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { if (!currentSessionFile.exists()) { + previousSessionMoved = true; return; } @@ -526,6 +567,8 @@ public void movePreviousSession( try { final boolean renamed = currentSessionFile.renameTo(previousSessionFile); + // a failed rename leaves the last run's session in place, so a later move can retry it + previousSessionMoved = renamed; if (!renamed) { options.getLogger().log(WARNING, "Unable to move current session to previous session."); } diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 0cc2c968195..609c7b2fb21 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -227,7 +227,7 @@ class EnvelopeCacheTest { assertTrue(currentSessionFile.delete()) assertTrue(currentSessionFile.mkdir()) cache.persistCurrentSession(newerSession) - assertTrue(currentSessionFile.delete()) + assertThat(currentSessionFile.exists()).isFalse() val delayedStart = createSession(sessionId = sid) val envelope = SentryEnvelope.from(fixture.options.serializer, delayedStart, null) @@ -347,6 +347,27 @@ class EnvelopeCacheTest { verify(serializer).serialize(same(delayedStart), any()) } + @Test + fun `failed persist after the move keeps the last run's session from the next SessionStart`() { + val liveSession = createSession() + val serializer = mock() + whenever(serializer.serialize(same(liveSession), any())) + .thenThrow(RuntimeException("forced ex")) + whenever(serializer.deserialize(any(), eq(Session::class.java))).thenReturn(liveSession) + val cache = fixture.getSUT { options -> options.setSerializer(serializer) } + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + + cache.persistCurrentSession(liveSession) + assertThat(currentSessionFile.exists()).isFalse() + + val envelope = SentryEnvelope.from(SentryOptions.empty().serializer, liveSession, null) + cache.storeEnvelope(envelope, HintUtils.createWithTypeCheckHint(SessionStartHint())) + + assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") + } + @Test fun `updates current file on session update and read it back`() { val cache = fixture.getSUT() @@ -821,4 +842,94 @@ class EnvelopeCacheTest { assertTrue(previousSessionFile.exists()) assertEquals("current session content", previousSessionFile.readText()) } + + @Test + fun `persistCurrentSession before the init-time move keeps both sessions in place`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + val liveSession = createSession() + + // a hybrid SDK persists the live session before the executor runs MovePreviousSession + cache.persistCurrentSession(liveSession) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") + val persistedCurrent = + fixture.options.serializer.deserialize( + currentSessionFile.bufferedReader(), + Session::class.java, + )!! + assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + } + + @Test + fun `failed move in persistCurrentSession still writes the live session for the init-time move to skip`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + // a non-empty directory where the previous session file belongs makes the move fail + assertTrue(File(previousSessionFile, "blocker").mkdirs()) + val liveSession = createSession() + + cache.persistCurrentSession(liveSession) + assertTrue(previousSessionFile.deleteRecursively()) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(previousSessionFile.exists()).isFalse() + val persistedCurrent = + fixture.options.serializer.deserialize( + currentSessionFile.bufferedReader(), + Session::class.java, + )!! + assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + } + + @Test + fun `failed move and failed write in persistCurrentSession leave the file for a later move`() { + val liveSession = createSession() + val serializer = mock() + whenever(serializer.serialize(same(liveSession), any())) + .thenThrow(RuntimeException("forced ex")) + val cache = fixture.getSUT { options -> options.setSerializer(serializer) } + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + assertTrue(File(previousSessionFile, "blocker").mkdirs()) + + cache.persistCurrentSession(liveSession) + // the file may still be the last run's session, so it is not deleted + assertThat(currentSessionFile.exists()).isTrue() + + assertTrue(previousSessionFile.deleteRecursively()) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(currentSessionFile.exists()).isFalse() + assertThat(previousSessionFile.exists()).isTrue() + } + + @Test + fun `SessionStart before the init-time move keeps both sessions in place`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + currentSessionFile.writeText("session content from last run") + val liveSession = createSession() + + cache.storeEnvelope( + SentryEnvelope.from(fixture.options.serializer, liveSession, null), + HintUtils.createWithTypeCheckHint(SessionStartHint()), + ) + cache.movePreviousSession(currentSessionFile, previousSessionFile) + + assertThat(previousSessionFile.readText()).isEqualTo("session content from last run") + val persistedCurrent = + fixture.options.serializer.deserialize( + currentSessionFile.bufferedReader(), + Session::class.java, + )!! + assertThat(persistedCurrent.sessionId).isEqualTo(liveSession.sessionId) + } }