diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 8e39c9f533..6d9b7b62e6 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -213,7 +213,7 @@ public final class io/sentry/android/core/AppStartExtension$ExtendedAppStart { public fun (Lio/sentry/ITransaction;Lio/sentry/ISpan;)V } -public final class io/sentry/android/core/AppState : java/io/Closeable { +public final class io/sentry/android/core/AppState : io/sentry/android/core/AppStateProvider, java/io/Closeable { public fun addAppStateListener (Lio/sentry/android/core/AppState$AppStateListener;)V public fun close ()V public static fun getInstance ()Lio/sentry/android/core/AppState; @@ -437,6 +437,7 @@ public final class io/sentry/android/core/SentryAndroidDateProvider : io/sentry/ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/SentryOptions { public fun ()V + public fun close ()V public fun enableAllAutoBreadcrumbs (Z)V public fun getAnrProfilingSampleRate ()Ljava/lang/Double; public fun getAnrTimeoutIntervalMillis ()J @@ -444,6 +445,7 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr public fun getBeforeViewHierarchyCaptureCallback ()Lio/sentry/android/core/SentryAndroidOptions$BeforeCaptureCallback; public fun getDebugImagesLoader ()Lio/sentry/android/core/IDebugImagesLoader; public fun getFrameMetricsCollector ()Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector; + public fun getHangRecorder ()Lio/sentry/android/core/hang/HangRecorder; public fun getMonotonicTicker ()Lio/sentry/time/MonotonicTicker; public fun getNativeSdkName ()Ljava/lang/String; public fun getNdkAppHangTimeoutIntervalMillis ()J @@ -514,6 +516,7 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr public fun setEnableSystemEventBreadcrumbs (Z)V public fun setEnableSystemEventBreadcrumbsExtras (Z)V public fun setFrameMetricsCollector (Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;)V + public fun setHangRecorder (Lio/sentry/android/core/hang/HangRecorder;)V public fun setMemoryLimiterEnabled (Z)V public fun setNativeHandlerStrategy (Lio/sentry/android/core/NdkHandlerStrategy;)V public fun setNativeSdkName (Ljava/lang/String;)V @@ -811,6 +814,12 @@ public final class io/sentry/android/core/cache/AndroidEnvelopeCache : io/sentry public fun storeEnvelope (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)Z } +public final class io/sentry/android/core/hang/HandlerThreadPoster : io/sentry/android/core/hang/ThreadPoster { + public fun (Landroid/os/Handler;)V + public fun post (Ljava/lang/Runnable;)V + public fun remove (Ljava/lang/Runnable;)V +} + public abstract interface class io/sentry/android/core/hang/HangDataCollector : java/io/Closeable { public abstract fun close ()V public abstract fun onRecordingCanceled ()V diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java index 52a54b339d..3e7cfd65ff 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java @@ -9,11 +9,14 @@ import android.content.Context; import android.content.pm.PackageInfo; import android.os.Build; +import android.os.Handler; +import android.os.Looper; import io.sentry.CompositePerformanceCollector; import io.sentry.DeduplicateMultithreadedEventProcessor; import io.sentry.DefaultCompositePerformanceCollector; import io.sentry.DefaultVersionDetector; import io.sentry.IContinuousProfiler; +import io.sentry.IDebugManager; import io.sentry.ILogger; import io.sentry.ISentryLifecycleToken; import io.sentry.ITransactionProfiler; @@ -32,6 +35,11 @@ import io.sentry.android.core.anr.AnrProfileRotationHelper; import io.sentry.android.core.anr.AnrProfilingIntegration; import io.sentry.android.core.cache.AndroidEnvelopeCache; +import io.sentry.android.core.hang.HandlerThreadPoster; +import io.sentry.android.core.hang.HangRecorder; +import io.sentry.android.core.hang.ThreadHangSignal; +import io.sentry.android.core.hang.ThreadPoster; +import io.sentry.android.core.hang.ThreadSampleCollector; import io.sentry.android.core.internal.debugmeta.AssetsDebugMetaLoader; import io.sentry.android.core.internal.gestures.AndroidViewGestureTargetLocator; import io.sentry.android.core.internal.modules.AssetsModulesLoader; @@ -53,6 +61,9 @@ import io.sentry.internal.modules.NoOpModulesLoader; import io.sentry.internal.viewhierarchy.ViewHierarchyExporter; import io.sentry.protocol.SentryId; +import io.sentry.time.EpochClock; +import io.sentry.time.JavaMonotonicTicker; +import io.sentry.time.MonotonicTicker; import io.sentry.transport.CurrentDateProvider; import io.sentry.transport.NoOpEnvelopeCache; import io.sentry.transport.NoOpTransportGate; @@ -61,6 +72,7 @@ import io.sentry.util.thread.NoOpThreadChecker; import java.io.File; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -258,9 +270,12 @@ static void initializeIntegrationsAndProcessors( if (options.getThreadChecker() instanceof NoOpThreadChecker) { options.setThreadChecker(AndroidThreadChecker.getInstance()); } - if (options.getDebugManager() == null) { - options.setDebugManager(new AndroidDebugManager()); + @Nullable IDebugManager debugManager = options.getDebugManager(); + if (debugManager == null) { + debugManager = new AndroidDebugManager(); + options.setDebugManager(debugManager); } + setupHangRecorder(options, debugManager); if (options.getSocketTagger() instanceof NoOpSocketTagger) { options.setSocketTagger(AndroidSocketTagger.getInstance()); } @@ -516,6 +531,38 @@ static void installDefaultIntegrations( .setFormHandler(new SentryAndroidOptions.AndroidUserFeedbackFormHandler()); } + private static void setupHangRecorder( + final @NotNull SentryAndroidOptions options, final @NotNull IDebugManager debugManager) { + if (options.getCacheDirPath() == null || options.getHangRecorder() != null) { + return; + } + final @NotNull Looper mainLooper = Looper.getMainLooper(); + final @NotNull ThreadPoster mainThreadPoster = new HandlerThreadPoster(new Handler(mainLooper)); + // options.getMonotonicTicker() counts device sleep, which would read as a hang. + final @NotNull MonotonicTicker ticker = JavaMonotonicTicker.getInstance(); + final @NotNull EpochClock epochClock = options.getEpochClock(); + final @NotNull HangRecorder recorder = + new HangRecorder( + options, + AppState.getInstance(), + ticker, + epochClock, + HangRecorder.DEFAULT_POLLING_INTERVAL_MS, + HangRecorder.DEFAULT_MAX_RECORDING_TIME_MS, + HangRecorder.DEFAULT_EXECUTOR_FACTORY, + metronome -> + Collections.singletonList( + new ThreadHangSignal( + metronome, + ticker, + debugManager, + mainThreadPoster, + HangRecorder.DEFAULT_SUSPICIOUS_THRESHOLD_MS)), + Collections.singletonList( + new ThreadSampleCollector(options, epochClock, ticker, mainLooper.getThread()))); + options.setHangRecorder(recorder); + } + /** * Reads and sets default option values that are Android specific like release and inApp * diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java index 24562e3aa4..08897de956 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java @@ -22,7 +22,7 @@ /** AppState holds the state of the App, e.g. whether the app is in background/foreground, etc. */ @ApiStatus.Internal -public final class AppState implements Closeable { +public final class AppState implements Closeable, AppStateProvider { private static @NotNull AppState instance = new AppState(); private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); private volatile @Nullable LifecycleObserver lifecycleObserver; @@ -61,6 +61,7 @@ void setInBackground(final boolean inBackground) { this.inBackground = inBackground; } + @Override public void addAppStateListener(final @NotNull AppStateListener listener) { try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { ensureLifecycleObserver(NoOpLogger.getInstance()); @@ -71,6 +72,7 @@ public void addAppStateListener(final @NotNull AppStateListener listener) { } } + @Override public void removeAppStateListener(final @NotNull AppStateListener listener) { try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { if (lifecycleObserver != null) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java index 2afb245fe3..9789d070af 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java @@ -14,6 +14,7 @@ import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.SpanStatus; +import io.sentry.android.core.hang.HangRecorder; import io.sentry.android.core.internal.time.AndroidMonotonicTicker; import io.sentry.android.core.internal.util.RootChecker; import io.sentry.android.core.internal.util.SentryFrameMetricsCollector; @@ -333,6 +334,8 @@ public interface BeforeCaptureCallback { private boolean enableAnrFingerprinting = true; + private volatile @Nullable HangRecorder hangRecorder; + public SentryAndroidOptions() { setSentryClientName(BuildConfig.SENTRY_ANDROID_SDK_NAME + "/" + BuildConfig.VERSION_NAME); setSdkVersion(createSdkVersion()); @@ -977,6 +980,10 @@ public void setEnableSystemEventBreadcrumbsExtras( * Sets the sample rate for capturing main-thread stack profiles when a foreground ANR is * detected. The profile is attached to the ANR event on the next app start. * + *

The sampling decision is made once per SDK initialization, so a process records the stacks + * of all its hangs, or of none. Stack sampling starts after the main thread was blocked for 300 + * ms. + * *

Use {@code null} to disable ANR profiling (default). Values must be between {@code 0.0} and * {@code 1.0}. * @@ -1002,6 +1009,30 @@ public boolean isAnrProfilingEnabled() { return anrProfilingSampleRate != null && anrProfilingSampleRate > 0; } + /** + * The recorder that the ANR integrations share. Null if {@link #getCacheDirPath()} was null at + * init. + */ + @ApiStatus.Internal + public @Nullable HangRecorder getHangRecorder() { + return hangRecorder; + } + + @ApiStatus.Internal + public void setHangRecorder(final @Nullable HangRecorder hangRecorder) { + this.hangRecorder = hangRecorder; + } + + @ApiStatus.Internal + @Override + public void close() { + super.close(); + final @Nullable HangRecorder recorder = hangRecorder; + if (recorder != null) { + recorder.close(); + } + } + /** * Returns whether ANR fingerprinting is enabled. When enabled, the SDK assigns static * fingerprints to ANR events that would otherwise produce noisy grouping. Currently, this applies diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java index 204d4c5c65..e1f206b0a4 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; /** - * Coordinates file rotation between AnrProfilingIntegration and AnrV2Integration to prevent + * Coordinates file rotation between ThreadSampleCollector and AnrV2Integration to prevent * concurrent access to the same QueueFile. */ @ApiStatus.Internal diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java index 018fd49f6f..f6c53d8dd2 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java @@ -2,347 +2,109 @@ import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion; -import android.os.Handler; -import android.os.Looper; -import io.sentry.IDebugManager; import io.sentry.ILogger; import io.sentry.IScopes; -import io.sentry.ISentryLifecycleToken; import io.sentry.Integration; -import io.sentry.NoOpLogger; import io.sentry.SentryLevel; import io.sentry.SentryOptions; import io.sentry.android.core.AppState; import io.sentry.android.core.SentryAndroidOptions; -import io.sentry.time.MonotonicTicker; -import io.sentry.time.Stopwatch; -import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.android.core.hang.HangRecord; +import io.sentry.android.core.hang.HangRecorder; +import io.sentry.android.core.hang.HangRecorderListener; import io.sentry.util.Objects; import io.sentry.util.SentryRandom; import java.io.Closeable; -import java.io.File; import java.io.IOException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import org.jetbrains.annotations.ApiStatus; +import java.util.concurrent.atomic.AtomicReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.TestOnly; /** * Captures main-thread stack profiles while the app is unresponsive and attaches them to ANR events * on the next app start. * + *

If sampled, subscribes to the {@link HangRecorder} of the options for the SDK lifetime. The + * recorder writes the profile to disk while a subscription exists. + * *

Enable via {@link SentryAndroidOptions#setAnrProfilingSampleRate(Double)} or the {@code * io.sentry.anr.profiling.sample-rate} manifest metadata. */ public final class AnrProfilingIntegration implements Integration, Closeable, AppState.AppStateListener, Runnable { - public static final long POLLING_INTERVAL_MS = 66; - private static final long THRESHOLD_SUSPICION_MS = 1000; + // StackTraceConverter expects the samples this far apart. + public static final long POLLING_INTERVAL_MS = HangRecorder.DEFAULT_POLLING_INTERVAL_MS; public static final long THRESHOLD_ANR_MS = 4000; - static final int MAX_NUM_STACKS = (int) (10_000 / POLLING_INTERVAL_MS); - - private final AtomicBoolean enabled = new AtomicBoolean(true); - - private volatile @Nullable MonotonicTicker ticker; - - private final @NotNull Runnable updater = - () -> { - final @Nullable MonotonicTicker currentTicker = ticker; - if (currentTicker != null) { - lastMainThreadExecutionNanos = currentTicker.tickNanos(); - } - }; - private final @NotNull AutoClosableReentrantLock lifecycleLock = new AutoClosableReentrantLock(); - private final @NotNull AutoClosableReentrantLock profileManagerLock = - new AutoClosableReentrantLock(); - - private volatile long lastMainThreadExecutionNanos; - final AtomicInteger numCollectedStacks = new AtomicInteger(); - private volatile MainThreadState mainThreadState = MainThreadState.IDLE; - private volatile @Nullable AnrProfileManager profileManager; - private volatile @NotNull ILogger logger = NoOpLogger.getInstance(); - private volatile @Nullable SentryAndroidOptions options; - private volatile @Nullable IDebugManager debugManager; - private volatile @Nullable Thread thread = null; - private volatile boolean sampled = false; - private volatile boolean inForeground = false; - private volatile @Nullable Handler mainHandler; - private volatile @Nullable Thread mainThread; + private final @NotNull HangRecorderListener subscription = new DiskProfileSubscription(); + private final @NotNull AtomicReference subscribedRecorder = new AtomicReference<>(); @Override public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { - this.options = + final @NotNull SentryAndroidOptions androidOptions = Objects.requireNonNull( (options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null, "SentryAndroidOptions is required"); - this.logger = options.getLogger(); - final @NotNull MonotonicTicker ticker = options.getMonotonicTicker(); - // A tick's origin is arbitrary, so the default of 0 would read as a stall of unknown length. - this.lastMainThreadExecutionNanos = ticker.tickNanos(); - this.ticker = ticker; - this.debugManager = this.options.getDebugManager(); - - if (this.options.isAnrProfilingEnabled()) { - if (this.options.getCacheDirPath() == null) { - logger.log(SentryLevel.WARNING, "ANR Profiling is enabled but cacheDirPath is not set"); - return; - } - - final Looper mainLooper = Looper.getMainLooper(); - this.mainThread = mainLooper.getThread(); - this.mainHandler = new Handler(mainLooper); - - addIntegrationToSdkVersion("AnrProfiling"); - AppState.getInstance().addAppStateListener(this); - } - } - - @Override - @SuppressWarnings("FutureReturnValueIgnored") - public void close() throws IOException { - enabled.set(false); - AppState.getInstance().removeAppStateListener(this); - - // Remove any pending updater callbacks from the main handler - final @Nullable Handler handler = mainHandler; - if (handler != null) { - handler.removeCallbacks(updater); - } - - // Wake and interrupt the thread so it exits - final @Nullable Thread t = thread; - if (t != null) { - synchronized (this) { - notifyAll(); - } - t.interrupt(); - } - - final @Nullable SentryAndroidOptions opts = options; - final @Nullable AnrProfileManager pm; - try (final @NotNull ISentryLifecycleToken ignored = profileManagerLock.acquire()) { - pm = profileManager; - profileManager = null; - } - if (opts != null) { - try { - opts.getExecutorService() - .submit(() -> { - if (pm == null) { - return; - } - - try { - pm.close(); - } catch (IOException e) { - logger.log(SentryLevel.WARNING, "Failed to close AnrProfileManager"); - } - }); - } catch (Throwable e) { - logger.log(SentryLevel.WARNING, "Failed to submit AnrProfileManager close"); - } - } - } - - @Override - public void onForeground() { - if (!enabled.get()) { + if (!androidOptions.isAnrProfilingEnabled()) { return; } - try (final @NotNull ISentryLifecycleToken ignored = lifecycleLock.acquire()) { - if (inForeground) { - return; - } - inForeground = true; - updater.run(); - - final @Nullable Thread existingThread = thread; - if (existingThread != null && existingThread.isAlive()) { - // Wake the existing thread - synchronized (this) { - notifyAll(); - } - } - if (existingThread == null || !existingThread.isAlive()) { - final @NotNull Thread profilingThread = new Thread(this, "AnrProfilingIntegration"); - profilingThread.setDaemon(true); - profilingThread.start(); - thread = profilingThread; - } - } - } - - @Override - public void onBackground() { - if (!enabled.get()) { + final @NotNull ILogger logger = options.getLogger(); + if (androidOptions.getCacheDirPath() == null) { + logger.log(SentryLevel.WARNING, "ANR Profiling is enabled but cacheDirPath is not set"); return; } - try (final @NotNull ISentryLifecycleToken ignored = lifecycleLock.acquire()) { - inForeground = false; - } - } - - @Override - public void run() { - final @Nullable Handler handler = mainHandler; - final @Nullable Thread mt = mainThread; - if (handler == null || mt == null) { + final @Nullable HangRecorder recorder = androidOptions.getHangRecorder(); + if (recorder == null) { + logger.log(SentryLevel.WARNING, "ANR Profiling is enabled but there is no hang recorder"); return; } - - try { - while (enabled.get() && !Thread.currentThread().isInterrupted()) { - try { - if (!inForeground) { - // Wait until we're back in the foreground or disabled - synchronized (this) { - while (!inForeground && enabled.get()) { - wait(); - } - } - // Reset the updater timestamp after waking to avoid false suspicion - updater.run(); - continue; - } - - checkMainThread(mt); - - handler.removeCallbacks(updater); - handler.post(updater); - - // noinspection BusyWait - Thread.sleep(POLLING_INTERVAL_MS); - } catch (InterruptedException e) { - // Restore interrupt status and exit the polling loop - Thread.currentThread().interrupt(); - return; - } - } - } catch (Throwable t) { - logger.log(SentryLevel.WARNING, "Failed to execute AnrStacktraceIntegration", t); - } - } - - @ApiStatus.Internal - void checkMainThread(final @NotNull Thread mainThread) throws IOException { - if (debugManager != null && debugManager.isDebuggerConnected()) { - // The main thread can sit at a breakpoint for a long time, which is not an ANR. Reset the - // timestamp, so the paused time does not count against us after the debugger detaches. - mainThreadState = MainThreadState.IDLE; - sampled = false; - updater.run(); + final @Nullable Double sampleRate = androidOptions.getAnrProfilingSampleRate(); + if (sampleRate == null || SentryRandom.current().nextDouble() >= sampleRate) { + logger.log(SentryLevel.DEBUG, "ANR Profiling is not sampled"); return; } - - final @Nullable MonotonicTicker currentTicker = ticker; - if (currentTicker == null) { + if (!subscribedRecorder.compareAndSet(null, recorder)) { return; } - final long diff = - TimeUnit.NANOSECONDS.toMillis(currentTicker.tickNanos() - lastMainThreadExecutionNanos); - - if (diff < THRESHOLD_SUSPICION_MS) { - mainThreadState = MainThreadState.IDLE; - sampled = false; - } - - if (mainThreadState == MainThreadState.IDLE && diff > THRESHOLD_SUSPICION_MS) { - if (logger.isEnabled(SentryLevel.DEBUG)) { - logger.log(SentryLevel.DEBUG, "ANR: main thread is suspicious"); - } - mainThreadState = MainThreadState.SUSPICIOUS; - - final @Nullable SentryAndroidOptions opts = options; - final @Nullable Double sampleRate = opts != null ? opts.getAnrProfilingSampleRate() : null; - if (sampleRate != null && SentryRandom.current().nextDouble() < sampleRate) { - sampled = true; - } - - if (sampled) { - clearStacks(); - } - } - - // if we are suspicious and sampled, we need to collect stack traces - if (sampled - && (mainThreadState == MainThreadState.SUSPICIOUS - || mainThreadState == MainThreadState.ANR_DETECTED)) { - if (numCollectedStacks.get() < MAX_NUM_STACKS) { - final @NotNull Stopwatch stopwatch = Stopwatch.started(currentTicker); - final @NotNull AnrStackTrace trace = - new AnrStackTrace(System.currentTimeMillis(), mainThread.getStackTrace()); - if (logger.isEnabled(SentryLevel.DEBUG)) { - logger.log( - SentryLevel.DEBUG, - "AnrWatchdog: capturing main thread stacktrace took " - + stopwatch.elapsed(TimeUnit.MILLISECONDS) - + "ms"); - } - addStackTrace(trace); - } else { - if (logger.isEnabled(SentryLevel.DEBUG)) { - logger.log( - SentryLevel.DEBUG, - "ANR: reached maximum number of collected stack traces, skipping further collection"); - } - } - } - - if (mainThreadState == MainThreadState.SUSPICIOUS && diff > THRESHOLD_ANR_MS) { - if (logger.isEnabled(SentryLevel.DEBUG)) { - logger.log(SentryLevel.DEBUG, "ANR: main thread ANR threshold reached"); - } - mainThreadState = MainThreadState.ANR_DETECTED; - } + recorder.subscribe(subscription); + addIntegrationToSdkVersion("AnrProfiling"); } - @TestOnly - @NotNull - MainThreadState getState() { - return mainThreadState; + @Override + public void close() throws IOException { + final @Nullable HangRecorder recorder = subscribedRecorder.getAndSet(null); + if (recorder != null) { + recorder.unsubscribe(subscription); + } } - @TestOnly - @NotNull - AnrProfileManager getProfileManager() { - try (final @NotNull ISentryLifecycleToken ignored = profileManagerLock.acquire()) { - if (profileManager == null) { - final @NotNull SentryOptions opts = - Objects.requireNonNull(options, "Options can't be null"); - final @Nullable String cacheDirPath = opts.getCacheDirPath(); - if (cacheDirPath == null) { - throw new IllegalStateException("cacheDirPath is required for ANR profiling"); - } - final @NotNull File currentFile = - AnrProfileRotationHelper.getFileForRecording(new File(cacheDirPath)); - profileManager = new AnrProfileManager(opts, currentFile); - } + /** + * @deprecated Not used by the SDK any more. + */ + @Deprecated + @Override + public void onForeground() {} - return profileManager; - } - } + /** + * @deprecated Not used by the SDK any more. + */ + @Deprecated + @Override + public void onBackground() {} - private void clearStacks() throws IOException { - numCollectedStacks.set(0); - getProfileManager().clear(); - } + /** + * @deprecated Not used by the SDK any more. + */ + @Deprecated + @Override + public void run() {} - private void addStackTrace(@NotNull final AnrStackTrace trace) throws IOException { - if (!enabled.get()) { - return; + // Not a lambda: a non-capturing lambda can be one shared instance across integrations. + private static final class DiskProfileSubscription implements HangRecorderListener { + @Override + public void onHangRecorded(final @NotNull HangRecord record) { + // The fatal path reads the profile from disk at the next launch, it needs no record. } - numCollectedStacks.incrementAndGet(); - getProfileManager().add(trace); - } - - protected enum MainThreadState { - IDLE, - SUSPICIOUS, - ANR_DETECTED, } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HandlerThreadPoster.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HandlerThreadPoster.java new file mode 100644 index 0000000000..b9288c80d4 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HandlerThreadPoster.java @@ -0,0 +1,25 @@ +package io.sentry.android.core.hang; + +import android.os.Handler; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +@ApiStatus.Internal +public final class HandlerThreadPoster implements ThreadPoster { + + private final @NotNull Handler handler; + + public HandlerThreadPoster(final @NotNull Handler handler) { + this.handler = handler; + } + + @Override + public void post(final @NotNull Runnable runnable) { + handler.post(runnable); + } + + @Override + public void remove(final @NotNull Runnable runnable) { + handler.removeCallbacks(runnable); + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt index 226ea75397..e87679528e 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt @@ -4,12 +4,15 @@ import android.content.Context import android.content.res.AssetManager import android.os.Build import android.os.Bundle +import android.os.Looper import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat import io.sentry.CompositePerformanceCollector import io.sentry.DefaultCompositePerformanceCollector import io.sentry.IConnectionStatusProvider import io.sentry.IContinuousProfiler +import io.sentry.IDebugManager import io.sentry.ILogger import io.sentry.ISocketTagger import io.sentry.ITransaction @@ -21,6 +24,11 @@ import io.sentry.SentryIntegrationPackageStorage import io.sentry.SentryOptions import io.sentry.android.core.SentryAndroidOptions.AndroidUserFeedbackFormHandler import io.sentry.android.core.cache.AndroidEnvelopeCache +import io.sentry.android.core.hang.HangDataCollector +import io.sentry.android.core.hang.HangRecorder +import io.sentry.android.core.hang.HangSignal +import io.sentry.android.core.hang.ThreadHangSignal +import io.sentry.android.core.hang.ThreadSampleCollector import io.sentry.android.core.internal.debugmeta.AssetsDebugMetaLoader import io.sentry.android.core.internal.gestures.AndroidViewGestureTargetLocator import io.sentry.android.core.internal.modules.AssetsModulesLoader @@ -38,6 +46,8 @@ import io.sentry.internal.debugmeta.IDebugMetaLoader import io.sentry.internal.modules.IModulesLoader import io.sentry.protocol.SentryId import io.sentry.test.ImmediateExecutorService +import io.sentry.test.getProperty +import io.sentry.time.JavaMonotonicTicker import io.sentry.transport.ITransportGate import io.sentry.util.thread.IThreadChecker import java.io.File @@ -682,6 +692,88 @@ class AndroidOptionsInitializerTest { assertTrue { appLifecycleIndex < anrIndex } } + @Test + fun `HangRecorder is created and stored in the options`() { + fixture.initSut() + + val recorder = fixture.sentryOptions.hangRecorder + assertThat(recorder).isNotNull() + assertThat(recorder!!.getProperty("appStateProvider")) + .isSameInstanceAs(AppState.getInstance()) + assertThat(recorder.getProperty("ticker")) + .isSameInstanceAs(JavaMonotonicTicker.getInstance()) + assertThat(recorder.getProperty("epochClock")) + .isSameInstanceAs(fixture.sentryOptions.epochClock) + assertThat(recorder.getProperty("pollingIntervalMs")) + .isEqualTo(HangRecorder.DEFAULT_POLLING_INTERVAL_MS) + assertThat(recorder.getProperty("maxRecordingTimeMs")) + .isEqualTo(HangRecorder.DEFAULT_MAX_RECORDING_TIME_MS) + assertThat(recorder.getProperty("executorFactory")) + .isSameInstanceAs(HangRecorder.DEFAULT_EXECUTOR_FACTORY) + } + + @Test + fun `HangRecorder signal is a ThreadHangSignal with the AndroidDebugManager`() { + fixture.initSut() + + val signal = + fixture.sentryOptions.hangRecorder!!.getProperty>("signals").single() + assertThat(signal).isInstanceOf(ThreadHangSignal::class.java) + assertThat(signal.getProperty("debugManager")) + .isSameInstanceAs(fixture.sentryOptions.debugManager) + assertThat(fixture.sentryOptions.debugManager).isInstanceOf(AndroidDebugManager::class.java) + assertThat(signal.getProperty("ticker")) + .isSameInstanceAs(JavaMonotonicTicker.getInstance()) + assertThat(signal.getProperty("suspiciousThresholdMs")) + .isEqualTo(HangRecorder.DEFAULT_SUSPICIOUS_THRESHOLD_MS) + } + + @Test + fun `HangRecorder signal uses a debug manager that is already set`() { + val debugManager = IDebugManager { false } + fixture.sentryOptions.debugManager = debugManager + + fixture.initSut() + + val signal = + fixture.sentryOptions.hangRecorder!!.getProperty>("signals").single() + assertThat(signal.getProperty("debugManager")).isSameInstanceAs(debugManager) + } + + @Test + fun `HangRecorder collector samples the main thread`() { + fixture.initSut() + + val collector = + fixture.sentryOptions.hangRecorder!! + .getProperty>("collectors") + .single() + assertThat(collector).isInstanceOf(ThreadSampleCollector::class.java) + assertThat(collector.getProperty("epochClock")) + .isSameInstanceAs(fixture.sentryOptions.epochClock) + assertThat(collector.getProperty("ticker")) + .isSameInstanceAs(JavaMonotonicTicker.getInstance()) + assertThat(collector.getProperty("thread")) + .isSameInstanceAs(Looper.getMainLooper().thread) + } + + @Test + fun `HangRecorder that is already set is kept`() { + val existing = mock() + fixture.sentryOptions.hangRecorder = existing + + fixture.initSut() + + assertThat(fixture.sentryOptions.hangRecorder).isSameInstanceAs(existing) + } + + @Test + fun `HangRecorder is not created when cacheDirPath is null`() { + fixture.initSut(configureOptions = { cacheDirPath = null }) + + assertThat(fixture.sentryOptions.hangRecorder).isNull() + } + @Test fun `EnvelopeFileObserverIntegration added to integration list`() { fixture.initSut() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt index 0934ab97a5..3b9b5f13a0 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt @@ -2,6 +2,7 @@ package io.sentry.android.core import io.sentry.ITransactionProfiler import io.sentry.NoOpTransactionProfiler +import io.sentry.android.core.hang.HangRecorder import io.sentry.protocol.DebugImage import kotlin.test.Test import kotlin.test.assertEquals @@ -10,6 +11,7 @@ import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import org.mockito.kotlin.mock +import org.mockito.kotlin.verify class SentryAndroidOptionsTest { @Test @@ -267,6 +269,22 @@ class SentryAndroidOptionsTest { assertEquals(listOf("example.com"), sentryOptions.webViewTracing.allowedHosts) } + @Test + fun `close closes the hang recorder`() { + val sentryOptions = SentryAndroidOptions() + val recorder = mock() + sentryOptions.hangRecorder = recorder + + sentryOptions.close() + + verify(recorder).close() + } + + @Test + fun `close without a hang recorder does not throw`() { + SentryAndroidOptions().close() + } + private class CustomDebugImagesLoader : IDebugImagesLoader { override fun loadDebugImages(): List? = null diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index 2717128af9..794416af60 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt @@ -11,6 +11,7 @@ import android.os.Looper import android.os.SystemClock import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat import io.sentry.Breadcrumb import io.sentry.DateUtils import io.sentry.Hint @@ -31,6 +32,7 @@ import io.sentry.SystemOutLogger import io.sentry.UncaughtExceptionHandlerIntegration import io.sentry.android.core.anr.AnrProfilingIntegration import io.sentry.android.core.cache.AndroidEnvelopeCache +import io.sentry.android.core.hang.HangRecorder import io.sentry.android.core.performance.AppStartMetrics import io.sentry.android.fragment.FragmentLifecycleIntegration import io.sentry.android.replay.ReplayIntegration @@ -200,6 +202,32 @@ class SentryAndroidTest { assertTrue(Sentry.isEnabled()) } + @Test + fun `close closes the hang recorder`() { + val recorder = mock() + fixture.initSut { it.hangRecorder = recorder } + + Sentry.close() + + verify(recorder).close() + } + + @Test + fun `re-init closes the previous hang recorder and creates a new one`() { + val previous = mock() + fixture.initSut { it.hangRecorder = previous } + var options: SentryAndroidOptions? = null + + fixture.initSut { + it.cacheDirPath = tmpDir.newFolder().absolutePath + options = it + } + + verify(previous).close() + assertThat(options!!.hangRecorder).isNotNull() + assertThat(options!!.hangRecorder).isNotSameInstanceAs(previous) + } + @Test fun `when auto-init is disabled and user calls init manually with configuration handler, options should be set`() { assertFalse(Sentry.isEnabled()) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt index 6c3d08c76b..48ad6963e8 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt @@ -5,358 +5,169 @@ import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.IScopes import io.sentry.SentryIntegrationPackageStorage +import io.sentry.SentryLevel import io.sentry.SentryOptions -import io.sentry.android.core.AppState import io.sentry.android.core.SentryAndroidOptions -import io.sentry.test.getProperty -import io.sentry.time.TestMonotonicTicker -import java.util.concurrent.TimeUnit.HOURS -import java.util.concurrent.TimeUnit.MILLISECONDS -import kotlin.test.AfterTest +import io.sentry.android.core.hang.HangRecorder +import io.sentry.android.core.hang.HangRecorderListener import kotlin.test.BeforeTest import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertSame -import kotlin.test.assertTrue +import kotlin.test.assertFailsWith import org.junit.Rule import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.mock -import org.mockito.kotlin.spy -import org.mockito.kotlin.whenever +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions @RunWith(AndroidJUnit4::class) class AnrProfilingIntegrationTest { @get:Rule val tmpDir = TemporaryFolder() - private lateinit var mockScopes: IScopes - private lateinit var mockLogger: ILogger + private val scopes = mock() + private val mockLogger = mock() + private val recorder = mock() private lateinit var options: SentryAndroidOptions - private lateinit var ticker: TestMonotonicTicker @BeforeTest fun setup() { - // A tick origin far from zero, as on any device that has been up a while. Starting at zero - // would let a reading taken against a different origin pass unnoticed. - ticker = TestMonotonicTicker(HOURS.toNanos(30)) - mockScopes = mock() - mockLogger = mock() + SentryIntegrationPackageStorage.getInstance().clearStorage() options = SentryAndroidOptions().apply { cacheDirPath = tmpDir.root.absolutePath setLogger(mockLogger) + isDebug = true anrProfilingSampleRate = 1.0 + hangRecorder = recorder } - AppState.getInstance().resetInstance() } - @AfterTest - fun cleanup() { - AppState.getInstance().resetInstance() - } - - /** `SentryAndroidOptions` is final and has no ticker setter, so a spy supplies [ticker]. */ - private fun withTestTicker(options: SentryAndroidOptions): SentryAndroidOptions = - spy(options).also { whenever(it.monotonicTicker).thenReturn(ticker) } - @Test - fun `onForeground starts monitoring thread`() { + fun `register subscribes to the recorder when sampled`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - integration.onForeground() - Thread.sleep(100) // Allow thread to start + integration.register(scopes, options) - val thread = integration.getProperty("thread") - assertNotNull(thread) - assertTrue(thread.isAlive) - assertEquals("AnrProfilingIntegration", thread.name) + verify(recorder, times(1)).subscribe(any()) + assertThat(SentryIntegrationPackageStorage.getInstance().integrations).contains("AnrProfiling") } @Test - fun `onBackground pauses monitoring thread`() { + fun `register does not subscribe when not sampled`() { + // Enabled, but only a draw of exactly 0.0 is below it. + options.anrProfilingSampleRate = Double.MIN_VALUE val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - integration.onForeground() - Thread.sleep(100) - - val thread = integration.getProperty("thread") - assertNotNull(thread) - integration.onBackground() - Thread.sleep(200) // Allow thread to enter wait state - - // Thread should still be alive but waiting - assertTrue(thread.isAlive) + integration.register(scopes, options) - integration.close() - thread.join(2000) - assertFalse(thread.isAlive) + verify(recorder, never()).subscribe(any()) + assertThat(SentryIntegrationPackageStorage.getInstance().integrations) + .doesNotContain("AnrProfiling") } @Test - fun `close disables integration and interrupts thread`() { + fun `register does not subscribe when ANR profiling is disabled`() { + options.anrProfilingSampleRate = null val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - integration.onForeground() - Thread.sleep(100) - - val thread = integration.getProperty("thread") - assertNotNull(thread) - - assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isNotEmpty()) - integration.close() - thread.join(2000) - - assertTrue(!thread.isAlive) - val enabled = integration.getProperty("enabled") - assertTrue(!enabled.get()) - assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) - } - - @Test - fun `lifecycle methods have no influence after close`() { - val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - integration.close() - integration.onForeground() - integration.onBackground() + integration.register(scopes, options) - val thread = integration.getProperty("thread") - assertTrue(thread == null || !thread.isAlive) + verify(recorder, never()).subscribe(any()) } @Test - fun `multiple foreground calls do not create multiple threads`() { + fun `register does not subscribe when cacheDirPath is null`() { + options.cacheDirPath = null val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - - integration.onForeground() - Thread.sleep(100) - val thread1 = integration.getProperty("thread") - - integration.onForeground() - Thread.sleep(100) - val thread2 = integration.getProperty("thread") - assertNotNull(thread1) - assertNotNull(thread2) - assertEquals(thread1, thread2, "Should reuse the same thread") + integration.register(scopes, options) - integration.close() + verify(recorder, never()).subscribe(any()) + verify(mockLogger) + .log(SentryLevel.WARNING, "ANR Profiling is enabled but cacheDirPath is not set") } @Test - fun `foreground after background reuses thread`() { + fun `register does nothing when there is no recorder`() { + options.hangRecorder = null val integration = AnrProfilingIntegration() - integration.register(mockScopes, options) - - integration.onForeground() - Thread.sleep(100) - val thread1 = integration.getProperty("thread") - - integration.onBackground() - integration.onForeground() - - Thread.sleep(100) - val thread2 = integration.getProperty("thread") - - assertNotNull(thread1) - assertNotNull(thread2) - assertSame(thread1, thread2, "Should reuse the same thread after background") - assertTrue(thread1.isAlive) + integration.register(scopes, options) integration.close() - } - - @Test - fun `properly walks through state transitions and collects stack traces`() { - val mainThread = Thread.currentThread() - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 1.0 - } - - val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(androidOptions)) - // Drive the state machine synchronously to avoid racing the background polling thread. - - ticker.advance(900, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.IDLE, integration.state) - assertTrue(integration.profileManager.load().stacks.isEmpty()) - - ticker.advance(2_000, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.SUSPICIOUS, integration.state) - - ticker.advance(3_000, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.ANR_DETECTED, integration.state) - assertEquals(2, integration.profileManager.load().stacks.size) - - for (i in 0 until AnrProfilingIntegration.MAX_NUM_STACKS + 1) { - integration.checkMainThread(mainThread) - } - assertEquals(AnrProfilingIntegration.MAX_NUM_STACKS, integration.numCollectedStacks.get()) + assertThat(SentryIntegrationPackageStorage.getInstance().integrations) + .doesNotContain("AnrProfiling") } @Test - fun `debugger pauses are treated as idle`() { - val mainThread = Thread.currentThread() - var debuggerConnected = true - - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 1.0 - debugManager = { debuggerConnected } - } - + fun `register requires SentryAndroidOptions`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(androidOptions)) - - ticker.advance(19_000, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.IDLE, integration.state) - assertEquals(0, integration.numCollectedStacks.get()) - - // the time spent paused must not count towards an ANR once the debugger detaches - debuggerConnected = false - ticker.advance(100, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.IDLE, integration.state) + + assertFailsWith { integration.register(scopes, SentryOptions()) } } @Test - fun `background foreground transitions don't trigger an ANR`() { - val mainThread = Thread.currentThread() - - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 1.0 - } - + fun `close unsubscribes the listener it subscribed`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(androidOptions)) - integration.onBackground() + integration.register(scopes, options) - ticker.advance(19_000, MILLISECONDS) - integration.onForeground() + integration.close() - Thread.sleep(100) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.IDLE, integration.state) + val subscribed = argumentCaptor() + verify(recorder).subscribe(subscribed.capture()) + verify(recorder).unsubscribe(subscribed.firstValue) } @Test - fun `does not report a stall when the ticker origin is far from zero`() { + fun `close unsubscribes only once`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(options)) + integration.register(scopes, options) - integration.checkMainThread(Thread.currentThread()) + integration.close() + integration.close() - assertThat(integration.state).isEqualTo(AnrProfilingIntegration.MainThreadState.IDLE) - assertThat(integration.profileManager.load().stacks).isEmpty() + verify(recorder, times(1)).unsubscribe(any()) } @Test - fun `does not register when options is not SentryAndroidOptions`() { - val plainOptions = - SentryOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - } - + fun `close does not unsubscribe when not subscribed`() { + options.anrProfilingSampleRate = Double.MIN_VALUE val integration = AnrProfilingIntegration() + integration.register(scopes, options) - try { - integration.register(mockScopes, plainOptions) - } catch (e: IllegalArgumentException) { - // ignored - } - - // Verify no listeners were added - val lifecycleObserver = AppState.getInstance().lifecycleObserver - if (lifecycleObserver != null) { - assertTrue(lifecycleObserver.listeners.isEmpty()) - } - } - - @Test - fun `does not register when ANR profiling is disabled`() { - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = null - } + integration.close() - val integration = AnrProfilingIntegration() - integration.register(mockScopes, androidOptions) - - // When ANR profiling is disabled, the integration doesn't add itself to AppState - // So the lifecycle observer may be null or have no listeners - val lifecycleObserver = AppState.getInstance().lifecycleObserver - if (lifecycleObserver != null) { - assertTrue(lifecycleObserver.listeners.isEmpty()) - } + verify(recorder, never()).unsubscribe(any()) } @Test - fun `does not collect stacks when sample rate is zero`() { - val mainThread = Thread.currentThread() - - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 0.0 - } - - val integration = AnrProfilingIntegration() - integration.register(mockScopes, withTestTicker(androidOptions)) - integration.onForeground() + fun `two integrations on one recorder use distinct subscriptions`() { + val first = AnrProfilingIntegration() + val second = AnrProfilingIntegration() + first.register(scopes, options) + second.register(scopes, options) - // Transition to suspicious - ticker.advance(2_900, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.SUSPICIOUS, integration.state) - - // Transition to ANR - ticker.advance(3_000, MILLISECONDS) - integration.checkMainThread(mainThread) - assertEquals(AnrProfilingIntegration.MainThreadState.ANR_DETECTED, integration.state) - - // No stacks should have been collected - assertEquals(0, integration.numCollectedStacks.get()) + val subscribed = argumentCaptor() + verify(recorder, times(2)).subscribe(subscribed.capture()) + assertThat(subscribed.firstValue).isNotSameInstanceAs(subscribed.secondValue) } @Test - fun `registers when ANR profiling is enabled`() { - val androidOptions = - SentryAndroidOptions().apply { - cacheDirPath = tmpDir.root.absolutePath - setLogger(mockLogger) - anrProfilingSampleRate = 1.0 - } - + @Suppress("DEPRECATION") + fun `deprecated lifecycle and run methods do nothing`() { val integration = AnrProfilingIntegration() - integration.register(mockScopes, androidOptions) + integration.register(scopes, options) + verify(recorder).subscribe(any()) - assertFalse(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) - assertTrue(SentryIntegrationPackageStorage.getInstance().integrations.contains("AnrProfiling")) + integration.onForeground() + integration.onBackground() + integration.run() - integration.close() + verifyNoMoreInteractions(recorder) } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HandlerThreadPosterTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HandlerThreadPosterTest.kt new file mode 100644 index 0000000000..52b5db2ea5 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HandlerThreadPosterTest.kt @@ -0,0 +1,39 @@ +package io.sentry.android.core.hang + +import android.os.Handler +import android.os.Looper +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import kotlin.test.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf + +@RunWith(AndroidJUnit4::class) +class HandlerThreadPosterTest { + + private val sut = HandlerThreadPoster(Handler(Looper.getMainLooper())) + + @Test + fun `post runs the runnable on the main looper`() { + var ranOn: Thread? = null + + sut.post { ranOn = Thread.currentThread() } + shadowOf(Looper.getMainLooper()).idle() + + assertThat(ranOn).isSameInstanceAs(Looper.getMainLooper().thread) + } + + @Test + fun `remove drops only the given pending runnable`() { + val ran = mutableListOf() + val removed = Runnable { ran.add("removed") } + val kept = Runnable { ran.add("kept") } + sut.post(removed) + sut.post(kept) + + sut.remove(removed) + shadowOf(Looper.getMainLooper()).idle() + + assertThat(ran).containsExactly("kept") + } +} diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 5caa7674c9..a6b474ef79 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -3792,6 +3792,7 @@ public class io/sentry/SentryOptions : io/sentry/transport/RateLimiterConfig { public fun addOptionsObserver (Lio/sentry/IOptionsObserver;)V public fun addPerformanceCollector (Lio/sentry/IPerformanceCollector;)V public fun addScopeObserver (Lio/sentry/IScopeObserver;)V + public fun close ()V public static fun empty ()Lio/sentry/SentryOptions; public fun findPersistingScopeObserver ()Lio/sentry/cache/PersistingScopeObserver; public fun getAppStartExtender ()Lio/sentry/IAppStartExtender; diff --git a/sentry/src/main/java/io/sentry/Scopes.java b/sentry/src/main/java/io/sentry/Scopes.java index 30df253869..a628cc465f 100644 --- a/sentry/src/main/java/io/sentry/Scopes.java +++ b/sentry/src/main/java/io/sentry/Scopes.java @@ -470,6 +470,7 @@ public void close(final boolean isRestarting) { getOptions().getContinuousProfiler().close(true); getOptions().getCompositePerformanceCollector().close(); getOptions().getConnectionStatusProvider().close(); + getOptions().close(); // On restart we intentionally leave the timer executor running so that pending idle/ // deadline timeouts of transactions started before the restart still fire and finish // those transactions. It self-terminates once idle (allowCoreThreadTimeOut). diff --git a/sentry/src/main/java/io/sentry/SentryOptions.java b/sentry/src/main/java/io/sentry/SentryOptions.java index 4a056c7609..35adcd7635 100644 --- a/sentry/src/main/java/io/sentry/SentryOptions.java +++ b/sentry/src/main/java/io/sentry/SentryOptions.java @@ -3212,6 +3212,13 @@ public void setBackpressureMonitor(final @NotNull IBackpressureMonitor backpress this.backpressureMonitor = backpressureMonitor; } + /** + * Called by {@link Scopes#close(boolean)} after the integrations, also on restart, so platform + * options can release what they own. + */ + @ApiStatus.Internal + public void close() {} + @ApiStatus.Experimental public void setEnableBackpressureHandling(final boolean enableBackpressureHandling) { this.enableBackpressureHandling = enableBackpressureHandling; diff --git a/sentry/src/test/java/io/sentry/ScopesTest.kt b/sentry/src/test/java/io/sentry/ScopesTest.kt index 253c054531..950740ece1 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -22,6 +22,7 @@ import io.sentry.test.createTestScopes import io.sentry.test.initForTest import io.sentry.util.HintUtils import io.sentry.util.StringUtils +import java.io.Closeable import java.io.File import java.nio.file.Files import java.util.Queue @@ -2046,6 +2047,49 @@ class ScopesTest { verify(performanceCollector).close() } + @Test + fun `Scopes closes the options after the integrations on close call`() { + val calls = mutableListOf() + val sut = createScopesRecordingClose(calls) + + sut.close() + + assertEquals(listOf("integration", "options"), calls) + } + + @Test + fun `Scopes closes the options after the integrations on restart`() { + val calls = mutableListOf() + val sut = createScopesRecordingClose(calls) + + sut.close(true) + + assertEquals(listOf("integration", "options"), calls) + } + + private fun createScopesRecordingClose(calls: MutableList): Scopes { + val integration = + object : Integration, Closeable { + override fun register(scopes: IScopes, options: SentryOptions) = Unit + + override fun close() { + calls.add("integration") + } + } + val options = + object : SentryOptions() { + override fun close() { + calls.add("options") + } + } + .apply { + dsn = "https://key@sentry.io/proj" + cacheDirPath = file.absolutePath + addIntegration(integration) + } + return createScopes(options) + } + @Test fun `Scopes with isRestarting true should close the sentry executor in the background`() { val executor = spy(DeferredExecutorService())