Skip to content
Open
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 @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -407,31 +409,39 @@ private static void addTimeSpanToSerializedSpans(TimeSpan span, List<Map<String,

@SuppressWarnings("FutureReturnValueIgnored")
private static void deleteCurrentSessionFile(
final @NotNull SentryOptions options, boolean isSync) {
final @NotNull SentryOptions options, final @Nullable String sessionId, boolean isSync) {
if (!isSync) {
try {
options
.getExecutorService()
.submit(() -> {
deleteCurrentSessionFile(options);
deleteCurrentSessionFile(options, sessionId);
});
} catch (Throwable e) {
options
.getLogger()
.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.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Session>()
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()
Expand Down
2 changes: 2 additions & 0 deletions sentry/api/sentry.api
Original file line number Diff line number Diff line change
Expand Up @@ -5027,12 +5027,14 @@ public class io/sentry/cache/EnvelopeCache : io/sentry/cache/IEnvelopeCache {
protected final field sessionLock Lio/sentry/util/AutoClosableReentrantLock;
public fun <init> (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
Expand Down
6 changes: 4 additions & 2 deletions sentry/src/main/java/io/sentry/MovePreviousSession.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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();
}
Expand Down
7 changes: 4 additions & 3 deletions sentry/src/main/java/io/sentry/Sentry.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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);
}
Expand Down
169 changes: 142 additions & 27 deletions sentry/src/main/java/io/sentry/cache/EnvelopeCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -291,12 +290,9 @@ private void writeCrashMarkerFile() {
}

private @Nullable Session readSessionFromEnvelope(final @NotNull SentryEnvelope envelope) {
final Iterable<SentryEnvelopeItem> 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(
Expand All @@ -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;
}

Expand Down Expand Up @@ -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.");
}
}
}

Expand Down Expand Up @@ -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<String> 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.");
Expand All @@ -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;
}
}
}
Expand Down
Loading
Loading