diff --git a/CHANGELOG.md b/CHANGELOG.md index d64209bed76..cc8179b5875 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - Android: A crash long after `Sentry.init` is no longer marked as a startup crash when the device slept in between, because the time since init now counts deep sleep ([#6738](https://github.com/getsentry/sentry-java/pull/6738)) - Session Replay: Replays recovered after a crash no longer list `"null"` as a screen name when the last named frame leaves the buffer ([#6827](https://github.com/getsentry/sentry-java/pull/6827)) +- 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. A non-terminating error recorded right after a new session starts is no longer removed from disk when the previous session ends ([#6800](https://github.com/getsentry/sentry-java/pull/6800)) ### Internal diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java index 104d2f0c803..8379425a3df 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java @@ -26,6 +26,7 @@ import io.sentry.android.core.performance.AppStartMetrics; import io.sentry.android.core.performance.TimeSpan; import io.sentry.cache.EnvelopeCache; +import io.sentry.cache.IEnvelopeCache; import io.sentry.protocol.App; import io.sentry.protocol.Device; import io.sentry.protocol.SentryId; @@ -193,6 +194,7 @@ public static SentryId captureEnvelope( envelopeItems.add(sessionItem); deleteCurrentSessionFile( options, + session.getSessionId(), // should be sync if going to crash or already not a main thread !maybeStartNewSession || !scopes.getOptions().getThreadChecker().isMainThread()); if (maybeStartNewSession) { @@ -407,13 +409,13 @@ private static void addTimeSpanToSerializedSpans(TimeSpan span, List { - deleteCurrentSessionFile(options); + deleteCurrentSessionFile(options, sessionId); }); } catch (Throwable e) { options @@ -421,17 +423,25 @@ private static void deleteCurrentSessionFile( .log(WARNING, "Submission of deletion of the current session file rejected.", e); } } else { - deleteCurrentSessionFile(options); + deleteCurrentSessionFile(options, sessionId); } } - private static void deleteCurrentSessionFile(final @NotNull SentryOptions options) { + private static void deleteCurrentSessionFile( + final @NotNull SentryOptions options, final @Nullable String sessionId) { final String cacheDirPath = options.getCacheDirPath(); if (cacheDirPath == null) { options.getLogger().log(INFO, "Cache dir is not set, not deleting the current session."); return; } + final IEnvelopeCache cache = options.getEnvelopeDiskCache(); + if (cache instanceof EnvelopeCache) { + // keeps the file if it already holds another session + ((EnvelopeCache) cache).deleteCurrentSessionFile(sessionId); + return; + } + final File sessionFile = EnvelopeCache.getCurrentSessionFile(cacheDirPath); if (!sessionFile.delete()) { options.getLogger().log(WARNING, "Failed to delete the current session file."); diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt index baa46fdd3bb..9e2d350d9e4 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt @@ -462,6 +462,37 @@ class InternalSentrySdkTest { assertEquals(capturedSession.sessionId, sessionRef.get().sessionId) } + @Test + fun `captureEnvelope deletes the session file of the crashed session`() { + val fixture = Fixture() + fixture.init(context) + val sessionRef = AtomicReference() + Sentry.configureScope { scope -> sessionRef.set(scope.session) } + val sessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + sessionFile.parentFile!!.mkdirs() + sessionFile.bufferedWriter().use { fixture.options.serializer.serialize(sessionRef.get(), it) } + + fixture.captureEnvelopeWithEvent(fixture.createSentryEventWithUnhandledException()) + + assertThat(sessionFile.exists()).isFalse() + } + + @Test + fun `captureEnvelope keeps a session file that holds another session`() { + val fixture = Fixture() + fixture.init(context) + val otherSession = Session("other", null, "environment", "release") + val sessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + sessionFile.parentFile!!.mkdirs() + sessionFile.bufferedWriter().use { fixture.options.serializer.serialize(otherSession, it) } + + fixture.captureEnvelopeWithEvent(fixture.createSentryEventWithUnhandledException()) + + val persistedSession = + fixture.options.serializer.deserialize(sessionFile.reader(), Session::class.java)!! + assertThat(persistedSession.sessionId).isEqualTo(otherSession.sessionId) + } + @Test fun `captureEnvelope starts new session when enabled`() { val fixture = Fixture() diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 3dc8ed74c4a..00e4bcddd4a 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -5027,12 +5027,14 @@ public class io/sentry/cache/EnvelopeCache : io/sentry/cache/IEnvelopeCache { protected final field sessionLock Lio/sentry/util/AutoClosableReentrantLock; public fun (Lio/sentry/SentryOptions;Ljava/lang/String;I)V public static fun create (Lio/sentry/SentryOptions;)Lio/sentry/cache/IEnvelopeCache; + public fun deleteCurrentSessionFile (Ljava/lang/String;)V public fun discard (Lio/sentry/SentryEnvelope;)V public fun flushPreviousSession ()V public static fun getCurrentSessionFile (Ljava/lang/String;)Ljava/io/File; public static fun getPreviousSessionFile (Ljava/lang/String;)Ljava/io/File; public fun iterator ()Ljava/util/Iterator; public fun movePreviousSession (Ljava/io/File;Ljava/io/File;)V + public fun movePreviousSession (Ljava/io/File;Ljava/io/File;Lio/sentry/IScopes;)V public fun persistCurrentSession (Lio/sentry/Session;)V public fun store (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)V public fun storeEnvelope (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)Z diff --git a/sentry/src/main/java/io/sentry/MovePreviousSession.java b/sentry/src/main/java/io/sentry/MovePreviousSession.java index 6b7de16d81a..ece78e0b31a 100644 --- a/sentry/src/main/java/io/sentry/MovePreviousSession.java +++ b/sentry/src/main/java/io/sentry/MovePreviousSession.java @@ -10,9 +10,11 @@ final class MovePreviousSession implements Runnable { private final @NotNull SentryOptions options; + private final @NotNull IScopes scopes; - MovePreviousSession(final @NotNull SentryOptions options) { + MovePreviousSession(final @NotNull SentryOptions options, final @NotNull IScopes scopes) { this.options = options; + this.scopes = scopes; } @Override @@ -28,7 +30,7 @@ public void run() { final File currentSessionFile = EnvelopeCache.getCurrentSessionFile(cacheDirPath); final File previousSessionFile = EnvelopeCache.getPreviousSessionFile(cacheDirPath); - ((EnvelopeCache) cache).movePreviousSession(currentSessionFile, previousSessionFile); + ((EnvelopeCache) cache).movePreviousSession(currentSessionFile, previousSessionFile, scopes); ((EnvelopeCache) cache).flushPreviousSession(); } diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index 8112cf0ee8b..d15c5730f3d 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -380,7 +380,7 @@ private static void init(final @NotNull SentryOptions options, final boolean glo e); } - movePreviousSession(options); + movePreviousSession(options, rootScopes); // when integrations are registered on Scopes ctor and async integrations are fired, // it might and actually happened that integrations called captureSomething // and Scopes was still NoOp. @@ -543,10 +543,11 @@ private static void handleAppStartProfilingConfig( } @SuppressWarnings("FutureReturnValueIgnored") - private static void movePreviousSession(final @NotNull SentryOptions options) { + private static void movePreviousSession( + final @NotNull SentryOptions options, final @NotNull IScopes scopes) { // enqueue a task to move previous unfinished session to its own file try { - options.getExecutorService().submit(new MovePreviousSession(options)); + options.getExecutorService().submit(new MovePreviousSession(options, scopes)); } catch (Throwable e) { options.getLogger().log(SentryLevel.DEBUG, "Failed to move previous session.", e); } diff --git a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java index d3f473cfbc9..95c440c6257 100644 --- a/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java +++ b/sentry/src/main/java/io/sentry/cache/EnvelopeCache.java @@ -9,6 +9,7 @@ import com.jakewharton.nopen.annotation.Open; import io.sentry.DateUtils; import io.sentry.Hint; +import io.sentry.IScopes; import io.sentry.ISentryLifecycleToken; import io.sentry.SentryCrashLastRunState; import io.sentry.SentryEnvelope; @@ -50,6 +51,7 @@ import java.util.WeakHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -124,12 +126,9 @@ private boolean storeInternal(final @NotNull SentryEnvelope envelope, final @Not final File previousSessionFile = getPreviousSessionFile(directoryPath); if (HintUtils.hasType(hint, SessionEnd.class)) { - try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { - lastPersistedSessionId = null; - if (!currentSessionFile.delete()) { - options.getLogger().log(WARNING, "Current envelope doesn't exist."); - } - } + final @Nullable Session endedSession = readSessionFromEnvelope(envelope); + deleteCurrentSessionFile( + currentSessionFile, endedSession != null ? endedSession.getSessionId() : null); } if (HintUtils.hasType(hint, AbnormalExit.class) @@ -291,12 +290,9 @@ private void writeCrashMarkerFile() { } private @Nullable Session readSessionFromEnvelope(final @NotNull SentryEnvelope envelope) { - final Iterable items = envelope.getItems(); - - // we know that an envelope with a SessionStart hint has a single item inside - if (items.iterator().hasNext()) { - final SentryEnvelopeItem item = items.iterator().next(); - + // a SessionStart or SessionEnd envelope has a single session item, but a crash envelope + // (UncaughtExceptionHint, which is a SessionEnd) has the event first and the session after it + for (final SentryEnvelopeItem item : envelope.getItems()) { if (SentryItemType.Session.equals(item.getHeader().getType())) { try (final Reader reader = new BufferedReader( @@ -315,17 +311,9 @@ private void writeCrashMarkerFile() { } catch (Throwable e) { options.getLogger().log(ERROR, "Item failed to process.", e); } - } else { - options - .getLogger() - .log( - INFO, - "Current envelope has a different envelope type %s", - item.getHeader().getType()); } - } else { - options.getLogger().log(INFO, "Current envelope is empty."); } + options.getLogger().log(INFO, "Current envelope has no session item."); return null; } @@ -388,11 +376,75 @@ 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 - lastPersistedSessionId = written ? session.getSessionId() : null; + final String directoryPath = directory.getOrCreate().getAbsolutePath(); + final File currentSessionFile = getCurrentSessionFile(directoryPath); + final @Nullable String sessionId = session.getSessionId(); + // This can run before the init-time move, while the file still holds the last run's + // session. Move that session first instead of overwriting it. Once the previous session is + // handled, any other session in the file is an earlier one of this process, and moving it + // would leave a stale previous session file for the next launch to send again. The file is + // only read in that startup window, and only when we did not write this session to it last. + boolean moveFailed = false; + if (previousSessionLatch.getCount() > 0 + && (sessionId == null || !sessionId.equals(lastPersistedSessionId))) { + final @Nullable String fileSessionId = readSessionId(currentSessionFile); + if (fileSessionId != null && !fileSessionId.equals(sessionId)) { + moveFailed = + !moveCurrentToPreviousSession( + currentSessionFile, getPreviousSessionFile(directoryPath)); + } + } + // If the move failed, this still writes: a rename that fails keeps failing, and the next + // SessionStart would write over the last run's session anyway. + final boolean written = writeSessionToDisk(currentSessionFile, session); + // After a failed write, delete the file so a later move does not put it over the last run's + // session. If the move failed, the file is the last run's session: it is intact if the write + // failed to open it (a read-only file, for example), so it stays for a later move to retry. + // If the write opened it before it failed, it is truncated and lost either way; a later move + // then turns it into a previous session file that PreviousSessionFinalizer cannot parse and + // deletes. + if (!written && !moveFailed && !currentSessionFile.delete()) { + options + .getLogger() + .log(WARNING, "Unable to delete the current session file after a failed write."); + } + lastPersistedSessionId = written ? sessionId : null; + } + } + + /** + * Deletes the current session file for a session that ended, unless the file holds a different + * session. + * + * @param endedSessionId the id of the session that ended, or null to delete the file anyway + */ + @ApiStatus.Internal + public void deleteCurrentSessionFile(final @Nullable String endedSessionId) { + deleteCurrentSessionFile( + getCurrentSessionFile(directory.getFile().getAbsolutePath()), endedSessionId); + } + + /** + * The end of a session is stored on the transport thread, but a hybrid {@link + * #persistCurrentSession(Session)} writes on the caller's thread. So the file can already hold + * the next session, or, before the init-time move, the last run's session. Then it must stay. + */ + private void deleteCurrentSessionFile( + final @NotNull File currentSessionFile, final @Nullable String endedSessionId) { + try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { + if (endedSessionId != null) { + final @Nullable String fileSessionId = readSessionId(currentSessionFile); + if (fileSessionId != null && !fileSessionId.equals(endedSessionId)) { + options + .getLogger() + .log(DEBUG, "Current session file holds another session, not deleting it."); + return; + } + } + lastPersistedSessionId = null; + if (!currentSessionFile.delete()) { + options.getLogger().log(WARNING, "Current envelope doesn't exist."); + } } } @@ -508,10 +560,71 @@ public void flushPreviousSession() { public void movePreviousSession( final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { + moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); + } + + /** + * The init-time move of the last run's session to the previous session file. It runs on an + * executor, so a hybrid {@link #persistCurrentSession(Session)} or a {@link SessionStart} can + * write the live session to the current session file first. Then the file holds the scopes' + * session, and it is not moved. + */ + @ApiStatus.Internal + public void movePreviousSession( + final @NotNull File currentSessionFile, + final @NotNull File previousSessionFile, + final @NotNull IScopes scopes) { try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { - if (!currentSessionFile.exists()) { + // Read the live session under this lock, so the file cannot get a newer session between the + // two reads. If the scopes have no session yet, the file cannot hold a live one. + final @Nullable String liveSessionId = liveSessionId(scopes); + if (liveSessionId != null && liveSessionId.equals(readSessionId(currentSessionFile))) { + options.getLogger().log(DEBUG, "Current session file holds the live session, not moving."); return; } + moveCurrentToPreviousSession(currentSessionFile, previousSessionFile); + } + } + + /** + * Runs under {@link #sessionLock}, so it must stay lock-free: {@link + * #persistCurrentSession(Session)} holds a scope's session lock and then takes {@link + * #sessionLock}. {@code configureScope} only runs the callback, and {@code getSession()} reads a + * volatile field; {@code withSession} would take the scope's session lock and could deadlock. + */ + private static @Nullable String liveSessionId(final @NotNull IScopes scopes) { + final @NotNull AtomicReference sessionId = new AtomicReference<>(); + scopes.configureScope(scope -> { + final @Nullable Session session = scope.getSession(); + sessionId.set(session != null ? session.getSessionId() : null); + }); + return sessionId.get(); + } + + /** The session id in the file, or null if the file is missing or holds no valid session. */ + private @Nullable String readSessionId(final @NotNull File sessionFile) { + try (final Reader reader = + new BufferedReader(new InputStreamReader(new FileInputStream(sessionFile), UTF_8))) { + final @Nullable Session session = serializer.getValue().deserialize(reader, Session.class); + return session != null ? session.getSessionId() : null; + } catch (FileNotFoundException e) { + // no file is a normal case, so open it directly instead of checking exists() first + return null; + } catch (IOException e) { + options.getLogger().log(DEBUG, e, "Unable to read the session file: %s", sessionFile); + return null; + } + } + + /** + * @return whether the current session file is out of the way: moved, or not there at all + */ + private boolean moveCurrentToPreviousSession( + final @NotNull File currentSessionFile, final @NotNull File previousSessionFile) { + try (final @NotNull ISentryLifecycleToken ignored = sessionLock.acquire()) { + if (!currentSessionFile.exists()) { + return true; + } if (previousSessionFile.exists()) { options.getLogger().log(DEBUG, "Previous session file already exists, deleting it."); @@ -529,10 +642,12 @@ public void movePreviousSession( if (!renamed) { options.getLogger().log(WARNING, "Unable to move current session to previous session."); } + return renamed; } catch (Throwable e) { options .getLogger() .log(SentryLevel.ERROR, "Error moving current session to previous session.", e); + return false; } } } diff --git a/sentry/src/test/java/io/sentry/MovePreviousSessionTest.kt b/sentry/src/test/java/io/sentry/MovePreviousSessionTest.kt index f14cbd6d016..cda5f6fe374 100644 --- a/sentry/src/test/java/io/sentry/MovePreviousSessionTest.kt +++ b/sentry/src/test/java/io/sentry/MovePreviousSessionTest.kt @@ -13,6 +13,7 @@ import kotlin.test.assertTrue import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.same import org.mockito.kotlin.verify class MovePreviousSessionTest { @@ -34,7 +35,7 @@ class MovePreviousSessionTest { options.cacheDirPath = cacheDirPath options.isEnableAutoSessionTracking = isEnableSessionTracking options.setEnvelopeDiskCache(envelopeCache ?: EnvelopeCache.create(options)) - return MovePreviousSession(options) + return MovePreviousSession(options, NoOpScopes.getInstance()) } fun cleanup() { @@ -60,10 +61,22 @@ class MovePreviousSessionTest { sut.run() - verify(fixture.cache, never()).movePreviousSession(any(), any()) + verify(fixture.cache, never()).movePreviousSession(any(), any(), any()) verify(fixture.cache, never()).flushPreviousSession() } + @Test + fun `passes its scopes to the cache so the live session is not moved`() { + val scopes = mock() + fixture.options.cacheDirPath = fixture.tempDir.toAbsolutePath().toFile().absolutePath + fixture.options.setEnvelopeDiskCache(fixture.cache) + + MovePreviousSession(fixture.options, scopes).run() + + verify(fixture.cache).movePreviousSession(any(), any(), same(scopes)) + verify(fixture.cache).flushPreviousSession() + } + @Test fun `when session tracking is disabled, still moves previous session`() { val sut = fixture.getSUT(isEnableSessionTracking = false) @@ -88,7 +101,7 @@ class MovePreviousSessionTest { sut.run() - verify(fixture.cache, never()).movePreviousSession(any(), any()) + verify(fixture.cache, never()).movePreviousSession(any(), any(), any()) verify(fixture.cache, never()).flushPreviousSession() } diff --git a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt index 0cc2c968195..9c4fc77ec96 100644 --- a/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt +++ b/sentry/src/test/java/io/sentry/cache/EnvelopeCacheTest.kt @@ -4,10 +4,15 @@ import com.google.common.truth.Truth.assertThat import io.sentry.DateUtils import io.sentry.Hint import io.sentry.ILogger +import io.sentry.IScope +import io.sentry.IScopes import io.sentry.ISerializer import io.sentry.NoOpLogger +import io.sentry.ScopeCallback import io.sentry.SentryCrashLastRunState import io.sentry.SentryEnvelope +import io.sentry.SentryEnvelopeHeader +import io.sentry.SentryEnvelopeItem import io.sentry.SentryEvent import io.sentry.SentryOptions import io.sentry.SentryUUID @@ -36,6 +41,7 @@ import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.same @@ -227,7 +233,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) @@ -299,24 +305,22 @@ class EnvelopeCacheTest { } @Test - fun `SessionEnd deleting the persisted session lets the delayed SessionStart write it again`() { + fun `queued SessionEnd of the previous session keeps the persisted live session`() { val cache = fixture.getSUT() val sid = SentryUUID.generateSentryId() val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) - cache.persistCurrentSession(createSession(sessionId = sid)) + val liveSession = createSession(sessionId = sid) + liveSession.recordNonTerminatingUnhandledError() + cache.persistCurrentSession(liveSession) - // the previous session's end envelope is still queued and deletes the file the live session - // was just written to - val endedSession = createSession() + // the previous session's end envelope is still queued when the live session is persisted cache.storeEnvelope( - SentryEnvelope.from(fixture.options.serializer, endedSession, null), + SentryEnvelope.from(fixture.options.serializer, createSession(), null), HintUtils.createWithTypeCheckHint(SessionEndHint()), ) - assertThat(currentSessionFile.exists()).isFalse() - - val delayedStart = createSession(sessionId = sid) + // so is the live session's start, which is older than the persisted copy cache.storeEnvelope( - SentryEnvelope.from(fixture.options.serializer, delayedStart, null), + SentryEnvelope.from(fixture.options.serializer, createSession(sessionId = sid), null), HintUtils.createWithTypeCheckHint(SessionStartHint()), ) @@ -326,6 +330,63 @@ class EnvelopeCacheTest { Session::class.java, )!! assertThat(persistedSession.sessionId).isEqualTo(sid) + assertThat(persistedSession.hasNonTerminatingUnhandledError()).isTrue() + } + + @Test + fun `crash envelope with the session after the event keeps a file that holds another session`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val otherSession = writeSession(currentSessionFile, createSession()) + val serializer = fixture.options.serializer + val envelope = + SentryEnvelope( + SentryEnvelopeHeader(), + listOf( + SentryEnvelopeItem.fromEvent(serializer, SentryEvent()), + SentryEnvelopeItem.fromSession(serializer, createSession()), + ), + ) + + cache.storeEnvelope( + envelope, + HintUtils.createWithTypeCheckHint(UncaughtExceptionHint(0, NoOpLogger.getInstance())), + ) + + assertThat(readSessionId(currentSessionFile)).isEqualTo(otherSession.sessionId) + } + + @Test + fun `deleteCurrentSessionFile deletes the file of the ended session`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val endedSession = writeSession(currentSessionFile, createSession()) + + cache.deleteCurrentSessionFile(endedSession.sessionId) + + assertThat(currentSessionFile.exists()).isFalse() + } + + @Test + fun `deleteCurrentSessionFile keeps a file that holds another session`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val otherSession = writeSession(currentSessionFile, createSession()) + + cache.deleteCurrentSessionFile(SentryUUID.generateSentryId()) + + assertThat(readSessionId(currentSessionFile)).isEqualTo(otherSession.sessionId) + } + + @Test + fun `deleteCurrentSessionFile without a session id deletes the file`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + writeSession(currentSessionFile, createSession()) + + cache.deleteCurrentSessionFile(null) + + assertThat(currentSessionFile.exists()).isFalse() } @Test @@ -347,6 +408,29 @@ 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")) + // first the persist reads the last run's session file, then the SessionStart reads its envelope + whenever(serializer.deserialize(any(), eq(Session::class.java))) + .thenReturn(createSession(), 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 +905,144 @@ 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!!) + val lastRunSession = writeSession(currentSessionFile, createSession()) + val liveSession = createSession() + + // a hybrid SDK persists the live session before the executor runs MovePreviousSession + cache.persistCurrentSession(liveSession) + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(liveSession)) + + assertThat(readSessionId(previousSessionFile)).isEqualTo(lastRunSession.sessionId) + assertThat(readSessionId(currentSessionFile)).isEqualTo(liveSession.sessionId) + } + + @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!!) + val lastRunSession = writeSession(currentSessionFile, createSession()) + val liveSession = createSession() + + cache.storeEnvelope( + SentryEnvelope.from(fixture.options.serializer, liveSession, null), + HintUtils.createWithTypeCheckHint(SessionStartHint()), + ) + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(liveSession)) + + assertThat(readSessionId(previousSessionFile)).isEqualTo(lastRunSession.sessionId) + assertThat(readSessionId(currentSessionFile)).isEqualTo(liveSession.sessionId) + } + + @Test + fun `init-time move moves the last run's session when the live session is not written yet`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + val lastRunSession = writeSession(currentSessionFile, createSession()) + + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(createSession())) + + assertThat(currentSessionFile.exists()).isFalse() + assertThat(readSessionId(previousSessionFile)).isEqualTo(lastRunSession.sessionId) + } + + @Test + fun `init-time move without a live session moves the last run's session`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + val lastRunSession = writeSession(currentSessionFile, createSession()) + + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(null)) + + assertThat(currentSessionFile.exists()).isFalse() + assertThat(readSessionId(previousSessionFile)).isEqualTo(lastRunSession.sessionId) + } + + @Test + fun `persistCurrentSession after the previous session was handled does not move an earlier session of this process`() { + val cache = fixture.getSUT() + val currentSessionFile = EnvelopeCache.getCurrentSessionFile(fixture.options.cacheDirPath!!) + val previousSessionFile = EnvelopeCache.getPreviousSessionFile(fixture.options.cacheDirPath!!) + cache.flushPreviousSession() + // the earlier session's SessionEnd is still queued, so its file is still there + writeSession(currentSessionFile, createSession()) + val nextSession = createSession() + + cache.persistCurrentSession(nextSession) + + assertThat(previousSessionFile.exists()).isFalse() + assertThat(readSessionId(currentSessionFile)).isEqualTo(nextSession.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!!) + writeSession(currentSessionFile, createSession()) + // 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, scopesWith(liveSession)) + + assertThat(previousSessionFile.exists()).isFalse() + assertThat(readSessionId(currentSessionFile)).isEqualTo(liveSession.sessionId) + } + + @Test + fun `failed move and failed write in persistCurrentSession leave the file for a later move`() { + val lastRunSession = createSession() + 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(lastRunSession) + 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 is not deleted, because it is the last run's session. Here the throwing serializer + // truncated it; a write that fails to open the file leaves it intact for the later move. + assertThat(currentSessionFile.exists()).isTrue() + + assertTrue(previousSessionFile.deleteRecursively()) + cache.movePreviousSession(currentSessionFile, previousSessionFile, scopesWith(liveSession)) + + assertThat(currentSessionFile.exists()).isFalse() + assertThat(previousSessionFile.exists()).isTrue() + } + + private fun writeSession(file: File, session: Session): Session { + file.bufferedWriter().use { fixture.options.serializer.serialize(session, it) } + return session + } + + private fun readSessionId(file: File): String? = + file.bufferedReader().use { + fixture.options.serializer.deserialize(it, Session::class.java)?.sessionId + } + + private fun scopesWith(session: Session?): IScopes { + val scope = mock() + whenever(scope.session).thenReturn(session) + val scopes = mock() + doAnswer { (it.arguments[0] as ScopeCallback).run(scope) } + .whenever(scopes) + .configureScope(any()) + return scopes + } }