diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 5ab0634a49..fe6b644b33 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -237,6 +237,11 @@ public final class io/sentry/android/core/AppState$LifecycleObserver : androidx/ public fun onStop (Landroidx/lifecycle/LifecycleOwner;)V } +public abstract interface class io/sentry/android/core/AppStateProvider { + public abstract fun addAppStateListener (Lio/sentry/android/core/AppState$AppStateListener;)V + public abstract fun removeAppStateListener (Lio/sentry/android/core/AppState$AppStateListener;)V +} + public final class io/sentry/android/core/ApplicationExitInfoEventProcessor : io/sentry/BackfillingEventProcessor, io/sentry/internal/eventprocessor/SentryEventProcessor { public fun (Landroid/content/Context;Lio/sentry/android/core/SentryAndroidOptions;Lio/sentry/android/core/BuildInfoProvider;)V public fun getOrder ()Ljava/lang/Long; @@ -805,6 +810,91 @@ public final class io/sentry/android/core/cache/AndroidEnvelopeCache : io/sentry public fun storeEnvelope (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)Z } +public abstract interface class io/sentry/android/core/hang/HangDataCollector : java/io/Closeable { + public abstract fun close ()V + public abstract fun onRecordingCanceled ()V + public abstract fun onRecordingStarted (Lio/sentry/android/core/hang/HangInterval;)V + public abstract fun onRecordingStopped (Lio/sentry/android/core/hang/HangInterval;Lio/sentry/android/core/hang/HangRecord$Builder;)V + public abstract fun onSample (Lio/sentry/android/core/hang/HangInterval;)V +} + +public final class io/sentry/android/core/hang/HangInterval { + public fun (J)V + public fun getStartTimeMs ()J +} + +public final class io/sentry/android/core/hang/HangRecord { + public fun getDurationMs ()J + public fun getSamples ()Ljava/util/List; + public fun getStartTimestampMs ()J + public fun hasEndedAtMaxRecordingTime ()Z +} + +public final class io/sentry/android/core/hang/HangRecord$Builder { + public fun (JJ)V + public fun build ()Lio/sentry/android/core/hang/HangRecord; + public fun setEndedAtMaxRecordingTime (Z)Lio/sentry/android/core/hang/HangRecord$Builder; + public fun setSamples (Ljava/util/List;)Lio/sentry/android/core/hang/HangRecord$Builder; +} + +public final class io/sentry/android/core/hang/HangRecorder : io/sentry/android/core/AppState$AppStateListener, io/sentry/android/core/hang/Metronome, java/io/Closeable { + public static final field DEFAULT_EXECUTOR_FACTORY Lio/sentry/android/core/hang/HangRecorder$ExecutorFactory; + public static final field DEFAULT_MAX_RECORDING_TIME_MS J + public static final field DEFAULT_POLLING_INTERVAL_MS J + public fun (Lio/sentry/SentryOptions;Lio/sentry/android/core/AppStateProvider;Lio/sentry/time/MonotonicTicker;Lio/sentry/time/EpochClock;JJLio/sentry/android/core/hang/HangRecorder$ExecutorFactory;Lio/sentry/android/core/hang/HangRecorder$SignalFactory;Ljava/util/List;)V + public fun addTickListener (Lio/sentry/android/core/hang/Metronome$TickListener;)V + public fun close ()V + public fun onBackground ()V + public fun onForeground ()V + public fun removeTickListener (Lio/sentry/android/core/hang/Metronome$TickListener;)V + public fun subscribe (Lio/sentry/android/core/hang/HangRecorderListener;)V + public fun unsubscribe (Lio/sentry/android/core/hang/HangRecorderListener;)V +} + +public abstract interface class io/sentry/android/core/hang/HangRecorder$ExecutorFactory { + public abstract fun create ()Ljava/util/concurrent/ScheduledExecutorService; +} + +public abstract interface class io/sentry/android/core/hang/HangRecorder$SignalFactory { + public abstract fun create (Lio/sentry/android/core/hang/Metronome;)Ljava/util/List; +} + +public abstract interface class io/sentry/android/core/hang/HangRecorderListener { + public abstract fun onHangRecorded (Lio/sentry/android/core/hang/HangRecord;)V +} + +public abstract interface class io/sentry/android/core/hang/HangSignal : java/io/Closeable { + public abstract fun close ()V + public abstract fun start (Lio/sentry/android/core/hang/HangSignalListener;)V + public abstract fun stop ()V +} + +public final class io/sentry/android/core/hang/HangSignal$State : java/lang/Enum { + public static final field IDLE Lio/sentry/android/core/hang/HangSignal$State; + public static final field SUSPICIOUS Lio/sentry/android/core/hang/HangSignal$State; + public static fun valueOf (Ljava/lang/String;)Lio/sentry/android/core/hang/HangSignal$State; + public static fun values ()[Lio/sentry/android/core/hang/HangSignal$State; +} + +public abstract interface class io/sentry/android/core/hang/HangSignalListener { + public abstract fun onSignalCanceled (Lio/sentry/android/core/hang/HangSignal;)V + public abstract fun onSignalChanged (Lio/sentry/android/core/hang/HangSignal;Lio/sentry/android/core/hang/HangSignal$State;J)V +} + +public abstract interface class io/sentry/android/core/hang/Metronome { + public abstract fun addTickListener (Lio/sentry/android/core/hang/Metronome$TickListener;)V + public abstract fun removeTickListener (Lio/sentry/android/core/hang/Metronome$TickListener;)V +} + +public abstract interface class io/sentry/android/core/hang/Metronome$TickListener { + public abstract fun onMetronomeTick (J)V +} + +public abstract interface class io/sentry/android/core/hang/ThreadPoster { + public abstract fun post (Ljava/lang/Runnable;)V + public abstract fun remove (Ljava/lang/Runnable;)V +} + public abstract class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter : android/app/Application$ActivityLifecycleCallbacks { public fun ()V public fun onActivityCreated (Landroid/app/Activity;Landroid/os/Bundle;)V diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppStateProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppStateProvider.java new file mode 100644 index 0000000000..29cb638d5a --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppStateProvider.java @@ -0,0 +1,17 @@ +package io.sentry.android.core; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * Tells listeners whether the app is in the foreground. Implementations may call the listeners on + * any thread. + */ +@ApiStatus.Internal +public interface AppStateProvider { + + /** Calls the new listener right away with the current app state, if it is known. */ + void addAppStateListener(@NotNull AppState.AppStateListener listener); + + void removeAppStateListener(@NotNull AppState.AppStateListener listener); +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangDataCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangDataCollector.java new file mode 100644 index 0000000000..3bf915e444 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangDataCollector.java @@ -0,0 +1,30 @@ +package io.sentry.android.core.hang; + +import java.io.Closeable; +import java.io.IOException; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** Collects data while a hang interval is open. */ +@ApiStatus.Internal +public interface HangDataCollector extends Closeable { + + /** Called when an interval opens. */ + void onRecordingStarted(@NotNull HangInterval interval); + + /** Called on each tick while an interval is open. */ + void onSample(@NotNull HangInterval interval); + + /** Called when the interval ends with a record. */ + void onRecordingStopped(@NotNull HangInterval interval, @NotNull HangRecord.Builder out); + + /** + * Called when the interval ends without a record, because a signal canceled it or the last + * subscription was removed. + */ + void onRecordingCanceled(); + + /** Called once, when the recorder is closed. The collector is not used after this. */ + @Override + void close() throws IOException; +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangInterval.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangInterval.java new file mode 100644 index 0000000000..a9805c17d7 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangInterval.java @@ -0,0 +1,21 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; + +@ApiStatus.Internal +public final class HangInterval { + + private final long startTimeMs; + + public HangInterval(final long startTimeMs) { + this.startTimeMs = startTimeMs; + } + + /** + * The start of the hang, in the time base of {@link + * Metronome.TickListener#onMetronomeTick(long)}. + */ + public long getStartTimeMs() { + return startTimeMs; + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecord.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecord.java new file mode 100644 index 0000000000..abed2ee8a4 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecord.java @@ -0,0 +1,71 @@ +package io.sentry.android.core.hang; + +import io.sentry.android.core.anr.AnrStackTrace; +import java.util.Collections; +import java.util.List; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** The collected data of one hang interval that ended with a record. */ +@ApiStatus.Internal +public final class HangRecord { + + private final long durationMs; + private final long startTimestampMs; + private final @NotNull List samples; + private final boolean endedAtMaxRecordingTime; + + private HangRecord(final @NotNull Builder builder) { + this.durationMs = builder.durationMs; + this.startTimestampMs = builder.startTimestampMs; + this.samples = builder.samples; + this.endedAtMaxRecordingTime = builder.endedAtMaxRecordingTime; + } + + public long getDurationMs() { + return durationMs; + } + + /** The start of the interval, as Unix time in milliseconds. */ + public long getStartTimestampMs() { + return startTimestampMs; + } + + public @NotNull List getSamples() { + return samples; + } + + /** + * Whether the interval was cut at the maximum recording time. The watched thread is then still + * blocked when the record is given to the listeners. + */ + public boolean hasEndedAtMaxRecordingTime() { + return endedAtMaxRecordingTime; + } + + public static final class Builder { + private final long durationMs; + private final long startTimestampMs; + private @NotNull List samples = Collections.emptyList(); + private boolean endedAtMaxRecordingTime; + + public Builder(final long durationMs, final long startTimestampMs) { + this.durationMs = durationMs; + this.startTimestampMs = startTimestampMs; + } + + public @NotNull Builder setSamples(final @NotNull List samples) { + this.samples = samples; + return this; + } + + public @NotNull Builder setEndedAtMaxRecordingTime(final boolean endedAtMaxRecordingTime) { + this.endedAtMaxRecordingTime = endedAtMaxRecordingTime; + return this; + } + + public @NotNull HangRecord build() { + return new HangRecord(this); + } + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecorder.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecorder.java new file mode 100644 index 0000000000..b8f96cbff2 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecorder.java @@ -0,0 +1,414 @@ +package io.sentry.android.core.hang; + +import io.sentry.ISentryLifecycleToken; +import io.sentry.SentryLevel; +import io.sentry.SentryOptions; +import io.sentry.android.core.AppState; +import io.sentry.android.core.AppStateProvider; +import io.sentry.time.EpochClock; +import io.sentry.time.MonotonicTicker; +import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.ExceptionUtils; +import java.io.Closeable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Opens a {@link HangInterval} when a {@link HangSignal} reports {@link + * HangSignal.State#SUSPICIOUS}, lets the {@link HangDataCollector}s sample on each tick, and gives + * a {@link HangRecord} to the subscribers when the interval ends. + * + *

Runs on its own thread, {@code SentryHangRecorder}, which starts at the first subscription and + * stops at {@link #close()}. All calls from other threads are moved to that thread, so the + * recording state needs no lock. The recorder calls its signals, its collectors and the tick + * listeners only on that thread. + * + *

Needs a monotonic ticker that does not advance during device sleep, so a device suspend does + * not read as a hang. + */ +@ApiStatus.Internal +public final class HangRecorder implements Metronome, Closeable, AppState.AppStateListener { + + public static final long DEFAULT_POLLING_INTERVAL_MS = 66; + public static final long DEFAULT_MAX_RECORDING_TIME_MS = 8_000; + + /** + * Creates the executor of the recorder thread. It must run one task at a time on one thread, in + * the order they were queued. + */ + public interface ExecutorFactory { + @NotNull + ScheduledExecutorService create(); + } + + /** Creates the signals of a recorder, with the recorder as their metronome. */ + public interface SignalFactory { + @NotNull + List create(@NotNull Metronome metronome); + } + + public static final @NotNull ExecutorFactory DEFAULT_EXECUTOR_FACTORY = + () -> + Executors.newSingleThreadScheduledExecutor(runnable -> { + final @NotNull Thread thread = new Thread(runnable, "SentryHangRecorder"); + thread.setDaemon(true); + return thread; + }); + + private final @NotNull SentryOptions options; + private final @NotNull AppStateProvider appStateProvider; + private final @NotNull MonotonicTicker ticker; + private final @NotNull EpochClock epochClock; + private final long pollingIntervalMs; + private final long maxRecordingTimeMs; + private final @NotNull ExecutorFactory executorFactory; + private final @NotNull List signals; + private final @NotNull List collectors; + private final @NotNull List tickListeners = new CopyOnWriteArrayList<>(); + + private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); + + private volatile @Nullable ScheduledExecutorService executor; + private volatile @Nullable Thread executorThread; + + private boolean closed; + + private final @NotNull Set subscriptions = new LinkedHashSet<>(); + private boolean signalsStarted; + private @Nullable Future tickFuture; + private @Nullable HangInterval openInterval; + private long openIntervalStartTimestampMs; + private boolean waitingForIdleAfterMaxRecordingTime; + + private final @NotNull HangSignalListener signalListener = + new HangSignalListener() { + @Override + public void onSignalChanged( + final @NotNull HangSignal signal, + final @NotNull HangSignal.State state, + final long durationMs) { + final long sinceMs = nowMs() - durationMs; + postOnRecorderThread(() -> handleSignalChanged(state, sinceMs)); + } + + @Override + public void onSignalCanceled(final @NotNull HangSignal signal) { + postOnRecorderThread(HangRecorder.this::handleSignalCanceled); + } + }; + + /** + * Creates a recorder that starts no thread before the first {@link + * #subscribe(HangRecorderListener)}. + */ + public HangRecorder( + final @NotNull SentryOptions options, + final @NotNull AppStateProvider appStateProvider, + final @NotNull MonotonicTicker ticker, + final @NotNull EpochClock epochClock, + final long pollingIntervalMs, + final long maxRecordingTimeMs, + final @NotNull ExecutorFactory executorFactory, + final @NotNull SignalFactory signalFactory, + final @NotNull List collectors) { + this.options = options; + this.appStateProvider = appStateProvider; + this.ticker = ticker; + this.epochClock = epochClock; + this.pollingIntervalMs = pollingIntervalMs; + this.maxRecordingTimeMs = maxRecordingTimeMs; + this.executorFactory = executorFactory; + this.signals = Collections.unmodifiableList(new ArrayList<>(signalFactory.create(this))); + this.collectors = Collections.unmodifiableList(new ArrayList<>(collectors)); + } + + /** + * Starts the recorder thread at the first call, and the signals when the app is in the + * foreground. The recorder calls the listener on the SDK executor, see {@link + * SentryOptions#getExecutorService()}. Does nothing after {@link #close()}. + */ + public void subscribe(final @NotNull HangRecorderListener listener) { + postOnRecorderThread( + () -> { + if (subscriptions.add(listener) && subscriptions.size() == 1) { + appStateProvider.addAppStateListener(this); + } + }, + true); + } + + /** + * At the last subscription, stops the signals and the tick, and drops an open interval without a + * record. The recorder thread stays for the next {@link #subscribe(HangRecorderListener)}. + */ + public void unsubscribe(final @NotNull HangRecorderListener listener) { + postOnRecorderThread( + () -> { + if (subscriptions.remove(listener) && subscriptions.isEmpty()) { + appStateProvider.removeAppStateListener(this); + stopSignals(false); + } + }, + false); + } + + /** + * The recorder calls the listener on the recorder thread, on each tick before the collectors + * sample. + */ + @Override + public void addTickListener(final @NotNull TickListener listener) { + tickListeners.add(listener); + } + + @Override + public void removeTickListener(final @NotNull TickListener listener) { + tickListeners.remove(listener); + } + + /** + * Drops an open interval without a record, closes the signals and the collectors, and stops the + * recorder thread. Later calls do nothing. + */ + @Override + public void close() { + final @Nullable ScheduledExecutorService current; + try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { + if (closed) { + return; + } + closed = true; + current = executor; + if (current != null) { + current.execute(() -> closeOnRecorderThread(current)); + } + } + if (current == null) { + // No recorder thread was started, so close here. + closeSignalsAndCollectors(); + } + } + + @Override + public void onForeground() { + postOnRecorderThread(this::startSignals, false); + } + + @Override + public void onBackground() { + postOnRecorderThread(() -> stopSignals(true), false); + } + + private void postOnRecorderThread( + final @NotNull Runnable task, final boolean startRecorderThread) { + try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { + if (closed) { + return; + } + @Nullable ScheduledExecutorService current = executor; + if (current == null) { + if (!startRecorderThread) { + return; + } + current = executorFactory.create(); + executor = current; + // Runs before any other task of this single-thread executor. + current.execute(() -> executorThread = Thread.currentThread()); + } + current.execute(task); + } + } + + @SuppressWarnings("ReferenceEquality") + private void postOnRecorderThread(final @NotNull Runnable task) { + if (Thread.currentThread() == executorThread) { + task.run(); + } else { + postOnRecorderThread(task, false); + } + } + + private void closeOnRecorderThread(final @NotNull ScheduledExecutorService self) { + try { + try { + if (!subscriptions.isEmpty()) { + appStateProvider.removeAppStateListener(this); + stopSignals(false); + } + } finally { + subscriptions.clear(); + closeSignalsAndCollectors(); + } + } finally { + self.shutdown(); + } + } + + private void closeSignalsAndCollectors() { + try { + for (final @NotNull HangSignal signal : signals) { + signal.close(); + } + } finally { + for (final @NotNull HangDataCollector collector : collectors) { + try { + collector.close(); + } catch (IOException e) { + options.getLogger().log(SentryLevel.WARNING, "Failed to close a hang data collector", e); + } + } + } + } + + private void startSignals() { + final @Nullable ScheduledExecutorService self = executor; + if (self == null || subscriptions.isEmpty() || signalsStarted) { + return; + } + signalsStarted = true; + for (final @NotNull HangSignal signal : signals) { + signal.start(signalListener); + } + tickFuture = + self.scheduleWithFixedDelay(this::tick, 0, pollingIntervalMs, TimeUnit.MILLISECONDS); + } + + private void stopSignals(final boolean endIntervalWithRecord) { + if (!signalsStarted) { + return; + } + signalsStarted = false; + waitingForIdleAfterMaxRecordingTime = false; + final @Nullable Future future = tickFuture; + if (future != null) { + future.cancel(false); + tickFuture = null; + } + try { + for (final @NotNull HangSignal signal : signals) { + signal.stop(); + } + } finally { + if (endIntervalWithRecord) { + endInterval(nowMs(), false); + } else { + cancelInterval(); + } + } + } + + private void tick() { + try { + final long nowMs = nowMs(); + for (final @NotNull TickListener listener : tickListeners) { + listener.onMetronomeTick(nowMs); + } + final @Nullable HangInterval interval = openInterval; + if (interval == null) { + return; + } + try { + for (final @NotNull HangDataCollector collector : collectors) { + collector.onSample(interval); + } + } finally { + // A collector that throws on every tick must not keep the interval open past the maximum. + if (nowMs - interval.getStartTimeMs() >= maxRecordingTimeMs) { + endInterval(interval.getStartTimeMs() + maxRecordingTimeMs, true); + waitingForIdleAfterMaxRecordingTime = true; + } + } + } catch (Throwable t) { + // scheduleWithFixedDelay stops all later ticks after an exception. + ExceptionUtils.rethrowIfFatal(t); + options.getLogger().log(SentryLevel.ERROR, "HangRecorder tick failed", t); + } + } + + private void handleSignalChanged(final @NotNull HangSignal.State state, final long sinceMs) { + if (!signalsStarted) { + return; + } + if (state == HangSignal.State.SUSPICIOUS) { + if (openInterval != null || waitingForIdleAfterMaxRecordingTime) { + return; + } + final long nowTimestampMs = TimeUnit.NANOSECONDS.toMillis(epochClock.now().epochNanos()); + final @NotNull HangInterval interval = new HangInterval(sinceMs); + openInterval = interval; + openIntervalStartTimestampMs = nowTimestampMs - (nowMs() - sinceMs); + for (final @NotNull HangDataCollector collector : collectors) { + collector.onRecordingStarted(interval); + } + } else { + waitingForIdleAfterMaxRecordingTime = false; + endInterval(sinceMs, false); + } + } + + private void handleSignalCanceled() { + waitingForIdleAfterMaxRecordingTime = false; + cancelInterval(); + } + + private void cancelInterval() { + if (openInterval == null) { + return; + } + openInterval = null; + for (final @NotNull HangDataCollector collector : collectors) { + collector.onRecordingCanceled(); + } + } + + private void endInterval(final long endTimeMs, final boolean endedAtMaxRecordingTime) { + final @Nullable HangInterval interval = openInterval; + if (interval == null) { + return; + } + openInterval = null; + final @NotNull HangRecord.Builder builder = + new HangRecord.Builder(endTimeMs - interval.getStartTimeMs(), openIntervalStartTimestampMs) + .setEndedAtMaxRecordingTime(endedAtMaxRecordingTime); + for (final @NotNull HangDataCollector collector : collectors) { + collector.onRecordingStopped(interval, builder); + } + final @NotNull HangRecord record = builder.build(); + final @NotNull List listeners = new ArrayList<>(subscriptions); + try { + final @NotNull Future delivery = + options + .getExecutorService() + .submit(() -> { + for (final @NotNull HangRecorderListener listener : listeners) { + listener.onHangRecorded(record); + } + }); + // The SDK executor returns a canceled future instead of throwing when its queue is full. + if (delivery.isCancelled()) { + options + .getLogger() + .log(SentryLevel.WARNING, "Dropped a hang record, the SDK executor queue is full"); + } + } catch (RejectedExecutionException e) { + options.getLogger().log(SentryLevel.WARNING, "Dropped a hang record, executor is closed", e); + } + } + + private long nowMs() { + return TimeUnit.NANOSECONDS.toMillis(ticker.tickNanos()); + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecorderListener.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecorderListener.java new file mode 100644 index 0000000000..120191dd0e --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecorderListener.java @@ -0,0 +1,10 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +@ApiStatus.Internal +public interface HangRecorderListener { + + void onHangRecorded(@NotNull HangRecord record); +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSignal.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSignal.java new file mode 100644 index 0000000000..a59bd6556b --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSignal.java @@ -0,0 +1,33 @@ +package io.sentry.android.core.hang; + +import java.io.Closeable; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * A source that reports whether a watched thread is {@link State#SUSPICIOUS} or {@link State#IDLE}. + */ +@ApiStatus.Internal +public interface HangSignal extends Closeable { + + /** + * Starts reporting to the listener, until {@link #stop()}. The signal may call the listener on + * any thread. + */ + void start(@NotNull HangSignalListener listener); + + /** + * Stops reporting. After this, the signal must not call its listener until the next {@link + * #start(HangSignalListener)}. + */ + void stop(); + + /** Called once, when the signal is no longer needed. The signal is not used after this. */ + @Override + void close(); + + enum State { + IDLE, + SUSPICIOUS + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSignalListener.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSignalListener.java new file mode 100644 index 0000000000..70699e6da6 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSignalListener.java @@ -0,0 +1,24 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** Receives the state changes of a {@link HangSignal}. */ +@ApiStatus.Internal +public interface HangSignalListener { + + /** + * The signal changed its state. + * + * @param durationMs how long before this call the watched thread entered the new state; a signal + * can detect a change late + */ + void onSignalChanged( + @NotNull HangSignal signal, @NotNull HangSignal.State state, long durationMs); + + /** + * The current {@link HangSignal.State#SUSPICIOUS} state is not valid anymore and ended without a + * recovery. + */ + void onSignalCanceled(@NotNull HangSignal signal); +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/Metronome.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/Metronome.java new file mode 100644 index 0000000000..ae7aa1c176 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/Metronome.java @@ -0,0 +1,22 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** Calls its listeners at a regular interval with the current time. */ +@ApiStatus.Internal +public interface Metronome { + + void addTickListener(@NotNull TickListener listener); + + void removeTickListener(@NotNull TickListener listener); + + interface TickListener { + /** + * Must be fast, it delays the metronome and the other listeners. + * + * @param nowMs a monotonic time in milliseconds, with an arbitrary origin + */ + void onMetronomeTick(long nowMs); + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadPoster.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadPoster.java new file mode 100644 index 0000000000..898ad76f70 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/ThreadPoster.java @@ -0,0 +1,12 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +@ApiStatus.Internal +public interface ThreadPoster { + + void post(@NotNull Runnable runnable); + + void remove(@NotNull Runnable runnable); +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/FakeScheduledExecutorService.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/FakeScheduledExecutorService.kt new file mode 100644 index 0000000000..b3ad510d82 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/FakeScheduledExecutorService.kt @@ -0,0 +1,126 @@ +package io.sentry.android.core.hang + +import java.util.concurrent.AbstractExecutorService +import java.util.concurrent.Callable +import java.util.concurrent.Delayed +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.ScheduledExecutorService +import java.util.concurrent.ScheduledFuture +import java.util.concurrent.TimeUnit + +/** + * A [ScheduledExecutorService] that runs tasks only when the test calls [runPending] or [runTick], + * on the test thread. + * + * It keeps the parts of the real contract that the recorder relies on: [execute] throws + * [RejectedExecutionException] after [shutdown], tasks submitted before [shutdown] still run, a + * task that throws does not stop the executor (the exception goes to [taskFailures], where the real + * executor keeps it in the task's future), and a periodic task that throws is cancelled silently. + */ +class FakeScheduledExecutorService : ScheduledExecutorService, AbstractExecutorService() { + private val pending = ArrayDeque() + private val periodicTasks = mutableListOf() + private var shutdown = false + val taskFailures = mutableListOf() + + val activePeriodicTasks: List + get() = periodicTasks.filter { !it.isCancelled } + + fun runPending() { + while (pending.isNotEmpty()) { + try { + pending.removeFirst().run() + } catch (t: Throwable) { + taskFailures.add(t) + } + } + } + + /** + * Runs one round of each active periodic task, then the pending tasks. A tick goes first because + * on a real executor a tick can be due before a task that was just queued. + */ + fun runTick() { + for (task in activePeriodicTasks) { + try { + task.command.run() + } catch (_: Throwable) { + task.cancel(false) + } + } + runPending() + } + + override fun execute(command: Runnable) { + if (shutdown) { + throw RejectedExecutionException("shut down") + } + pending.addLast(command) + } + + override fun scheduleWithFixedDelay( + command: Runnable, + initialDelay: Long, + delay: Long, + unit: TimeUnit, + ): ScheduledFuture<*> { + if (shutdown) { + throw RejectedExecutionException("shut down") + } + return PeriodicTask(command, unit.toMillis(delay)).also { periodicTasks.add(it) } + } + + override fun scheduleAtFixedRate( + command: Runnable, + initialDelay: Long, + period: Long, + unit: TimeUnit, + ): ScheduledFuture<*> = throw UnsupportedOperationException() + + override fun schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledFuture<*> = + throw UnsupportedOperationException() + + override fun schedule( + callable: Callable, + delay: Long, + unit: TimeUnit, + ): ScheduledFuture = throw UnsupportedOperationException() + + override fun shutdown() { + shutdown = true + periodicTasks.forEach { it.cancel(false) } + } + + override fun shutdownNow(): List { + shutdown() + return pending.toList().also { pending.clear() } + } + + override fun isShutdown(): Boolean = shutdown + + override fun isTerminated(): Boolean = shutdown && pending.isEmpty() + + override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = isTerminated + + class PeriodicTask(val command: Runnable, val delayMs: Long) : ScheduledFuture { + private var cancelled = false + + override fun cancel(mayInterruptIfRunning: Boolean): Boolean { + cancelled = true + return true + } + + override fun isCancelled(): Boolean = cancelled + + override fun isDone(): Boolean = cancelled + + override fun get() = throw UnsupportedOperationException() + + override fun get(timeout: Long, unit: TimeUnit) = throw UnsupportedOperationException() + + override fun getDelay(unit: TimeUnit): Long = unit.convert(delayMs, TimeUnit.MILLISECONDS) + + override fun compareTo(other: Delayed): Int = + getDelay(TimeUnit.MILLISECONDS).compareTo(other.getDelay(TimeUnit.MILLISECONDS)) + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt new file mode 100644 index 0000000000..23ddbab5ad --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt @@ -0,0 +1,783 @@ +package io.sentry.android.core.hang + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel +import io.sentry.SentryOptions +import io.sentry.android.core.AppState +import io.sentry.android.core.AppStateProvider +import io.sentry.android.core.anr.AnrStackTrace +import io.sentry.android.core.hang.HangRecorder.DEFAULT_MAX_RECORDING_TIME_MS +import io.sentry.android.core.hang.HangRecorder.DEFAULT_POLLING_INTERVAL_MS +import io.sentry.test.DeferredExecutorService +import io.sentry.test.NonOverridableNoOpSentryExecutorService +import io.sentry.time.EpochClock +import io.sentry.time.TestMonotonicTicker +import io.sentry.time.Timestamp +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeUnit.HOURS +import java.util.concurrent.TimeUnit.MILLISECONDS +import kotlin.test.BeforeTest +import kotlin.test.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify + +class HangRecorderTest { + + private lateinit var ticker: TestMonotonicTicker + private var unixTimeMs = 1_700_000_000_000L + private lateinit var logger: ILogger + private lateinit var sdkExecutor: DeferredExecutorService + private lateinit var options: SentryOptions + private val epochClock = EpochClock { Timestamp.ofEpochNanos(MILLISECONDS.toNanos(unixTimeMs)) } + private lateinit var appStateProvider: FakeAppStateProvider + private val executors = mutableListOf() + private lateinit var recorder: HangRecorder + private lateinit var signal: FakeSignal + private val signals = mutableListOf() + private lateinit var collector: FakeCollector + private val records = mutableListOf() + private val listener = HangRecorderListener { records.add(it) } + + private val executor: FakeScheduledExecutorService + get() = executors.last() + + @BeforeTest + fun setUp() { + // A tick's origin is arbitrary, so start far from zero. + ticker = TestMonotonicTicker(HOURS.toNanos(30)) + logger = mock() + sdkExecutor = DeferredExecutorService() + options = SentryOptions() + options.setLogger(logger) + options.isDebug = true + options.executorService = sdkExecutor + appStateProvider = FakeAppStateProvider() + collector = FakeCollector() + createRecorder() + } + + private fun createRecorder(signalCount: Int = 1) { + recorder = + HangRecorder( + options, + appStateProvider, + ticker, + epochClock, + DEFAULT_POLLING_INTERVAL_MS, + DEFAULT_MAX_RECORDING_TIME_MS, + { FakeScheduledExecutorService().also { executors.add(it) } }, + { metronome -> + signals.clear() + repeat(signalCount) { signals.add(FakeSignal(metronome)) } + signals + }, + listOf(collector), + ) + signal = signals.first() + } + + private fun nowMs(): Long = TimeUnit.NANOSECONDS.toMillis(ticker.tickNanos()) + + private fun advance(ms: Long) { + ticker.advance(ms, MILLISECONDS) + unixTimeMs += ms + } + + private fun startInForeground() { + recorder.subscribe(listener) + executor.runPending() + appStateProvider.foreground() + executor.runPending() + } + + private fun openIntervalInTick(durationMs: Long) { + signal.onNextTick { signal.report(HangSignal.State.SUSPICIOUS, durationMs) } + executor.runTick() + } + + private fun tickUntilRecorded() { + var ticks = 0 + while ( + records.isEmpty() && ticks < DEFAULT_MAX_RECORDING_TIME_MS / DEFAULT_POLLING_INTERVAL_MS + 2 + ) { + advance(DEFAULT_POLLING_INTERVAL_MS) + executor.runTick() + sdkExecutor.runAll() + ticks++ + } + assertThat(records).isNotEmpty() + } + + @Test + fun `suspicious opens interval and starts collectors`() { + startInForeground() + val sinceMs = nowMs() - 300 + + openIntervalInTick(300) + + assertThat(collector.calls).containsExactly("start $sinceMs", "sample $sinceMs").inOrder() + } + + @Test + fun `ticks with a fixed delay of the tick interval`() { + startInForeground() + + assertThat(executor.activePeriodicTasks.map { it.delayMs }) + .containsExactly(DEFAULT_POLLING_INTERVAL_MS) + } + + @Test + fun `tick listeners run before collectors sample`() { + val calls = collector.calls + recorder.addTickListener { calls.add("tick") } + startInForeground() + + val sinceMs = nowMs() - 300 + openIntervalInTick(300) + executor.runTick() + + assertThat(calls) + .containsExactly("tick", "start $sinceMs", "sample $sinceMs", "tick", "sample $sinceMs") + .inOrder() + } + + @Test + fun `idle closes interval and notifies listeners on sdk executor`() { + startInForeground() + val suspiciousSinceMs = nowMs() - 300 + val timestampAtOpenMs = unixTimeMs + openIntervalInTick(300) + val samples = listOf(AnrStackTrace(unixTimeMs, arrayOf())) + collector.onRecordingStoppedAction = { it.setSamples(samples) } + advance(1_000) + val idleSinceMs = nowMs() - 20 + + signal.report(HangSignal.State.IDLE, 20) + + assertThat(collector.calls.last()).isEqualTo("stop $suspiciousSinceMs") + assertThat(records).isEmpty() + sdkExecutor.runAll() + val record = records.single() + assertThat(record.durationMs).isEqualTo(idleSinceMs - suspiciousSinceMs) + assertThat(record.startTimestampMs).isEqualTo(timestampAtOpenMs - 300) + assertThat(record.samples).isSameInstanceAs(samples) + } + + @Test + fun `no sample after idle`() { + startInForeground() + openIntervalInTick(300) + signal.report(HangSignal.State.IDLE, 0) + collector.calls.clear() + + executor.runTick() + + assertThat(collector.calls).isEmpty() + } + + @Test + fun `idle without open interval is ignored`() { + startInForeground() + + signal.report(HangSignal.State.IDLE, 0) + executor.runTick() + sdkExecutor.runAll() + + assertThat(collector.calls).isEmpty() + assertThat(records).isEmpty() + } + + @Test + fun `second suspicious from another signal does not reopen interval`() { + createRecorder(signalCount = 2) + val otherSignal = signals[1] + startInForeground() + openIntervalInTick(300) + advance(100) + + otherSignal.report(HangSignal.State.SUSPICIOUS, 0) + advance(100) + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(collector.calls.count { it.startsWith("start") }).isEqualTo(1) + assertThat(records.single().durationMs).isEqualTo(500) + } + + @Test + fun `signal factory gets the recorder as metronome`() { + var metronome: Metronome? = null + val created = + HangRecorder( + options, + appStateProvider, + ticker, + epochClock, + DEFAULT_POLLING_INTERVAL_MS, + DEFAULT_MAX_RECORDING_TIME_MS, + { FakeScheduledExecutorService() }, + { + metronome = it + emptyList() + }, + emptyList(), + ) + + assertThat(metronome).isSameInstanceAs(created) + } + + @Test + fun `default executor factory runs the recorder on a daemon thread`() { + val executor = HangRecorder.DEFAULT_EXECUTOR_FACTORY.create() + try { + val thread = executor.submit { Thread.currentThread() }.get(10, TimeUnit.SECONDS) + + assertThat(thread.name).isEqualTo("SentryHangRecorder") + assertThat(thread.isDaemon).isTrue() + } finally { + executor.shutdown() + } + } + + @Test + fun `maxRecordingTime ends interval with durationMs 8000 and later idle is ignored`() { + startInForeground() + openIntervalInTick(0) + tickUntilRecorded() + val samplesAtEnd = collector.calls.count { it.startsWith("sample") } + + executor.runTick() + signal.report(HangSignal.State.IDLE, 0) + executor.runTick() + sdkExecutor.runAll() + + assertThat(records.single().durationMs).isEqualTo(DEFAULT_MAX_RECORDING_TIME_MS) + assertThat(collector.calls.count { it.startsWith("sample") }).isEqualTo(samplesAtEnd) + } + + @Test + fun `maxRecordingTime end marks the record as ended at maxRecordingTime`() { + startInForeground() + openIntervalInTick(0) + + tickUntilRecorded() + + assertThat(records.single().hasEndedAtMaxRecordingTime()).isTrue() + } + + @Test + fun `idle end does not mark the record as ended at maxRecordingTime`() { + startInForeground() + openIntervalInTick(300) + advance(500) + + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(records.single().hasEndedAtMaxRecordingTime()).isFalse() + } + + @Test + fun `background end does not mark the record as ended at maxRecordingTime`() { + startInForeground() + openIntervalInTick(300) + advance(500) + + appStateProvider.background() + executor.runPending() + sdkExecutor.runAll() + + assertThat(records.single().hasEndedAtMaxRecordingTime()).isFalse() + } + + @Test + fun `collector that always throws does not stop the maxRecordingTime end`() { + startInForeground() + collector.throwOnSample = true + openIntervalInTick(0) + + tickUntilRecorded() + + assertThat(records.single().durationMs).isEqualTo(DEFAULT_MAX_RECORDING_TIME_MS) + assertThat(records.single().hasEndedAtMaxRecordingTime()).isTrue() + } + + @Test + fun `after maxRecordingTime no interval opens until idle`() { + startInForeground() + openIntervalInTick(0) + advance(DEFAULT_MAX_RECORDING_TIME_MS) + executor.runTick() + collector.calls.clear() + + signal.report(HangSignal.State.SUSPICIOUS, 0) + assertThat(collector.calls).isEmpty() + + signal.report(HangSignal.State.IDLE, 0) + signal.report(HangSignal.State.SUSPICIOUS, 0) + assertThat(collector.calls).containsExactly("start ${nowMs()}") + } + + @Test + fun `background ends open interval and cancels tick`() { + startInForeground() + openIntervalInTick(300) + advance(500) + + appStateProvider.background() + executor.runPending() + sdkExecutor.runAll() + + assertThat(records.single().durationMs).isEqualTo(800) + assertThat(signal.isStarted).isFalse() + assertThat(executor.activePeriodicTasks).isEmpty() + } + + @Test + fun `foreground after background starts the signals and the tick again`() { + startInForeground() + appStateProvider.background() + executor.runPending() + + appStateProvider.foreground() + executor.runPending() + + assertThat(signal.startCount).isEqualTo(2) + assertThat(signal.isStarted).isTrue() + assertThat(executor.activePeriodicTasks).hasSize(1) + } + + @Test + fun `signal cancel cancels the recording and sends no record`() { + startInForeground() + openIntervalInTick(300) + collector.calls.clear() + + signal.cancel() + executor.runTick() + sdkExecutor.runAll() + + assertThat(collector.calls).containsExactly("cancel") + assertThat(records).isEmpty() + } + + @Test + fun `signal change from another thread runs on the recorder thread`() { + startInForeground() + val sinceMs = nowMs() + + val thread = Thread { signal.report(HangSignal.State.SUSPICIOUS, 0) } + thread.start() + thread.join() + assertThat(collector.calls).isEmpty() + + executor.runPending() + assertThat(collector.calls).containsExactly("start $sinceMs") + } + + @Test + fun `signal duration from another thread is measured at the call`() { + startInForeground() + val sinceMs = nowMs() - 300 + + val thread = Thread { signal.report(HangSignal.State.SUSPICIOUS, 300) } + thread.start() + thread.join() + advance(100) + executor.runPending() + + assertThat(collector.calls).containsExactly("start $sinceMs") + } + + @Test + fun `no subscription starts no thread`() { + appStateProvider.foreground() + + assertThat(executors).isEmpty() + assertThat(appStateProvider.listeners).isEmpty() + assertThat(signal.startCount).isEqualTo(0) + } + + @Test + fun `signals start only at foreground`() { + recorder.subscribe(listener) + executor.runPending() + + assertThat(executors).hasSize(1) + assertThat(signal.startCount).isEqualTo(0) + assertThat(executor.activePeriodicTasks).isEmpty() + } + + @Test + fun `subscribe and unsubscribe from one thread keep their order`() { + appStateProvider.foreground() + + recorder.subscribe(listener) + recorder.unsubscribe(listener) + executor.runPending() + + assertThat(signal.isStarted).isFalse() + assertThat(appStateProvider.listeners).isEmpty() + } + + @Test + fun `last unsubscribe stops signals and the tick but keeps the executor`() { + val otherListener = HangRecorderListener {} + recorder.subscribe(otherListener) + startInForeground() + + recorder.unsubscribe(otherListener) + executor.runPending() + assertThat(signal.isStarted).isTrue() + + recorder.unsubscribe(listener) + executor.runPending() + assertThat(signal.isStarted).isFalse() + assertThat(executor.activePeriodicTasks).isEmpty() + assertThat(executor.isShutdown).isFalse() + assertThat(appStateProvider.listeners).isEmpty() + } + + @Test + fun `subscribers share one app state listener`() { + recorder.subscribe(listener) + recorder.subscribe(HangRecorderListener {}) + executor.runPending() + + assertThat(appStateProvider.listeners).hasSize(1) + } + + @Test + fun `last unsubscribe drops an open interval without a record`() { + startInForeground() + openIntervalInTick(300) + + recorder.unsubscribe(listener) + executor.runPending() + sdkExecutor.runAll() + + assertThat(collector.calls.last()).isEqualTo("cancel") + assertThat(collector.calls.none { it.startsWith("stop") }).isTrue() + assertThat(records).isEmpty() + } + + @Test + fun `last unsubscribe does not close signals or collectors`() { + startInForeground() + + recorder.unsubscribe(listener) + executor.runPending() + + assertThat(signal.closeCount).isEqualTo(0) + assertThat(collector.calls).doesNotContain("close") + } + + @Test + fun `subscribe after last unsubscribe reuses the executor`() { + startInForeground() + recorder.unsubscribe(listener) + executor.runPending() + + startInForeground() + + assertThat(executors).hasSize(1) + assertThat(signal.isStarted).isTrue() + assertThat(executor.activePeriodicTasks).hasSize(1) + } + + @Test + fun `signal that throws on stop leaves no second tick loop`() { + signal.throwOnStop = true + startInForeground() + openIntervalInTick(300) + + appStateProvider.background() + executor.runPending() + sdkExecutor.runAll() + appStateProvider.foreground() + executor.runPending() + + assertThat(executor.taskFailures).hasSize(1) + assertThat(executor.activePeriodicTasks).hasSize(1) + assertThat(records).hasSize(1) + } + + @Test + fun `collector that throws on cancel does not block a later subscribe`() { + collector.throwOnCancel = true + startInForeground() + openIntervalInTick(300) + recorder.unsubscribe(listener) + executor.runPending() + collector.throwOnCancel = false + + startInForeground() + + assertThat(executor.taskFailures).hasSize(1) + assertThat(signal.isStarted).isTrue() + assertThat(executor.activePeriodicTasks).hasSize(1) + } + + @Test + fun `exception in collector does not stop the tick loop`() { + startInForeground() + collector.throwOnSample = true + openIntervalInTick(300) + collector.throwOnSample = false + + executor.runTick() + + assertThat(collector.calls.count { it.startsWith("sample") }).isEqualTo(2) + verify(logger).log(eq(SentryLevel.ERROR), any(), any()) + } + + @Test + fun `close closes signals and collectors once on the recorder thread`() { + startInForeground() + + recorder.close() + assertThat(signal.closeCount).isEqualTo(0) + assertThat(collector.calls).doesNotContain("close") + executor.runPending() + recorder.close() + executor.runPending() + + assertThat(signal.closeCount).isEqualTo(1) + assertThat(collector.calls.count { it == "close" }).isEqualTo(1) + assertThat(executor.isShutdown).isTrue() + } + + @Test + fun `close after the last unsubscribe still closes everything`() { + startInForeground() + recorder.unsubscribe(listener) + executor.runPending() + + recorder.close() + executor.runPending() + + assertThat(signal.closeCount).isEqualTo(1) + assertThat(collector.calls.count { it == "close" }).isEqualTo(1) + assertThat(executor.isShutdown).isTrue() + } + + @Test + fun `signal that throws on close still lets the executor shut down`() { + signal.throwOnClose = true + startInForeground() + + recorder.close() + executor.runPending() + + assertThat(executor.taskFailures).hasSize(1) + assertThat(executor.isShutdown).isTrue() + } + + @Test + fun `collector that throws on close still lets the executor shut down`() { + collector.throwOnClose = true + startInForeground() + + recorder.close() + executor.runPending() + + assertThat(executor.taskFailures).hasSize(1) + assertThat(executor.isShutdown).isTrue() + } + + @Test + fun `close stops ticks and ignores later calls`() { + var ticks = 0 + recorder.addTickListener { ticks++ } + startInForeground() + + recorder.close() + executor.runPending() + executor.runTick() + assertThat(ticks).isEqualTo(0) + + recorder.close() + recorder.subscribe(listener) + recorder.unsubscribe(listener) + appStateProvider.foreground() + signal.report(HangSignal.State.SUSPICIOUS, 0) + executor.runTick() + + assertThat(ticks).isEqualTo(0) + assertThat(executors).hasSize(1) + assertThat(executor.taskFailures).isEmpty() + assertThat(signal.isStarted).isFalse() + assertThat(collector.calls.count { it == "close" }).isEqualTo(1) + } + + @Test + fun `close removes the app state listener`() { + startInForeground() + + recorder.close() + executor.runPending() + + assertThat(appStateProvider.listeners).isEmpty() + } + + @Test + fun `close drops an open interval without a record`() { + startInForeground() + openIntervalInTick(300) + + recorder.close() + executor.runPending() + sdkExecutor.runAll() + + assertThat(records).isEmpty() + assertThat(collector.calls).contains("cancel") + } + + @Test + fun `record dropped by a full sdk executor queue is logged`() { + options.executorService = NonOverridableNoOpSentryExecutorService() + startInForeground() + openIntervalInTick(300) + + signal.report(HangSignal.State.IDLE, 0) + executor.runPending() + + verify(logger) + .log(eq(SentryLevel.WARNING), eq("Dropped a hang record, the SDK executor queue is full")) + } + + @Test + fun `close without subscription starts no thread`() { + recorder.close() + recorder.subscribe(listener) + + assertThat(executors).isEmpty() + } + + @Test + fun `close without subscription closes signals and collectors`() { + recorder.close() + + assertThat(signal.closeCount).isEqualTo(1) + assertThat(collector.calls).containsExactly("close") + } + + private class FakeAppStateProvider : AppStateProvider { + val listeners = mutableListOf() + private var inBackground: Boolean? = null + + override fun addAppStateListener(listener: AppState.AppStateListener) { + listeners.add(listener) + when (inBackground) { + false -> listener.onForeground() + true -> listener.onBackground() + null -> Unit + } + } + + override fun removeAppStateListener(listener: AppState.AppStateListener) { + listeners.remove(listener) + } + + fun foreground() { + inBackground = false + listeners.toList().forEach { it.onForeground() } + } + + fun background() { + inBackground = true + listeners.toList().forEach { it.onBackground() } + } + } + + private class FakeSignal(private val metronome: Metronome) : HangSignal { + private var listener: HangSignalListener? = null + private var nextTickAction: (() -> Unit)? = null + private val tickListener = Metronome.TickListener { _ -> + val action = nextTickAction + nextTickAction = null + action?.invoke() + } + var startCount = 0 + var closeCount = 0 + var throwOnStop = false + var throwOnClose = false + + val isStarted: Boolean + get() = listener != null + + override fun start(listener: HangSignalListener) { + startCount++ + this.listener = listener + metronome.addTickListener(tickListener) + } + + override fun stop() { + listener = null + metronome.removeTickListener(tickListener) + if (throwOnStop) { + throw IllegalStateException("stop failed") + } + } + + override fun close() { + closeCount++ + if (throwOnClose) { + throw IllegalStateException("close failed") + } + } + + fun onNextTick(action: () -> Unit) { + nextTickAction = action + } + + fun report(state: HangSignal.State, durationMs: Long) { + listener?.onSignalChanged(this, state, durationMs) + } + + fun cancel() { + listener?.onSignalCanceled(this) + } + } + + private class FakeCollector : HangDataCollector { + val calls = mutableListOf() + var throwOnSample = false + var throwOnCancel = false + var throwOnClose = false + var onRecordingStoppedAction: (HangRecord.Builder) -> Unit = {} + + override fun onRecordingStarted(interval: HangInterval) { + calls.add("start ${interval.startTimeMs}") + } + + override fun onSample(interval: HangInterval) { + calls.add("sample ${interval.startTimeMs}") + if (throwOnSample) { + throw IllegalStateException("collector failed") + } + } + + override fun onRecordingStopped(interval: HangInterval, out: HangRecord.Builder) { + calls.add("stop ${interval.startTimeMs}") + onRecordingStoppedAction(out) + } + + override fun onRecordingCanceled() { + calls.add("cancel") + if (throwOnCancel) { + throw IllegalStateException("cancel failed") + } + } + + override fun close() { + calls.add("close") + if (throwOnClose) { + throw IllegalStateException("close failed") + } + } + } +}