diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 5ab0634a499..24203026b9f 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,103 @@ 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/HangCollectorSetup { + public fun (Lio/sentry/android/core/hang/HangDataCollector;Lio/sentry/android/core/hang/HangRecordWriter;Lio/sentry/android/core/hang/HangSampleStore;)V +} + +public abstract interface class io/sentry/android/core/hang/HangDataCollector { + public abstract fun sample ()Ljava/lang/Object; +} + +public final class io/sentry/android/core/hang/HangManager : io/sentry/android/core/AppState$AppStateListener, io/sentry/android/core/hang/Metronome { + public static final field DEFAULT_EXECUTOR_FACTORY Lio/sentry/android/core/hang/HangManager$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;JJILio/sentry/android/core/hang/HangManager$ExecutorFactory;Lio/sentry/android/core/hang/HangManager$SignalFactory;Ljava/util/List;)V + public fun addTickListener (Lio/sentry/android/core/hang/Metronome$TickListener;)V + public fun nowMs ()J + 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/HangRecordingListener;)V + public fun unsubscribe (Lio/sentry/android/core/hang/HangRecordingListener;)V +} + +public abstract interface class io/sentry/android/core/hang/HangManager$ExecutorFactory { + public abstract fun create ()Ljava/util/concurrent/ScheduledExecutorService; +} + +public abstract interface class io/sentry/android/core/hang/HangManager$SignalFactory { + public abstract fun create (Lio/sentry/android/core/hang/Metronome;)Ljava/util/List; +} + +public final class io/sentry/android/core/hang/HangRecord { + public fun getDurationMs ()J + public fun getStackTraces ()Ljava/util/List; + public fun getStartTimestampMs ()J +} + +public final class io/sentry/android/core/hang/HangRecord$Builder { + public fun ()V + public fun addStackTrace (Lio/sentry/android/core/anr/AnrStackTrace;)Lio/sentry/android/core/hang/HangRecord$Builder; + public fun build ()Lio/sentry/android/core/hang/HangRecord; + public fun setDurationMs (J)Lio/sentry/android/core/hang/HangRecord$Builder; + public fun setStartTimestampMs (J)Lio/sentry/android/core/hang/HangRecord$Builder; +} + +public abstract interface class io/sentry/android/core/hang/HangRecordWriter { + public abstract fun write (Ljava/lang/Object;Lio/sentry/android/core/hang/HangRecord$Builder;)V +} + +public abstract interface class io/sentry/android/core/hang/HangRecordingListener { + public abstract fun onHangRecorded (Lio/sentry/android/core/hang/HangRecord;)V + public abstract fun onHangStarted ()Lio/sentry/android/core/hang/HangRecordingRequest; +} + +public final class io/sentry/android/core/hang/HangRecordingRequest { + public fun (ZZ)V + public fun shouldPersist ()Z + public fun shouldRecord ()Z +} + +public abstract interface class io/sentry/android/core/hang/HangSampleStore : java/io/Closeable { + public abstract fun add (Ljava/lang/Object;)V + public abstract fun clear ()V +} + +public abstract interface class io/sentry/android/core/hang/HangSignal { + 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 nowMs ()J + 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 00000000000..29cb638d5aa --- /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/HangCollectorSetup.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangCollectorSetup.java new file mode 100644 index 00000000000..eb8c171c91c --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangCollectorSetup.java @@ -0,0 +1,22 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** A collector, the writer of its values into the record, and its optional store. */ +@ApiStatus.Internal +public final class HangCollectorSetup { + final @NotNull HangDataCollector collector; + final @NotNull HangRecordWriter writer; + final @Nullable HangSampleStore store; + + public HangCollectorSetup( + final @NotNull HangDataCollector collector, + final @NotNull HangRecordWriter writer, + final @Nullable HangSampleStore store) { + this.collector = collector; + this.writer = writer; + this.store = store; + } +} 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 00000000000..e54762ed5df --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangDataCollector.java @@ -0,0 +1,13 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +/** Reads one value from a data source. */ +@ApiStatus.Internal +public interface HangDataCollector { + + /** One value, or null for no value. Must be fast, no IO. */ + @Nullable + T sample(); +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangManager.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangManager.java new file mode 100644 index 00000000000..629b5863845 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangManager.java @@ -0,0 +1,396 @@ +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.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; + +/** + * Starts a {@link HangRecorder} when a {@link HangSignal} reports {@link + * HangSignal.State#SUSPICIOUS}, lets it sample the {@link HangDataCollector}s on each tick, and + * gives its {@link HangRecord} to the subscribers that asked for it when the hang ends: when the + * signal reports {@link HangSignal.State#IDLE} or the app goes to the background. A hang that never + * ends, for example because the process is killed, gives no record. + * + *

Only the first {@code maxRecordingTimeMs} of a hang are sampled. The hang stays open after + * that, and its record has the full duration. + * + *

Each subscriber says in {@link HangRecordingListener#onHangStarted()} what it needs from the + * hang. If no subscriber needs a record, the hang is not recorded and the collectors are not + * called. If a subscriber asks for it, the values also go to the {@link HangSampleStore}s from the + * start of the hang, so the fatal ANR path can read them after a process kill. + * + *

Runs on its own thread, {@code SentryHangManager}, which starts at the first subscription and + * stops at the last {@link #unsubscribe(HangRecordingListener)}. The manager is then closed, and + * later calls do nothing. All calls from other threads are moved to that thread, so the recording + * state needs no lock. The manager calls its signals, its collectors, its stores 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 HangManager implements Metronome, AppState.AppStateListener { + + public static final long DEFAULT_POLLING_INTERVAL_MS = 66; + + /** How long a hang is sampled at most. The hang itself can last longer. */ + public static final long DEFAULT_MAX_RECORDING_TIME_MS = 8_000; + + /** + * Creates the executor of the manager 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 manager, with the manager 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, "SentryHangManager"); + 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 int maxSamples; + 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 volatile boolean closed; + + private final @NotNull Set subscriptions = new LinkedHashSet<>(); + private boolean signalsStarted; + private @Nullable Future tickFuture; + private @Nullable HangRecorder activeRecorder; + + 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; + postOnManagerThread(() -> handleSignalChanged(state, sinceMs)); + } + + @Override + public void onSignalCanceled(final @NotNull HangSignal signal) { + postOnManagerThread(HangManager.this::handleSignalCanceled); + } + }; + + /** + * Creates a manager that starts no thread before the first {@link + * #subscribe(HangRecordingListener)}. + */ + public HangManager( + final @NotNull SentryOptions options, + final @NotNull AppStateProvider appStateProvider, + final @NotNull MonotonicTicker ticker, + final @NotNull EpochClock epochClock, + final long pollingIntervalMs, + final long maxRecordingTimeMs, + final int maxSamples, + 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.maxSamples = maxSamples; + this.executorFactory = executorFactory; + this.signals = Collections.unmodifiableList(new ArrayList<>(signalFactory.create(this))); + this.collectors = Collections.unmodifiableList(new ArrayList<>(collectors)); + } + + /** + * Starts the manager thread at the first call, and the signals when the app is in the foreground. + * The manager calls {@link HangRecordingListener#onHangStarted()} on the manager thread and + * {@link HangRecordingListener#onHangRecorded(HangRecord)} on the SDK executor, see {@link + * SentryOptions#getExecutorService()}. A listener gets the record of a hang only if it asked for + * a record when the hang started. Does nothing after the last {@link + * #unsubscribe(HangRecordingListener)}. + */ + public void subscribe(final @NotNull HangRecordingListener listener) { + postOnManagerThread( + () -> { + if (subscriptions.add(listener) && subscriptions.size() == 1) { + appStateProvider.addAppStateListener(this); + } + }, + true); + } + + /** + * The last unsubscribe closes the manager: it stops the signals and the tick, drops an open hang + * record without delivering it, closes the signals and the stores, and stops the manager thread. + * Later calls do nothing. Otherwise the listener still gets the record of an open hang that it + * asked for. + */ + public void unsubscribe(final @NotNull HangRecordingListener listener) { + postOnManagerThread( + () -> { + if (subscriptions.remove(listener) && subscriptions.isEmpty()) { + closeOnManagerThread(); + } + }, + false); + } + + /** + * The manager calls the listener on the manager 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); + } + + @Override + public void onForeground() { + postOnManagerThread(this::startSignals, false); + } + + @Override + public void onBackground() { + postOnManagerThread(() -> stopSignals(true), false); + } + + private void postOnManagerThread(final @NotNull Runnable task, final boolean startManagerThread) { + try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { + if (closed) { + return; + } + @Nullable ScheduledExecutorService current = executor; + if (current == null) { + if (!startManagerThread) { + return; + } + current = executorFactory.create(); + executor = current; + // Runs before any other task of this single-thread executor. + current.execute(() -> executorThread = Thread.currentThread()); + } + current.execute(() -> { + // A task queued before the last unsubscribe ran must not open the manager again. + if (!closed) { + task.run(); + } + }); + } + } + + @SuppressWarnings("ReferenceEquality") + private void postOnManagerThread(final @NotNull Runnable task) { + if (Thread.currentThread() == executorThread) { + task.run(); + } else { + postOnManagerThread(task, false); + } + } + + private void closeOnManagerThread() { + final @Nullable ScheduledExecutorService self; + try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { + closed = true; + self = executor; + } + try { + try { + appStateProvider.removeAppStateListener(this); + stopSignals(false); + } finally { + closeSignalsAndStores(); + } + } finally { + if (self != null) { + self.shutdown(); + } + } + } + + private void closeSignalsAndStores() { + try { + for (final @NotNull HangSignal signal : signals) { + signal.close(); + } + } finally { + for (final @NotNull HangCollectorSetup setup : collectors) { + final @Nullable HangSampleStore store = setup.store; + if (store != null) { + try { + store.close(); + } catch (IOException e) { + options.getLogger().log(SentryLevel.WARNING, "Failed to close a hang sample store", e); + } + } + } + } + } + + private void startSignals() { + final @Nullable ScheduledExecutorService self = executor; + if (self == null || subscriptions.isEmpty() || signalsStarted) { + return; + } + signalsStarted = true; + // Scheduled first, so a signal that fails to start does not stop the tick for the others. + tickFuture = + self.scheduleWithFixedDelay(this::tick, 0, pollingIntervalMs, TimeUnit.MILLISECONDS); + for (final @NotNull HangSignal signal : signals) { + signal.start(signalListener); + } + } + + private void stopSignals(final boolean endIntervalWithRecord) { + if (!signalsStarted) { + return; + } + signalsStarted = 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) { + endRecord(nowMs()); + } else { + cancelRecord(); + } + } + } + + private void tick() { + try { + final long nowMs = nowMs(); + for (final @NotNull TickListener listener : tickListeners) { + listener.onMetronomeTick(nowMs); + } + final @Nullable HangRecorder recorder = activeRecorder; + if (recorder != null && nowMs - recorder.getStartTimeMs() < maxRecordingTimeMs) { + recorder.sample(maxSamples); + } + } catch (Throwable t) { + // scheduleWithFixedDelay stops all later ticks after an exception. + ExceptionUtils.rethrowIfFatal(t); + options.getLogger().log(SentryLevel.ERROR, "HangManager tick failed", t); + } + } + + private void handleSignalChanged(final @NotNull HangSignal.State state, final long sinceMs) { + if (!signalsStarted) { + return; + } + if (state == HangSignal.State.SUSPICIOUS) { + if (activeRecorder != null) { + return; + } + final long nowTimestampMs = TimeUnit.NANOSECONDS.toMillis(epochClock.now().epochNanos()); + activeRecorder = + HangRecorder.start( + subscriptions, + collectors, + sinceMs, + nowTimestampMs - (nowMs() - sinceMs), + options.getLogger()); + } else { + endRecord(sinceMs); + } + } + + private void handleSignalCanceled() { + cancelRecord(); + } + + private void cancelRecord() { + activeRecorder = null; + } + + private void endRecord(final long endTimeMs) { + final @Nullable HangRecorder recorder = activeRecorder; + if (recorder == null) { + return; + } + activeRecorder = null; + final @NotNull HangRecord record = recorder.end(endTimeMs); + final @NotNull List listeners = recorder.getListeners(); + try { + final @NotNull Future delivery = + options + .getExecutorService() + .submit(() -> { + for (final @NotNull HangRecordingListener 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); + } + } + + @Override + public long nowMs() { + return TimeUnit.NANOSECONDS.toMillis(ticker.tickNanos()); + } +} 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 00000000000..4ed0be3aadd --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecord.java @@ -0,0 +1,68 @@ +package io.sentry.android.core.hang; + +import io.sentry.android.core.anr.AnrStackTrace; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** The collected data of one recorded hang. */ +@ApiStatus.Internal +public final class HangRecord { + + private final long durationMs; + private final long startTimestampMs; + private final @NotNull List stackTraces; + + private HangRecord(final @NotNull Builder builder) { + this.durationMs = builder.durationMs; + this.startTimestampMs = builder.startTimestampMs; + this.stackTraces = Collections.unmodifiableList(new ArrayList<>(builder.stackTraces)); + } + + /** The full duration of the hang, also when only its start was sampled. */ + public long getDurationMs() { + return durationMs; + } + + /** The start of the hang, as Unix time in milliseconds. */ + public long getStartTimestampMs() { + return startTimestampMs; + } + + /** + * The stacks of the watched thread, in the order they were sampled. They cover only the start of + * a long hang. + */ + public @NotNull List getStackTraces() { + return stackTraces; + } + + /** Builds a {@link HangRecord}. */ + public static final class Builder { + private long durationMs; + private long startTimestampMs; + private final @NotNull List stackTraces = new ArrayList<>(); + + public @NotNull Builder setDurationMs(final long durationMs) { + this.durationMs = durationMs; + return this; + } + + /** The start of the hang, as Unix time in milliseconds. */ + public @NotNull Builder setStartTimestampMs(final long startTimestampMs) { + this.startTimestampMs = startTimestampMs; + return this; + } + + public @NotNull Builder addStackTrace(final @NotNull AnrStackTrace stackTrace) { + stackTraces.add(stackTrace); + return this; + } + + public @NotNull HangRecord build() { + return new HangRecord(this); + } + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordWriter.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordWriter.java new file mode 100644 index 00000000000..ae31db9313c --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordWriter.java @@ -0,0 +1,11 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +// Not a BiConsumer, which needs API 24. +/** Puts one value of a collector into the record. */ +@ApiStatus.Internal +public interface HangRecordWriter { + void write(@NotNull T sample, @NotNull HangRecord.Builder record); +} 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 00000000000..d32241a5a97 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecorder.java @@ -0,0 +1,147 @@ +package io.sentry.android.core.hang; + +import io.sentry.ILogger; +import io.sentry.SentryLevel; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Records one hang: asks the listeners what they need, samples the collectors into the record, and + * writes the samples to the stores. + */ +final class HangRecorder { + + private final @NotNull List> collectors; + private final @NotNull List listeners; + private final @NotNull ILogger logger; + private final long startTimeMs; + private final @NotNull HangRecord.Builder record; + private boolean persist; + private int samplingTicks; + + private HangRecorder( + final @NotNull List> collectors, + final @NotNull List listeners, + final @NotNull ILogger logger, + final long startTimeMs, + final long startTimestampMs, + final boolean persist) { + this.collectors = collectors; + this.listeners = listeners; + this.logger = logger; + this.startTimeMs = startTimeMs; + this.record = new HangRecord.Builder().setStartTimestampMs(startTimestampMs); + this.persist = persist; + } + + /** + * Asks each listener what it needs from this hang, and clears the stores if one asks to persist. + * + * @param startTimeMs the start of the hang, as a monotonic time in milliseconds + * @param startTimestampMs the start of the hang, as Unix time in milliseconds + * @return null if no listener asks for a record + */ + static @Nullable HangRecorder start( + final @NotNull Collection subscriptions, + final @NotNull List> collectors, + final long startTimeMs, + final long startTimestampMs, + final @NotNull ILogger logger) { + boolean persist = false; + final @NotNull List listeners = new ArrayList<>(); + for (final @NotNull HangRecordingListener listener : subscriptions) { + final @Nullable HangRecordingRequest request = listener.onHangStarted(); + if (request != null && request.shouldRecord()) { + listeners.add(listener); + if (request.shouldPersist()) { + persist = true; + } + } + } + if (listeners.isEmpty()) { + return null; + } + final @NotNull HangRecorder recorder = + new HangRecorder(collectors, listeners, logger, startTimeMs, startTimestampMs, persist); + if (persist) { + recorder.clearStores(); + } + return recorder; + } + + /** The start of the hang, as a monotonic time in milliseconds. */ + long getStartTimeMs() { + return startTimeMs; + } + + /** + * Samples each collector one time, at most {@code maxSamples} times for this hang. A store error + * stops the persistence of this hang. + */ + void sample(final int maxSamples) { + // Stop sampling at the cap instead of rotating out samples: the early ones show how the hang + // began. + if (samplingTicks >= maxSamples) { + return; + } + samplingTicks++; + for (final @NotNull HangCollectorSetup setup : collectors) { + try { + sample(setup, record, persist); + } catch (IOException e) { + stopPersisting(e); + } + } + } + + /** The listeners that asked for the record of this hang. */ + @NotNull + List getListeners() { + return listeners; + } + + /** Builds the record of this hang. */ + @NotNull + HangRecord end(final long endTimeMs) { + return record.setDurationMs(endTimeMs - startTimeMs).build(); + } + + private void clearStores() { + for (final @NotNull HangCollectorSetup setup : collectors) { + final @Nullable HangSampleStore store = setup.store; + if (store == null) { + continue; + } + try { + store.clear(); + } catch (IOException e) { + stopPersisting(e); + return; + } + } + } + + private static void sample( + final @NotNull HangCollectorSetup setup, + final @NotNull HangRecord.Builder record, + final boolean persist) + throws IOException { + final @Nullable T sample = setup.collector.sample(); + if (sample == null) { + return; + } + setup.writer.write(sample, record); + if (persist && setup.store != null) { + setup.store.add(sample); + } + } + + private void stopPersisting(final @NotNull IOException e) { + persist = false; + logger.log(SentryLevel.WARNING, "Failed to write to a hang sample store", e); + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordingListener.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordingListener.java new file mode 100644 index 00000000000..07228c7f045 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordingListener.java @@ -0,0 +1,26 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@ApiStatus.Internal +public interface HangRecordingListener { + + /** + * A hang started. Must be fast, no IO. + * + * @return what this listener needs from the recording of this hang, or null for nothing + */ + @Nullable + HangRecordingRequest onHangStarted(); + + /** + * The record of a hang for which this listener asked for a record in {@link #onHangStarted()}. + * + *

The listener gets the record also if it unsubscribed during the hang or before the delivery. + * Only the last {@link HangManager#unsubscribe(HangRecordingListener)} drops an open hang without + * a record. + */ + void onHangRecorded(@NotNull HangRecord record); +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordingRequest.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordingRequest.java new file mode 100644 index 00000000000..3c080c2aee6 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangRecordingRequest.java @@ -0,0 +1,26 @@ +package io.sentry.android.core.hang; + +import org.jetbrains.annotations.ApiStatus; + +/** What a subscriber needs from the recording of one hang. Immutable. */ +@ApiStatus.Internal +public final class HangRecordingRequest { + + private final boolean record; + private final boolean persist; + + public HangRecordingRequest(final boolean record, final boolean persist) { + this.record = record; + this.persist = persist; + } + + /** Whether this subscriber gets the record of this hang. */ + public boolean shouldRecord() { + return record; + } + + /** Whether the values of this hang also go to the stores. Has no effect without a record. */ + public boolean shouldPersist() { + return persist; + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSampleStore.java b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSampleStore.java new file mode 100644 index 00000000000..4063f02abd7 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSampleStore.java @@ -0,0 +1,16 @@ +package io.sentry.android.core.hang; + +import java.io.Closeable; +import java.io.IOException; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** Stores values on disk. */ +@ApiStatus.Internal +public interface HangSampleStore extends Closeable { + + /** Removes all stored values. */ + void clear() throws IOException; + + void add(@NotNull T sample) throws IOException; +} 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 00000000000..7e79319e23a --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/HangSignal.java @@ -0,0 +1,31 @@ +package io.sentry.android.core.hang; + +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 { + + /** + * 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. */ + 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 00000000000..70699e6da61 --- /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 00000000000..9c8a353de2f --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/hang/Metronome.java @@ -0,0 +1,28 @@ +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); + + /** + * The current time of this metronome, as a monotonic time in milliseconds with an arbitrary + * origin. It has the same origin as the time of each tick. Can be called from any thread. + */ + long nowMs(); + + interface TickListener { + /** + * Must be fast, it delays the metronome and the other listeners. + * + * @param nowMs the time of this tick, see {@link Metronome#nowMs()} + */ + 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 00000000000..898ad76f70f --- /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 00000000000..b3ad510d82e --- /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/HangManagerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangManagerTest.kt new file mode 100644 index 00000000000..4fca09bdbf1 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangManagerTest.kt @@ -0,0 +1,1231 @@ +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.HangManager.DEFAULT_MAX_RECORDING_TIME_MS +import io.sentry.android.core.hang.HangManager.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.io.IOException +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.times +import org.mockito.kotlin.verify + +class HangManagerTest { + + 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 manager: HangManager + private lateinit var signal: FakeSignal + private val signals = mutableListOf() + private lateinit var collector: FakeCollector + private lateinit var store: FakeStore + private val records = mutableListOf() + private val listener = FakeListener(records) + private val record = HangRecordingRequest(true, false) + private val persist = HangRecordingRequest(true, true) + + 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() + store = FakeStore() + createRecorder() + } + + private fun createRecorder( + signalCount: Int = 1, + collectors: List> = listOf(setup(collector, store)), + maxSamples: Int = MAX_SAMPLES, + ) { + manager = + HangManager( + options, + appStateProvider, + ticker, + epochClock, + DEFAULT_POLLING_INTERVAL_MS, + DEFAULT_MAX_RECORDING_TIME_MS, + maxSamples, + { FakeScheduledExecutorService().also { executors.add(it) } }, + { metronome -> + signals.clear() + repeat(signalCount) { signals.add(FakeSignal(metronome)) } + signals + }, + collectors, + ) + signal = signals.first() + } + + private fun setup(collector: FakeCollector, store: FakeStore?) = + HangCollectorSetup(collector, writer, store) + + private fun recordedValues(): List> { + sdkExecutor.runAll() + return records.map { record -> record.stackTraces.map { it.stack.single().methodName } } + } + + private fun nowMs(): Long = TimeUnit.NANOSECONDS.toMillis(ticker.tickNanos()) + + private fun advance(ms: Long) { + ticker.advance(ms, MILLISECONDS) + unixTimeMs += ms + } + + private fun startInForeground() { + manager.subscribe(listener) + executor.runPending() + appStateProvider.foreground() + executor.runPending() + } + + private fun openHangInTick(durationMs: Long) { + signal.onNextTick { signal.report(HangSignal.State.SUSPICIOUS, durationMs) } + executor.runTick() + } + + private fun tickEvery66Ms(count: Int) { + repeat(count) { + advance(DEFAULT_POLLING_INTERVAL_MS) + executor.runTick() + } + } + + private fun tickPastMaxRecordingTime() { + tickEvery66Ms((DEFAULT_MAX_RECORDING_TIME_MS / DEFAULT_POLLING_INTERVAL_MS + 2).toInt()) + sdkExecutor.runAll() + } + + @Test + fun `suspicious starts a record, asks the subscriber and samples in the same tick`() { + startInForeground() + + openHangInTick(300) + + assertThat(listener.started).isEqualTo(1) + assertThat(collector.calls).containsExactly("sample") + } + + @Test + fun `each subscriber is asked once at the start of a hang`() { + val other = FakeListener() + manager.subscribe(other) + startInForeground() + + openHangInTick(300) + executor.runTick() + + assertThat(listener.started).isEqualTo(1) + assertThat(other.started).isEqualTo(1) + } + + @Test + fun `subscriber added during a hang is not asked and gets no record`() { + startInForeground() + openHangInTick(300) + val late = FakeListener(request = persist) + + manager.subscribe(late) + executor.runPending() + tickEvery66Ms(15) + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(late.started).isEqualTo(0) + assertThat(late.records).isEmpty() + assertThat(store.calls).isEmpty() + } + + @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 `ticks carry the time of nowMs`() { + val ticks = mutableListOf() + manager.addTickListener { ticks.add(it) } + startInForeground() + ticker.advance(100, MILLISECONDS) + + executor.runTick() + + assertThat(ticks.last()).isEqualTo(manager.nowMs()) + assertThat(manager.nowMs()).isEqualTo(nowMs()) + } + + @Test + fun `tick listeners run before collectors sample`() { + val calls = collector.calls + manager.addTickListener { calls.add("tick") } + startInForeground() + + openHangInTick(300) + executor.runTick() + + assertThat(calls).containsExactly("tick", "sample", "tick", "sample").inOrder() + } + + @Test + fun `idle ends the hang and notifies listeners on sdk executor`() { + startInForeground() + val suspiciousSinceMs = nowMs() - 300 + val timestampAtOpenMs = unixTimeMs + openHangInTick(300) + advance(1_000) + val idleSinceMs = nowMs() - 20 + + signal.report(HangSignal.State.IDLE, 20) + + assertThat(records).isEmpty() + sdkExecutor.runAll() + val record = records.single() + assertThat(record.durationMs).isEqualTo(idleSinceMs - suspiciousSinceMs) + assertThat(record.startTimestampMs).isEqualTo(timestampAtOpenMs - 300) + assertThat(recordedValues().single()).containsExactly("s1") + } + + @Test + fun `sampling stops at maxRecordingTime counted from the monotonic start of the hang`() { + startInForeground() + openHangInTick(300) + collector.calls.clear() + + advance(DEFAULT_MAX_RECORDING_TIME_MS - 300 - 1) + executor.runTick() + assertThat(collector.calls).hasSize(1) + + advance(1) + executor.runTick() + sdkExecutor.runAll() + assertThat(collector.calls).hasSize(1) + assertThat(records).isEmpty() + } + + @Test + fun `the writer puts the non-null values of the hang into the record in order`() { + startInForeground() + openHangInTick(300) + collector.returnNull = true + executor.runTick() + collector.returnNull = false + executor.runTick() + + signal.report(HangSignal.State.IDLE, 0) + + assertThat(recordedValues().single()).containsExactly("s1", "s3").inOrder() + } + + @Test + fun `a new hang starts with an empty record`() { + startInForeground() + openHangInTick(300) + signal.report(HangSignal.State.IDLE, 0) + + openHangInTick(300) + signal.report(HangSignal.State.IDLE, 0) + + assertThat(recordedValues()).containsExactly(listOf("s1"), listOf("s2")).inOrder() + } + + @Test + fun `collectors sample on exactly maxSamples ticks`() { + createRecorder(maxSamples = 3) + startInForeground() + openHangInTick(300) + + tickEvery66Ms(5) + signal.report(HangSignal.State.IDLE, 0) + + assertThat(collector.calls).hasSize(3) + assertThat(recordedValues().single()).containsExactly("s1", "s2", "s3").inOrder() + } + + @Test + fun `a sampling tick without a value counts towards maxSamples`() { + createRecorder(maxSamples = 2) + startInForeground() + collector.returnNull = true + openHangInTick(300) + collector.returnNull = false + + tickEvery66Ms(5) + signal.report(HangSignal.State.IDLE, 0) + + assertThat(recordedValues().single()).containsExactly("s2") + } + + @Test + fun `a hang past maxRecordingTime ends at idle with its full duration`() { + startInForeground() + val start = nowMs() + openHangInTick(0) + tickPastMaxRecordingTime() + assertThat(records).isEmpty() + advance(1_000) + + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(records.single().durationMs).isEqualTo(nowMs() - start) + assertThat(records.single().durationMs).isGreaterThan(DEFAULT_MAX_RECORDING_TIME_MS) + } + + @Test + fun `a hang past maxRecordingTime ends at background with its full duration`() { + startInForeground() + val start = nowMs() + openHangInTick(0) + tickPastMaxRecordingTime() + + appStateProvider.background() + executor.runPending() + sdkExecutor.runAll() + + assertThat(records.single().durationMs).isEqualTo(nowMs() - start) + } + + @Test + fun `the writers run in setup order on each tick`() { + val second = FakeCollector("t") + createRecorder(collectors = listOf(setup(collector, null), setup(second, null))) + startInForeground() + openHangInTick(300) + executor.runTick() + + signal.report(HangSignal.State.IDLE, 0) + + assertThat(recordedValues().single()).containsExactly("s1", "t1", "s2", "t2").inOrder() + } + + @Test + fun `values stay in memory when no subscriber asks to persist`() { + startInForeground() + openHangInTick(0) + + tickEvery66Ms(20) + + assertThat(store.calls).isEmpty() + } + + @Test + fun `persisting hang clears the store at its start and then writes each value`() { + listener.request = persist + startInForeground() + + openHangInTick(300) + assertThat(store.calls).containsExactly("clear", "add s1").inOrder() + + executor.runTick() + assertThat(store.calls).containsExactly("clear", "add s1", "add s2").inOrder() + } + + @Test + fun `persisting hang clears each store once`() { + val second = FakeCollector("t") + val secondStore = FakeStore() + listener.request = persist + createRecorder(collectors = listOf(setup(collector, store), setup(second, secondStore))) + startInForeground() + + openHangInTick(300) + tickEvery66Ms(3) + + assertThat(store.calls.count { it == "clear" }).isEqualTo(1) + assertThat(secondStore.calls.first()).isEqualTo("clear") + assertThat(secondStore.calls.count { it == "clear" }).isEqualTo(1) + } + + @Test + fun `one persisting subscriber before one that does not persist is enough`() { + manager.subscribe(FakeListener(request = persist)) + startInForeground() + + openHangInTick(0) + + assertThat(store.calls).contains("clear") + } + + @Test + fun `one persisting subscriber after one that does not persist is enough`() { + startInForeground() + manager.subscribe(FakeListener(request = persist)) + executor.runPending() + + openHangInTick(0) + + assertThat(store.calls).contains("clear") + } + + @Test + fun `persisting hang stops writing at maxSamples`() { + listener.request = persist + createRecorder(maxSamples = 12) + startInForeground() + openHangInTick(0) + + tickEvery66Ms(20) + + assertThat(store.calls.count { it.startsWith("add") }).isEqualTo(12) + } + + @Test + fun `collector without a store is sampled but not persisted`() { + listener.request = persist + createRecorder(collectors = listOf(setup(collector, null))) + startInForeground() + openHangInTick(0) + + tickEvery66Ms(15) + signal.report(HangSignal.State.IDLE, 0) + + assertThat(recordedValues().single()).hasSize(16) + } + + @Test + fun `each persisted hang clears the store once`() { + listener.request = persist + startInForeground() + openHangInTick(0) + tickEvery66Ms(3) + signal.report(HangSignal.State.IDLE, 0) + store.calls.clear() + + openHangInTick(0) + tickEvery66Ms(3) + + assertThat(store.calls.first()).isEqualTo("clear") + assertThat(store.calls.count { it == "clear" }).isEqualTo(1) + } + + @Test + fun `the persist decision is fixed for the hang`() { + startInForeground() + openHangInTick(0) + + listener.request = persist + tickEvery66Ms(15) + + assertThat(store.calls).isEmpty() + } + + @Test + fun `store that fails on add is not written again in this hang`() { + listener.request = persist + store.throwOnAdd = true + startInForeground() + openHangInTick(0) + store.throwOnAdd = false + + tickEvery66Ms(5) + + assertThat(store.calls).containsExactly("clear", "add s1").inOrder() + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), eq("Failed to write to a hang sample store"), any()) + } + + @Test + fun `store that fails on add does not stop the other collectors in the same tick`() { + val second = FakeCollector("t") + val secondStore = FakeStore() + listener.request = persist + store.throwOnAdd = true + createRecorder(collectors = listOf(setup(collector, store), setup(second, secondStore))) + startInForeground() + + openHangInTick(0) + signal.report(HangSignal.State.IDLE, 0) + + assertThat(recordedValues().single()).containsExactly("s1", "t1").inOrder() + assertThat(secondStore.calls).containsExactly("clear") + } + + @Test + fun `store that fails on clear is not written in this hang`() { + listener.request = persist + store.throwOnClear = true + startInForeground() + openHangInTick(0) + + tickEvery66Ms(5) + signal.report(HangSignal.State.IDLE, 0) + + assertThat(store.calls).containsExactly("clear") + assertThat(recordedValues().single()).hasSize(6) + verify(logger) + .log(eq(SentryLevel.WARNING), eq("Failed to write to a hang sample store"), any()) + } + + @Test + fun `store that failed is written again in the next hang`() { + listener.request = persist + store.throwOnClear = true + startInForeground() + openHangInTick(0) + signal.report(HangSignal.State.IDLE, 0) + store.throwOnClear = false + store.calls.clear() + + openHangInTick(0) + tickEvery66Ms(2) + + assertThat(store.calls).containsExactly("clear", "add s2", "add s3", "add s4").inOrder() + } + + @Test + fun `cancel does not touch the store`() { + listener.request = persist + startInForeground() + openHangInTick(0) + tickEvery66Ms(3) + val callsBeforeCancel = store.calls.toList() + + signal.cancel() + executor.runTick() + + assertThat(store.calls).isEqualTo(callsBeforeCancel) + } + + @Test + fun `background end of a persisting hang stops the store writes`() { + listener.request = persist + startInForeground() + openHangInTick(0) + tickEvery66Ms(3) + val callsBeforeEnd = store.calls.toList() + + appStateProvider.background() + executor.runPending() + tickEvery66Ms(3) + + assertThat(store.calls).isEqualTo(callsBeforeEnd) + assertThat(recordedValues().single()).hasSize(4) + } + + @Test + fun `last unsubscribe during a persisting hang stops the store writes`() { + listener.request = persist + startInForeground() + openHangInTick(0) + tickEvery66Ms(3) + val callsBeforeUnsubscribe = store.calls.toList() + + manager.unsubscribe(listener) + executor.runPending() + tickEvery66Ms(3) + + assertThat(store.calls).isEqualTo(callsBeforeUnsubscribe + "close") + } + + @Test + fun `persisting hang stops the store writes at maxRecordingTime`() { + listener.request = persist + startInForeground() + openHangInTick(0) + tickPastMaxRecordingTime() + val callsAtCut = store.calls.toList() + + tickEvery66Ms(3) + signal.report(HangSignal.State.IDLE, 0) + tickEvery66Ms(3) + + assertThat(store.calls).isEqualTo(callsAtCut) + assertThat(store.calls.count { it == "clear" }).isEqualTo(1) + } + + @Test + fun `hang without persist after a persisted one does not clear the store`() { + listener.request = persist + startInForeground() + openHangInTick(0) + tickEvery66Ms(3) + signal.report(HangSignal.State.IDLE, 0) + listener.request = record + store.calls.clear() + + openHangInTick(0) + tickEvery66Ms(15) + + assertThat(store.calls).isEmpty() + } + + @Test + fun `subscribers that need nothing cause no sample, no store call and no record`() { + listener.request = null + startInForeground() + openHangInTick(0) + tickEvery66Ms(15) + + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(listener.started).isEqualTo(1) + assertThat(collector.calls).isEmpty() + assertThat(store.calls).isEmpty() + assertThat(records).isEmpty() + } + + @Test + fun `a request to persist without a record does nothing`() { + listener.request = HangRecordingRequest(false, true) + startInForeground() + openHangInTick(0) + tickEvery66Ms(15) + + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(collector.calls).isEmpty() + assertThat(store.calls).isEmpty() + assertThat(records).isEmpty() + } + + @Test + fun `record goes only to the subscribers that record`() { + val notRecording = FakeListener(request = null) + manager.subscribe(notRecording) + startInForeground() + openHangInTick(300) + + signal.report(HangSignal.State.IDLE, 0) + + assertThat(recordedValues().single()).containsExactly("s1") + assertThat(notRecording.records).isEmpty() + assertThat(notRecording.started).isEqualTo(1) + } + + @Test + fun `record still goes to a subscriber that left during the hang`() { + val leaving = FakeListener() + manager.subscribe(leaving) + startInForeground() + openHangInTick(300) + + manager.unsubscribe(leaving) + executor.runPending() + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(records).hasSize(1) + assertThat(leaving.records).hasSize(1) + } + + @Test + fun `record still goes to a subscriber that left after the hang end and before the delivery`() { + val other = FakeListener() + manager.subscribe(other) + startInForeground() + openHangInTick(300) + signal.report(HangSignal.State.IDLE, 0) + + manager.unsubscribe(other) + executor.runPending() + sdkExecutor.runAll() + + assertThat(records).hasSize(1) + assertThat(other.records).hasSize(1) + } + + @Test + fun `no sample after idle`() { + startInForeground() + openHangInTick(300) + signal.report(HangSignal.State.IDLE, 0) + collector.calls.clear() + + executor.runTick() + + assertThat(collector.calls).isEmpty() + } + + @Test + fun `idle without an open hang 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 start a second record`() { + createRecorder(signalCount = 2) + val otherSignal = signals[1] + startInForeground() + openHangInTick(300) + advance(100) + + otherSignal.report(HangSignal.State.SUSPICIOUS, 0) + advance(100) + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(listener.started).isEqualTo(1) + assertThat(records.single().durationMs).isEqualTo(500) + } + + @Test + fun `signal factory gets the manager as metronome`() { + var metronome: Metronome? = null + val created = + HangManager( + options, + appStateProvider, + ticker, + epochClock, + DEFAULT_POLLING_INTERVAL_MS, + DEFAULT_MAX_RECORDING_TIME_MS, + MAX_SAMPLES, + { FakeScheduledExecutorService() }, + { + metronome = it + emptyList() + }, + emptyList(), + ) + + assertThat(metronome).isSameInstanceAs(created) + } + + @Test + fun `default executor factory runs the manager on a daemon thread`() { + val executor = HangManager.DEFAULT_EXECUTOR_FACTORY.create() + try { + val thread = executor.submit { Thread.currentThread() }.get(10, TimeUnit.SECONDS) + + assertThat(thread.name).isEqualTo("SentryHangManager") + assertThat(thread.isDaemon).isTrue() + } finally { + executor.shutdown() + } + } + + @Test + fun `after maxRecordingTime there is no sample and no record until idle`() { + startInForeground() + openHangInTick(0) + tickPastMaxRecordingTime() + val samplesAtMax = collector.calls.size + + tickEvery66Ms(3) + sdkExecutor.runAll() + + assertThat(collector.calls).hasSize(samplesAtMax) + assertThat(records).isEmpty() + } + + @Test + fun `signal that throws on start does not stop the tick for the other signals`() { + createRecorder(signalCount = 2) + signals[1].throwOnStart = true + + startInForeground() + + assertThat(executor.taskFailures).hasSize(1) + assertThat(signals[0].isStarted).isTrue() + assertThat(executor.activePeriodicTasks).hasSize(1) + } + + @Test + fun `after maxRecordingTime no hang starts until idle`() { + startInForeground() + openHangInTick(0) + advance(DEFAULT_MAX_RECORDING_TIME_MS) + executor.runTick() + listener.started = 0 + + signal.report(HangSignal.State.SUSPICIOUS, 0) + assertThat(listener.started).isEqualTo(0) + + signal.report(HangSignal.State.IDLE, 0) + signal.report(HangSignal.State.SUSPICIOUS, 0) + assertThat(listener.started).isEqualTo(1) + } + + @Test + fun `background ends the open hang and cancels tick`() { + startInForeground() + openHangInTick(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() + openHangInTick(300) + collector.calls.clear() + + signal.cancel() + executor.runTick() + sdkExecutor.runAll() + + assertThat(collector.calls).isEmpty() + assertThat(records).isEmpty() + } + + @Test + fun `signal change from another thread runs on the manager thread`() { + startInForeground() + + val thread = Thread { signal.report(HangSignal.State.SUSPICIOUS, 0) } + thread.start() + thread.join() + assertThat(listener.started).isEqualTo(0) + + executor.runPending() + assertThat(listener.started).isEqualTo(1) + } + + @Test + fun `signal duration from another thread is measured at the call`() { + startInForeground() + + val thread = Thread { signal.report(HangSignal.State.SUSPICIOUS, 300) } + thread.start() + thread.join() + advance(100) + executor.runPending() + signal.report(HangSignal.State.IDLE, 0) + sdkExecutor.runAll() + + assertThat(records.single().durationMs).isEqualTo(400) + } + + @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`() { + manager.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() + + manager.subscribe(listener) + manager.unsubscribe(listener) + executor.runPending() + + assertThat(signal.isStarted).isFalse() + assertThat(appStateProvider.listeners).isEmpty() + } + + @Test + fun `last unsubscribe stops signals and the tick and shuts down the executor`() { + val otherListener = FakeListener() + manager.subscribe(otherListener) + startInForeground() + + manager.unsubscribe(otherListener) + executor.runPending() + assertThat(signal.isStarted).isTrue() + assertThat(executor.isShutdown).isFalse() + + manager.unsubscribe(listener) + executor.runPending() + assertThat(signal.isStarted).isFalse() + assertThat(executor.activePeriodicTasks).isEmpty() + assertThat(executor.isShutdown).isTrue() + assertThat(appStateProvider.listeners).isEmpty() + } + + @Test + fun `subscribers share one app state listener`() { + manager.subscribe(listener) + manager.subscribe(FakeListener()) + executor.runPending() + + assertThat(appStateProvider.listeners).hasSize(1) + } + + @Test + fun `last unsubscribe drops the open hang without a record`() { + startInForeground() + openHangInTick(300) + + manager.unsubscribe(listener) + executor.runPending() + sdkExecutor.runAll() + + assertThat(records).isEmpty() + } + + @Test + fun `last unsubscribe closes signals and stores once on the manager thread`() { + startInForeground() + + manager.unsubscribe(listener) + assertThat(signal.closeCount).isEqualTo(0) + assertThat(store.calls).doesNotContain("close") + executor.runPending() + manager.unsubscribe(listener) + executor.runPending() + + assertThat(signal.closeCount).isEqualTo(1) + assertThat(store.calls).containsExactly("close") + } + + @Test + fun `subscribe after the last unsubscribe does nothing`() { + startInForeground() + manager.unsubscribe(listener) + executor.runPending() + + startInForeground() + + assertThat(executors).hasSize(1) + assertThat(signal.isStarted).isFalse() + assertThat(appStateProvider.listeners).isEmpty() + assertThat(executor.taskFailures).isEmpty() + } + + @Test + fun `subscribe queued behind the last unsubscribe does nothing`() { + val late = FakeListener() + startInForeground() + + manager.unsubscribe(listener) + manager.subscribe(late) + executor.runPending() + + assertThat(appStateProvider.listeners).isEmpty() + assertThat(signal.isStarted).isFalse() + assertThat(signal.closeCount).isEqualTo(1) + assertThat(executor.taskFailures).isEmpty() + } + + @Test + fun `signal that throws on stop leaves no second tick loop`() { + signal.throwOnStop = true + startInForeground() + openHangInTick(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 `exception in collector does not stop the tick loop`() { + startInForeground() + collector.throwOnSample = true + openHangInTick(300) + collector.throwOnSample = false + + executor.runTick() + + assertThat(collector.calls).hasSize(2) + verify(logger).log(eq(SentryLevel.ERROR), any(), any()) + } + + @Test + fun `store that fails to close is logged and the next stores are closed`() { + val secondStore = FakeStore() + store.throwOnClose = true + createRecorder( + collectors = listOf(setup(collector, store), setup(FakeCollector("t"), secondStore)), + ) + startInForeground() + + manager.unsubscribe(listener) + executor.runPending() + + assertThat(secondStore.calls).containsExactly("close") + verify(logger) + .log(eq(SentryLevel.WARNING), eq("Failed to close a hang sample store"), any()) + } + + @Test + fun `signal that throws on close does not skip closing the stores`() { + signal.throwOnClose = true + startInForeground() + + manager.unsubscribe(listener) + executor.runPending() + + assertThat(store.calls).containsExactly("close") + assertThat(executor.taskFailures).hasSize(1) + assertThat(executor.isShutdown).isTrue() + } + + @Test + fun `last unsubscribe stops ticks and later calls do nothing`() { + var ticks = 0 + manager.addTickListener { ticks++ } + startInForeground() + + manager.unsubscribe(listener) + executor.runPending() + executor.runTick() + assertThat(ticks).isEqualTo(0) + + manager.subscribe(listener) + manager.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(store.calls).containsExactly("close") + } + + @Test + fun `record dropped by a full sdk executor queue is logged`() { + options.executorService = NonOverridableNoOpSentryExecutorService() + startInForeground() + openHangInTick(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 `unsubscribe without subscription starts no thread`() { + manager.unsubscribe(listener) + + assertThat(executors).isEmpty() + assertThat(signal.closeCount).isEqualTo(0) + } + + 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 throwOnStart = false + var throwOnStop = false + var throwOnClose = false + + val isStarted: Boolean + get() = listener != null + + override fun start(listener: HangSignalListener) { + startCount++ + if (throwOnStart) { + throw IllegalStateException("start failed") + } + 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 FakeListener( + val records: MutableList = mutableListOf(), + var request: HangRecordingRequest? = HangRecordingRequest(true, false), + ) : HangRecordingListener { + var started = 0 + + override fun onHangStarted(): HangRecordingRequest? { + started++ + return request + } + + override fun onHangRecorded(record: HangRecord) { + records.add(record) + } + } + + /** + * Returns the values "s1", "s2", ..., counting every sample call, also those that return null. + */ + private class FakeCollector(private val prefix: String = "s") : HangDataCollector { + val calls = mutableListOf() + private var sampleCount = 0 + var returnNull = false + var throwOnSample = false + + override fun sample(): String? { + calls.add("sample") + sampleCount++ + if (throwOnSample) { + throw IllegalStateException("collector failed") + } + return if (returnNull) null else "$prefix$sampleCount" + } + } + + private class FakeStore : HangSampleStore { + val calls = mutableListOf() + var throwOnClear = false + var throwOnAdd = false + var throwOnClose = false + + override fun clear() { + calls.add("clear") + if (throwOnClear) { + throw IOException("clear failed") + } + } + + override fun add(sample: String) { + calls.add("add $sample") + if (throwOnAdd) { + throw IOException("add failed") + } + } + + override fun close() { + calls.add("close") + if (throwOnClose) { + throw IOException("close failed") + } + } + } + + private companion object { + const val MAX_SAMPLES = 120 + + /** + * Puts each value into the record as the method of a stack frame, so a test can read it back. + */ + val writer = + HangRecordWriter { value, record -> + record.addStackTrace(AnrStackTrace(0, arrayOf(StackTraceElement("Fake", value, null, 0)))) + } + } +} 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 00000000000..e325fb739af --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/hang/HangRecorderTest.kt @@ -0,0 +1,196 @@ +package io.sentry.android.core.hang + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel +import io.sentry.android.core.anr.AnrStackTrace +import java.io.IOException +import kotlin.test.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify + +class HangRecorderTest { + + private val logger = mock() + private val collector = FakeCollector() + private val store = FakeStore() + private val writer = + HangRecordWriter { value, record -> + record.addStackTrace(AnrStackTrace(0, arrayOf(StackTraceElement("Fake", value, null, 0)))) + } + + private fun start( + vararg listeners: FakeListener, + collectors: List> = listOf(HangCollectorSetup(collector, writer, store)), + ): HangRecorder? = HangRecorder.start(listeners.toList(), collectors, 100, 5_000, logger) + + private fun HangRecord.values() = stackTraces.map { it.stack.single().methodName } + + @Test + fun `no record without a listener that asks for one`() { + val recorder = start(FakeListener(null), FakeListener(HangRecordingRequest(false, true))) + + assertThat(recorder).isNull() + assertThat(store.calls).isEmpty() + } + + @Test + fun `asks every listener`() { + val first = FakeListener(HangRecordingRequest(true, false)) + val second = FakeListener(null) + + start(first, second) + + assertThat(first.started).isEqualTo(1) + assertThat(second.started).isEqualTo(1) + } + + @Test + fun `persist request clears the store and writes each sample`() { + val recorder = + start( + FakeListener(HangRecordingRequest(true, false)), + FakeListener(HangRecordingRequest(true, true)), + )!! + + recorder.sample(120) + recorder.sample(120) + + assertThat(store.calls).containsExactly("clear", "add s1", "add s2").inOrder() + } + + @Test + fun `record without persist request does not touch the store`() { + val recorder = start(FakeListener(HangRecordingRequest(true, false)))!! + + recorder.sample(120) + + assertThat(store.calls).isEmpty() + assertThat(recorder.end(200).values()).containsExactly("s1") + } + + @Test + fun `stops sampling after maxSamples ticks`() { + val recorder = start(FakeListener(HangRecordingRequest(true, false)))!! + + repeat(5) { recorder.sample(3) } + + assertThat(collector.sampleCount).isEqualTo(3) + assertThat(recorder.end(200).values()).containsExactly("s1", "s2", "s3").inOrder() + } + + @Test + fun `a tick without a value still counts against maxSamples`() { + val recorder = start(FakeListener(HangRecordingRequest(true, false)))!! + collector.returnNull = true + + recorder.sample(2) + recorder.sample(2) + collector.returnNull = false + recorder.sample(2) + + assertThat(collector.sampleCount).isEqualTo(2) + assertThat(recorder.end(200).values()).isEmpty() + } + + @Test + fun `store write failure stops persisting but not sampling`() { + val other = FakeCollector("o") + val recorder = + start( + FakeListener(HangRecordingRequest(true, true)), + collectors = + listOf( + HangCollectorSetup(collector, writer, store), + HangCollectorSetup(other, writer, null), + ), + )!! + store.throwOnAdd = true + + recorder.sample(120) + store.throwOnAdd = false + recorder.sample(120) + + assertThat(store.calls).containsExactly("clear", "add s1").inOrder() + assertThat(recorder.end(200).values()).containsExactly("s1", "o1", "s2", "o2").inOrder() + verify(logger, times(1)).log(eq(SentryLevel.WARNING), any(), any()) + } + + @Test + fun `store clear failure stops persisting`() { + store.throwOnClear = true + val recorder = start(FakeListener(HangRecordingRequest(true, true)))!! + + recorder.sample(120) + + assertThat(store.calls).containsExactly("clear") + verify(logger).log(eq(SentryLevel.WARNING), any(), any()) + } + + @Test + fun `listeners are the ones that asked for a record`() { + val recording1 = FakeListener(HangRecordingRequest(true, false)) + val recording2 = FakeListener(HangRecordingRequest(true, true)) + val notRecording = FakeListener(null) + val recorder = start(recording1, recording2, notRecording)!! + + assertThat(recorder.listeners).containsExactly(recording1, recording2).inOrder() + } + + @Test + fun `end builds the record with duration and start timestamp`() { + val recorder = start(FakeListener(HangRecordingRequest(true, false)))!! + + val record = recorder.end(8_100) + + assertThat(recorder.startTimeMs).isEqualTo(100) + assertThat(record.durationMs).isEqualTo(8_000) + assertThat(record.startTimestampMs).isEqualTo(5_000) + } + + private class FakeListener(private val request: HangRecordingRequest?) : HangRecordingListener { + var started = 0 + + override fun onHangStarted(): HangRecordingRequest? { + started++ + return request + } + + override fun onHangRecorded(record: HangRecord) = Unit + } + + private class FakeCollector(private val prefix: String = "s") : HangDataCollector { + var sampleCount = 0 + var returnNull = false + + override fun sample(): String? { + sampleCount++ + return if (returnNull) null else "$prefix$sampleCount" + } + } + + private class FakeStore : HangSampleStore { + val calls = mutableListOf() + var throwOnClear = false + var throwOnAdd = false + + override fun clear() { + calls.add("clear") + if (throwOnClear) { + throw IOException("clear failed") + } + } + + override fun add(sample: String) { + calls.add("add $sample") + if (throwOnAdd) { + throw IOException("add failed") + } + } + + override fun close() = Unit + } +}