diff --git a/sentry-android-navigation3/api/sentry-android-navigation3.api b/sentry-android-navigation3/api/sentry-android-navigation3.api index e69de29bb2..be90eab5cf 100644 --- a/sentry-android-navigation3/api/sentry-android-navigation3.api +++ b/sentry-android-navigation3/api/sentry-android-navigation3.api @@ -0,0 +1,8 @@ +public final class io/sentry/compose/navigation3/BuildConfig { + public static final field BUILD_TYPE Ljava/lang/String; + public static final field DEBUG Z + public static final field LIBRARY_PACKAGE_NAME Ljava/lang/String; + public static final field VERSION_NAME Ljava/lang/String; + public fun ()V +} + diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index 3e35211b22..973e071ad9 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -16,6 +16,8 @@ android { defaultConfig { minSdk = libs.versions.minSdk.get().toInt() + + buildConfigField("String", "VERSION_NAME", "\"${project.version}\"") } buildTypes { @@ -32,6 +34,10 @@ android { compilerOptions.apiVersion = KotlinVersion.KOTLIN_1_9 } + testOptions { + unitTests.isReturnDefaultValues = true + } + lint { warningsAsErrors = true checkDependencies = true @@ -40,6 +46,8 @@ android { checkReleaseBuilds = false } + buildFeatures { buildConfig = true } + androidComponents.beforeVariants { it.enable = !Config.Android.shouldSkipDebugVariant(it.buildType) } @@ -54,7 +62,6 @@ dependencies { testImplementation(libs.androidx.compose.runtime) testImplementation(libs.google.truth) - testImplementation(libs.kotlin.test.junit) testImplementation(libs.mockito.inline) testImplementation(libs.mockito.kotlin) } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt new file mode 100644 index 0000000000..cd1e09d14d --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt @@ -0,0 +1,480 @@ +package io.sentry.compose.navigation3 + +import io.sentry.Breadcrumb +import io.sentry.Hint +import io.sentry.IScope +import io.sentry.IScopes +import io.sentry.ITransaction +import io.sentry.PropagationContext +import io.sentry.SentryIntegrationPackageStorage +import io.sentry.SentryLevel.DEBUG +import io.sentry.SentryLevel.INFO +import io.sentry.SpanStatus +import io.sentry.TransactionContext +import io.sentry.TransactionOptions +import io.sentry.TypeCheckHint +import io.sentry.compose.navigation3.PreparedChange.BackStackHasNewTop +import io.sentry.compose.navigation3.PreparedChange.BackStackHasSameTop +import io.sentry.compose.navigation3.PreparedChange.BackStackIsEmpty +import io.sentry.compose.navigation3.RouteTranslator.RetentionPolicy +import io.sentry.protocol.App +import io.sentry.protocol.TransactionNameSource +import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion +import java.lang.ref.WeakReference + +private const val NAVIGATION_OP: String = "navigation" + +/** + * Observes the back stack managed by a single [SentryNavEffect] and records Sentry state as the + * back stack is updated. + * + * **Top of the stack == the current screen** + * + * This class treats top of the back stack as the current navigation destination and visible screen. + * It knows nothing about composite Scenes or multipane navigation scenarios. + * + * **Entry identity determines whether the top has changed** + * + * Referential equality (===), not structural equality, is used to determine whether the top of the + * incoming back stack has changed. That approach: + * + * - matches the typical Nav3 SnapshotStateList, where an entry instance has a stable identity for + * its lifetime in the stack; + * - mirrors [BackStackKey]'s policy; + * - doesn't depend on host-provided `equals()` / `hashCode()`, which can be absent, incorrect, or + * expensive; and + * - ensures we don't miss reporting a genuine top-of-stack change. + * + * **Thread safety** + * + * This class is ***not*** thread-safe. Clients should serialize calls to [onBackStackChanged] and + * [cleanup] (e.g., via invocation from an `*Effect` or another form of thread confinement). + */ +internal class BackStackObserver( + private val scopes: IScopes, + private val options: SentryNavOptions, + extractors: () -> RouteExtractors, +) { + + private val routeTranslator = RouteTranslator(extractors, scopes.options.logger) + + private val navTransaction = NavTransaction(scopes) + private val navContext = NavContext(scopes, options) + private val navScreen = NavScreen() + private val navBreadcrumbs = NavBreadcrumbs(scopes) + + // Safe because the host back stack retains the current top entry strongly between updates. + private var previousTopEntry: WeakReference? = null + private var previousTopRoute: Route? = null + + private val areNavigationTransactionsEnabled: Boolean + get() = scopes.options.isTracingEnabled && options.enableNavigationTransactions + + init { + addIntegrationToSdkVersion("ComposeNavigation3") + } + + internal companion object { + init { + SentryIntegrationPackageStorage.getInstance() + .addPackage("maven:io.sentry:sentry-android-navigation3", BuildConfig.VERSION_NAME) + } + } + + /** + * Updates Sentry nav data based on the provided [backStack]. + * + * **Data generated** + * + * By default, the following happens every time the top of the back stack changes: + * + * - a breadcrumb is emitted + * - a screen name is recorded + * - a new nav transaction is started and the old nav transaction, if any, is stopped. + * + * Names and other info for all of the above are derived from the new back stack top. + * + * By default, a record of the current back stack is recorded for every call, irrespective of + * whether the top changes. + * + * Defaults can be configured via the [SentryNavOptions] instance passed to this class's + * constructor. (Screen names can be disabled via [SentryOptions.setEnableScreenTracking].) + * + * **Not idempotent** + * + * This method is ***not*** idempotent. Callers should protect against repeat invocations with the + * same back stack to avoid emitting duplicate Sentry data. + */ + internal fun onBackStackChanged(backStack: List) { + val change = prepareChange(backStack) + scopes.configureScope { scope -> applyChange(scope, change) } + } + + internal fun cleanup() { + previousTopEntry = null + previousTopRoute = null + + scopes.configureScope { scope -> + navTransaction.stop(scope) + navScreen.clear(scope) + + if (options.captureBackStack) { + // This observer owns the nav context while it's in the composition, and cleanup removes + // it to avoid leaking stale back stack data after observation stops. If the host app + // replaces one observer with another, there may be a brief gap where events lack nav + // context. Apps should keep the observer at the nav root so cleanup only runs when the + // navigation session is ending, not during normal destination changes. + navContext.clear(scope) + } + } + } + + private fun prepareChange(backStack: List): PreparedChange { + val topEntry = backStack.lastOrNull() ?: return BackStackIsEmpty + val data = backStack.extractData() + + return if (topEntry === previousTopEntry?.get()) { + BackStackHasSameTop(data) + } else { + BackStackHasNewTop(previousTopRoute, data) + } + } + + private fun applyChange(scope: IScope, change: PreparedChange) { + when (change) { + is BackStackIsEmpty -> handleEmptyBackStack(scope) + + is BackStackHasNewTop -> handleNewTop(scope, change.previousTop, change.backStack) + is BackStackHasSameTop -> handleSameTop(scope, change.backStack) + } + } + + /** + * Extracts Sentry-compatible data from the receiver (i.e., a list of host app back stack entries) + * in the form of a [BackStackData]. + * + * Throws if the receiver is empty. + */ + private fun List.extractData(): BackStackData { + check(this.isNotEmpty()) + + val topEntry = this.last() + val shouldCaptureBackStack = options.captureBackStack && options.maxCapturedBackStackEntries > 0 + + val entriesToTranslate = + when { + shouldCaptureBackStack -> + // Reverse entries so they're displayed with the newest entry on top in the Sentry UI. + this.takeLast(options.maxCapturedBackStackEntries).asReversed() + + // We always need to translate the top entry for use with breadcrumbs, etc., even if we're + // not capturing the back stack. + else -> listOf(topEntry) + } + + val routes = + routeTranslator.translate( + backStackEntries = entriesToTranslate, + retentionPolicy = RetentionPolicy.KEEP_FIRST, + ) + + return BackStackData( + topEntry = topEntry, + topRoute = routes.first(), + capturedRoutes = if (shouldCaptureBackStack) routes else emptyList(), + ) + } + + private fun handleNewTop( + scope: IScope, + previousTop: Route?, + currentBackStack: BackStackData, + ) { + val currentTopRoute = currentBackStack.topRoute + + navContext.update(scope, currentBackStack.capturedRoutes) + + if (scopes.options.isEnableScreenTracking) { + navScreen.update(scope, currentTopRoute) + } + + if (options.enableNavigationBreadcrumbs) { + navBreadcrumbs.emit( + from = previousTop, + toEntry = currentBackStack.topEntry, + toRoute = currentBackStack.topRoute, + ) + } + + navTransaction.stop(scope) + + if (areNavigationTransactionsEnabled) { + navTransaction + .start( + scope, + currentTopRoute.name, + currentTopRoute.arguments, + ) + ?.let { transaction -> navContext.updateTransaction(transaction, scope, currentBackStack) } + } else { + // Rotate the propagation context. + scope.withPropagationContext { scope.setPropagationContext(PropagationContext()) } + } + + storeAsPreviousTop(currentBackStack.topEntry, currentBackStack.topRoute) + } + + private fun handleSameTop(scope: IScope, backStack: BackStackData) { + navContext.update(scope, backStack.capturedRoutes) + storeAsPreviousTop(backStack.topEntry, backStack.topRoute) + } + + private fun handleEmptyBackStack(scope: IScope) { + navTransaction.stop(scope) + navContext.clear(scope) + navScreen.clear(scope) + clearPreviousTop() + } + + private fun storeAsPreviousTop(topEntry: T, topRoute: Route) { + previousTopEntry = WeakReference(topEntry) + previousTopRoute = topRoute + } + + private fun clearPreviousTop() { + previousTopEntry = null + previousTopRoute = null + } +} + +/** + * A model for applying one back stack update. + * + * Lets us separate change preparation from its application so that the [IScopes.configureScope] + * callback in charge of application can use already-computed navigation state. Otherwise, any + * exceptions thrown during state computation would be swallowed by `configureScope`'s over-broad + * `catch` clause. + */ +private sealed interface PreparedChange { + + /** The incoming back stack is empty. */ + data object BackStackIsEmpty : PreparedChange + + /** + * The top of the back stack has changed, and one or more entries below it may have been updated. + */ + data class BackStackHasNewTop( + val previousTop: Route?, + val backStack: BackStackData, + ) : PreparedChange + + /** The top of the back stack is unchanged, but one or more entries below it have been updated. */ + data class BackStackHasSameTop(val backStack: BackStackData) : PreparedChange +} + +/** Info extracted from the host app's back stack in a form suitable for Sentry data. */ +private data class BackStackData( + val topEntry: T, + val topRoute: Route, + /** + * [Route]s representing the newest [SentryNavOption.maxCapturedBackStackEntries] entries from the + * host app's back stack. Possibly empty. + */ + val capturedRoutes: List, +) + +/** A helper class for managing nav transactions. */ +private class NavTransaction(private val scopes: IScopes) { + + private companion object { + private const val TRANSACTION_ORIGIN = "auto.navigation.nav3" + } + + private var activeNavTransaction: ITransaction? = null + + /** Starts an idle navigation transaction, or no-ops if another transaction is already active. */ + fun start( + scope: IScope, + name: String, + arguments: Map, + ): ITransaction? { + clearTransactionIfFinished(scope) + + if (scope.transaction != null) { + scopes.options.logger.log( + DEBUG, + "Nav3 transaction for route %s won't be created because another transaction is active.", + name, + ) + + return null + } + + val transactionOptions = + TransactionOptions().also { + it.isWaitForChildren = true + it.idleTimeout = scopes.options.idleTimeout + val deadlineTimeoutMillis = scopes.options.deadlineTimeout + it.deadlineTimeout = if (deadlineTimeoutMillis <= 0) null else deadlineTimeoutMillis + it.isTrimEnd = true + it.origin = TRANSACTION_ORIGIN + } + + val transaction = + scopes.startTransaction( + TransactionContext(name, TransactionNameSource.ROUTE, NAVIGATION_OP), + transactionOptions, + ) + + if (transaction.isNoOp) { + return null + } + + activeNavTransaction = transaction + + transaction.apply { + if (arguments.isNotEmpty()) { + setData("arguments", arguments) + } + } + + scope.withTransaction { tx -> + if (tx == null) { + scope.transaction = transaction + } + } + + return transaction + } + + /** Finishes and unsets the active navigation transaction, if one exists. */ + fun stop(scope: IScope) { + val transaction = activeNavTransaction ?: return + val status = transaction.status ?: SpanStatus.OK + transaction.finish(status) + + scope.withTransaction { tx -> + if (tx == transaction) { + scope.clearTransaction() + } + } + + activeNavTransaction = null + } + + /** Clears a stale finished transaction that's still bound to the default scope. */ + private fun clearTransactionIfFinished(scope: IScope) { + scope.withTransaction { tx -> + if (tx?.isFinished == true) { + scope.clearTransaction() + } + } + } +} + +/** A helper class for updating [nav context][NAVIGATION_CONTEXT_KEY]. */ +private class NavContext(private val scopes: IScopes, private val options: SentryNavOptions) { + + private companion object { + private const val BACKSTACK_KEY = "backstack" + private const val NAVIGATION_CONTEXT_KEY = "navigation" + } + + fun update(scope: IScope, backStackRoutes: List) { + if (backStackRoutes.isEmpty()) { + clear(scope) + return + } + + scope.setContexts(NAVIGATION_CONTEXT_KEY, backStackRoutes.toBackStackMap()) + } + + fun clear(scope: IScope) { + // We purposefully don't call IScope.removeContexts(), as it doesn't notify IScopeObserver and + // therefore doesn't write its updates to disk ¯\_ (ツ)_/¯. + scope.setContexts(NAVIGATION_CONTEXT_KEY, null as Any?) + } + + /** + * Updates the transaction with the provided navigation info. + * + * Needed because transactions inherit base scope context on a per-key basis unless transactions + * have their own values for those keys. In our case, we need to keep fresh back stack and route + * values in the base context for purposes of crash reporting. But those values will often advance + * past what's relevant to a given transaction. This method prevents misassociation by binding + * proper values to the transaction context instead. + */ + fun updateTransaction( + transaction: ITransaction, + scope: IScope, + backStack: BackStackData, + ) { + if (scopes.options.isEnableScreenTracking) { + val appContext = + transaction.contexts.app ?: io.sentry.protocol.Contexts(scope.contexts).app ?: App() + + appContext.viewNames = listOf(backStack.topRoute.name) + transaction.contexts.setApp(appContext) + } + + if (options.captureBackStack && backStack.capturedRoutes.isNotEmpty()) { + transaction.setContext(NAVIGATION_CONTEXT_KEY, backStack.capturedRoutes.toBackStackMap()) + } + } + + /** Builds the `{"backstack": [...]}` map bound under [NAVIGATION_CONTEXT_KEY]. */ + private fun List.toBackStackMap(): Map = mapOf(BACKSTACK_KEY to serialize()) +} + +/** A helper class for updating the tracked screen name. */ +private class NavScreen { + + private var lastScreenName: String? = null + + fun update(scope: IScope, currentRoute: Route) { + scope.screen = currentRoute.name + lastScreenName = currentRoute.name + } + + fun clear(scope: IScope) { + val routeName = lastScreenName ?: return + if (scope.screen == routeName) { + scope.screen = null + } + lastScreenName = null + } +} + +/** A helper class for generating nav breadcrumbs. */ +private class NavBreadcrumbs(private val scopes: IScopes) { + + fun emit( + from: Route?, + toEntry: T, + toRoute: Route, + ) { + val breadcrumb = + Breadcrumb().apply { + type = NAVIGATION_OP + category = NAVIGATION_OP + + from?.let { + data["from"] = it.name + if (it.arguments.isNotEmpty()) { + data["from_arguments"] = it.arguments + } + } + + data["to"] = toRoute.name + if (toRoute.arguments.isNotEmpty()) { + data["to_arguments"] = toRoute.arguments + } + + level = INFO + } + + val hint = Hint() + hint.set(TypeCheckHint.ANDROID_NAV3_DESTINATION, toEntry) + scopes.addBreadcrumb(breadcrumb, hint) + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/RouteExtractors.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/RouteExtractors.kt index 92dd05407f..02ee056cba 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/RouteExtractors.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/RouteExtractors.kt @@ -11,7 +11,7 @@ import org.jetbrains.annotations.ApiStatus * Values returned from [extract] are ***not*** scrubbed by the Sentry SDK before being sent to * Sentry. Only return names that are known to be safe or have been pre-scrubbed. * - * **Choosing stable route names** + * **Choosing appropriate route names** * * Implementations should return stable, low-cardinality names that don't depend on object identity, * argument values, or runtime class-name preservation. E.g., `Home`, `DetailScreen`, etc. @@ -19,6 +19,9 @@ import org.jetbrains.annotations.ApiStatus * In particular, avoid `::class.simpleName` in release builds, as R8 obfuscates class names and may * map them to different symbols across builds. * + * Extractors are invoked synchronously from [SentryNavEffect] on the same apply thread that runs + * the effect. Avoid non-performant extraction logic. + * * **Falls back to "/unknown"** * * If [extract] throws or returns a blank route name, Sentry records the destination as "/unknown". @@ -31,8 +34,8 @@ import org.jetbrains.annotations.ApiStatus * * **Using kotlinx.serialization** * - * If your back stack contains `@Serializable` route types, you may want to consider mapping each - * route type to a stable serializer name. For instance: + * If your back stack contains `@Serializable` route types, consider mapping each route type to a + * stable serializer name. For instance: * ```kotlin * val nameExtractor = RouteNameExtractor { route -> * when (route) { @@ -43,7 +46,7 @@ import org.jetbrains.annotations.ApiStatus * } * ``` * - * Doing so prevents route names from being obfuscated while leaving per-route arguments to + * Doing so gives each route type a stable, non-obfuscated name while leaving per-route arguments to * [RouteArgumentsExtractor]. */ @ApiStatus.Experimental @@ -60,13 +63,14 @@ internal fun interface RouteNameExtractor { * Values returned from [extract] are ***not*** scrubbed by the Sentry SDK before being sent to * Sentry. Only return arguments that are known to be safe or have been pre-scrubbed. * - * **Choosing performant route arguments** + * **Choosing appropriate route arguments** * * Return only a small subset of route data useful for diagnostics. Data should be stable enough to * inspect in Sentry. * - * For performance reasons, implementations should avoid large structures. Cyclic or deeply nested - * containers will be skipped. (See `RouteTranslator` for more details.) + * Extractors are invoked synchronously from [SentryNavEffect] on the same apply thread that runs + * the effect. For performance reasons, implementations should avoid large structures. Cyclic or + * deeply nested containers will be skipped. (See `RouteTranslator` for more details.) * * **Accepted value types** * @@ -96,9 +100,9 @@ internal fun interface RouteNameExtractor { * * **Using kotlinx.serialization** * - * Even if your back stack contains `@Serializable` route types, consider mapping each route type to - * a small set of diagnostic arguments to avoid the cost of serializing and returning the entire - * route object. For instance: + * If your back stack contains `@Serializable` route types, avoid returning the entire route object + * when it may be large, nested, or privacy-sensitive. Prefer a small set of diagnostic arguments + * instead. For instance: * ```kotlin * val argumentsExtractor = RouteArgumentsExtractor { route -> * when (route) { diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/RouteTranslator.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/RouteTranslator.kt index d687a7d890..7007a8162f 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/RouteTranslator.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/RouteTranslator.kt @@ -9,6 +9,14 @@ import org.jetbrains.annotations.TestOnly /** * Translates app-defined back stack entries into input-ordered [Route]s. * + * **Exception handling policy** + * + * Invocations of host-provided [extractors] and sanitization of host-defined arguments are + * protected by broad `try-catch` clauses, as each may throw arbitrary exceptions. We avoid failing + * fast on the assumption that navigation telemetry is supplemental from host apps' perspective, and + * that falling back to an `/unknown` route name or losing an argument map is preferable to + * crashing. + * * **Threading policy** * * This class performs work synchronously on the calling thread. Host-provided [extractors] are @@ -25,13 +33,13 @@ internal class RouteTranslator( } /** Translates the provided [backStackEntries] into [Route]s and returns them in input order. */ - fun translate(backStackEntries: List, policy: RetentionPolicy): List { + fun translate(backStackEntries: List, retentionPolicy: RetentionPolicy): List { val warningState = WarningState() val sanitizer = ArgumentSanitizer(logger, warningState) val routes = MutableList(backStackEntries.size) { null } val indicesInPolicyOrder = - when (policy) { + when (retentionPolicy) { RetentionPolicy.KEEP_FIRST -> backStackEntries.indices RetentionPolicy.KEEP_LAST -> backStackEntries.indices.reversed() } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt new file mode 100644 index 0000000000..add98ce3ef --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt @@ -0,0 +1,120 @@ +package io.sentry.compose.navigation3 + +import androidx.compose.runtime.Immutable +import org.jetbrains.annotations.ApiStatus + +// Keep the default low: every captured entry may require route-name extraction, argument +// extraction, and recursive argument sanitization when navigation changes are observed. +private const val DEFAULT_MAX_CAPTURED_BACK_STACK_ENTRIES = 10 + +/** + * Configuration info for a [SentryNavEffect]. + * + * Instances are immutable; create one with the SentryNavOptions DSL: + * ```kotlin + * val options = SentryNavOptions { + * captureBackStack = false + * maxCapturedBackStackEntries = 5 + * } + * ``` + */ +@ApiStatus.Experimental +@Immutable +internal class SentryNavOptions +private constructor( + val enableNavigationBreadcrumbs: Boolean, + val enableNavigationTransactions: Boolean, + val captureBackStack: Boolean, + val maxCapturedBackStackEntries: Int, +) { + + init { + require(maxCapturedBackStackEntries >= 0) { + "maxCapturedBackStackEntries must be non-negative, was $maxCapturedBackStackEntries" + } + } + + /** + * Mutable builder for [SentryNavOptions]. Prefer the [SentryNavOptions] DSL to using this + * directly. + * + * Lets us keep the resulting instance [Immutable] while preserving binary compatibility, should + * new properties be added in the future. + */ + class Builder { + + /** + * Whether navigation should produce Sentry breadcrumbs. If `true`, a new nav destination + * generates a breadcrumb like `from=/Home` and `to=/Profile`. + */ + var enableNavigationBreadcrumbs: Boolean = true + + /** + * Whether navigation should start a Sentry transaction. If `true`, navigating from `/Home` to + * `/Profile` starts a `/Profile` transaction and finishes the current `/Home` transaction. + */ + var enableNavigationTransactions: Boolean = true + + /** + * Whether Sentry should record back stack information for inclusion with crashes, errors, and + * other captured events. If `true`, a stack like `/Home -> /Profile` is recorded alongside the + * event, ordered with the current/top entry first. + */ + var captureBackStack: Boolean = true + + /** + * Maximum number of entries Sentry should record per captured back stack (starting with the + * most recent). Set to `0` to capture no back stack entries. + * + * Note: Sentry resolves and sanitizes up to [maxCapturedBackStackEntries] names + argument maps + * whenever your back stack changes. Keep name and argument extractors lightweight, and reduce + * the max captured count if extractor work is unusually expensive. + */ + var maxCapturedBackStackEntries: Int = DEFAULT_MAX_CAPTURED_BACK_STACK_ENTRIES + + fun build(): SentryNavOptions = + SentryNavOptions( + enableNavigationBreadcrumbs = enableNavigationBreadcrumbs, + enableNavigationTransactions = enableNavigationTransactions, + captureBackStack = captureBackStack, + maxCapturedBackStackEntries = maxCapturedBackStackEntries, + ) + } + + override fun equals(other: Any?): Boolean = + this === other || + (other is SentryNavOptions && + enableNavigationBreadcrumbs == other.enableNavigationBreadcrumbs && + enableNavigationTransactions == other.enableNavigationTransactions && + captureBackStack == other.captureBackStack && + maxCapturedBackStackEntries == other.maxCapturedBackStackEntries) + + override fun hashCode(): Int { + var result = enableNavigationBreadcrumbs.hashCode() + result = 31 * result + enableNavigationTransactions.hashCode() + result = 31 * result + captureBackStack.hashCode() + result = 31 * result + maxCapturedBackStackEntries + return result + } + + override fun toString(): String = + "SentryNavOptions(" + + "enableNavigationBreadcrumbs=$enableNavigationBreadcrumbs, " + + "enableNavigationTransactions=$enableNavigationTransactions, " + + "captureBackStack=$captureBackStack, " + + "maxCapturedBackStackEntries=$maxCapturedBackStackEntries)" +} + +/** + * Creates [SentryNavOptions]. Optionally configure it via [configure]. E.g.: + * ```kotlin + * val options = SentryNavOptions { + * captureBackStack = false + * maxCapturedBackStackEntries = 5 + * } + * ``` + */ +@ApiStatus.Experimental +internal fun SentryNavOptions( + configure: SentryNavOptions.Builder.() -> Unit = {} +): SentryNavOptions = SentryNavOptions.Builder().apply(configure).build() diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt new file mode 100644 index 0000000000..5c510ac9fd --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt @@ -0,0 +1,756 @@ +package io.sentry.compose.navigation3 + +import com.google.common.truth.Truth.assertThat +import io.sentry.Breadcrumb +import io.sentry.Hint +import io.sentry.ILogger +import io.sentry.IScope +import io.sentry.IScopes +import io.sentry.ISpan +import io.sentry.ITransaction +import io.sentry.NoOpTransaction +import io.sentry.Scope +import io.sentry.ScopeCallback +import io.sentry.SentryOptions +import io.sentry.SentryTracer +import io.sentry.TransactionContext +import io.sentry.TransactionOptions +import io.sentry.TypeCheckHint +import io.sentry.protocol.App +import io.sentry.protocol.TransactionNameSource +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class BackStackObserverTest { + + private data class HomeRoute(val id: String = "home") + + private data class ProfileRoute(val userId: String) + + private data class CartRoute(val productId: String) + + private data class SettingsRoute(val section: String) + + private data class ObserverConfig( + val enableNavigationBreadcrumbs: Boolean = true, + val enableNavigationTransactions: Boolean = true, + val captureBackStack: Boolean = true, + val maxCapturedBackStackEntries: Int = 10, + val enableScreenTracking: Boolean = true, + ) + + private class Fixture { + private val defaultNameExtractor = + RouteNameExtractor { entry -> entry::class.simpleName ?: "unknown" } + + val logger = mock() + val scope = Scope(createOptions(logger)) + val scopes = mock() + val breadcrumbs = mutableListOf() + val breadcrumbHints = mutableListOf() + val startedTransactions = mutableListOf() + + init { + whenever(scopes.options).thenReturn(scope.options) + whenever(scopes.getSpan()).thenAnswer { scope.span } + whenever(scopes.getTransaction()).thenAnswer { scope.transaction } + doAnswer { + (it.arguments[0] as ScopeCallback).run(scope) + null + } + .whenever(scopes) + .configureScope(any()) + doAnswer { + val transactionContext = it.arguments[0] as TransactionContext + val transactionOptions = it.arguments[1] as TransactionOptions + SentryTracer(transactionContext, scopes, transactionOptions) + .also(startedTransactions::add) + } + .whenever(scopes) + .startTransaction(any(), any()) + doAnswer { + breadcrumbs += it.arguments[0] as Breadcrumb + breadcrumbHints += it.arguments[1] as Hint + null + } + .whenever(scopes) + .addBreadcrumb(any(), any()) + } + + fun getSut( + config: ObserverConfig = ObserverConfig(), + nameExtractor: RouteNameExtractor = defaultNameExtractor, + argumentsExtractor: RouteArgumentsExtractor? = null, + ): BackStackObserver { + scope.options.isEnableScreenTracking = config.enableScreenTracking + + return BackStackObserver( + scopes = scopes, + options = + SentryNavOptions { + enableNavigationBreadcrumbs = config.enableNavigationBreadcrumbs + enableNavigationTransactions = config.enableNavigationTransactions + captureBackStack = config.captureBackStack + maxCapturedBackStackEntries = config.maxCapturedBackStackEntries + }, + extractors = { RouteExtractors(nameExtractor, argumentsExtractor) }, + ) + } + + private companion object { + fun createOptions(logger: ILogger): SentryOptions = + SentryOptions().apply { + dsn = "http://key@localhost/proj" + setTracesSampleRate(1.0) + isEnableScreenTracking = true + isDebug = true + setLogger(logger) + idleTimeout = null + deadlineTimeout = 0 + } + } + } + + @Test + fun `onBackStackChanged emits a breadcrumb for the top back stack entry when breadcrumbs are enabled`() { + val fixture = Fixture() + val sut = + fixture.getSut( + config = ObserverConfig(enableNavigationBreadcrumbs = true), + argumentsExtractor = + RouteArgumentsExtractor { entry -> + when (entry) { + is HomeRoute -> mapOf("tab" to entry.id) + is ProfileRoute -> mapOf("userId" to entry.userId) + else -> emptyMap() + } + }, + ) + val home = HomeRoute() + val profile = ProfileRoute("123") + + sut.onBackStackChanged(listOf(home)) + sut.onBackStackChanged(listOf(home, profile)) + + val breadcrumb = fixture.breadcrumbs.last() + assertThat(breadcrumb.type).isEqualTo("navigation") + assertThat(breadcrumb.category).isEqualTo("navigation") + assertThat(breadcrumb.data) + .containsExactly( + "from", + "/HomeRoute", + "from_arguments", + mapOf("tab" to "home"), + "to", + "/ProfileRoute", + "to_arguments", + mapOf("userId" to "123"), + ) + assertThat(fixture.breadcrumbHints.last().get(TypeCheckHint.ANDROID_NAV3_DESTINATION)) + .isSameInstanceAs(profile) + } + + @Test + fun `onBackStackChanged reuses the previous top snapshot for breadcrumb from payload`() { + val fixture = Fixture() + val previousProfile = ProfileRoute("123") + val replacementProfile = ProfileRoute("123") + var profileName = "profile" + var profileArguments = mapOf("userId" to "123") + val sut = + fixture.getSut( + nameExtractor = + RouteNameExtractor { entry -> + when (entry) { + is HomeRoute -> "home" + is ProfileRoute -> profileName + is SettingsRoute -> "settings" + else -> error("unknown route: $entry") + } + }, + argumentsExtractor = + RouteArgumentsExtractor { entry -> + when (entry) { + is HomeRoute -> mapOf("tab" to entry.id) + is ProfileRoute -> profileArguments + is SettingsRoute -> mapOf("section" to entry.section) + else -> emptyMap() + } + }, + ) + + sut.onBackStackChanged(listOf(HomeRoute(), previousProfile)) + profileName = "mutated-profile" + profileArguments = mapOf("userId" to "999") + + sut.onBackStackChanged(listOf(HomeRoute(), replacementProfile, SettingsRoute("privacy"))) + + assertThat(fixture.breadcrumbs.last().data) + .containsExactly( + "from", + "/profile", + "from_arguments", + mapOf("userId" to "123"), + "to", + "/settings", + "to_arguments", + mapOf("section" to "privacy"), + ) + } + + @Test + fun `onBackStackChanged does not emit a breadcrumb when breadcrumbs are disabled`() { + val fixture = Fixture() + val sut = fixture.getSut(config = ObserverConfig(enableNavigationBreadcrumbs = false)) + + sut.onBackStackChanged(listOf(HomeRoute())) + + assertThat(fixture.breadcrumbs).isEmpty() + } + + @Test + fun `onBackStackChanged emits a screen name for the top back stack entry when screen tracking is enabled`() { + val fixture = Fixture() + val sut = fixture.getSut(config = ObserverConfig(enableScreenTracking = true)) + + sut.onBackStackChanged(listOf(HomeRoute(), ProfileRoute("123"))) + + assertThat(fixture.scope.screen).isEqualTo("/ProfileRoute") + assertThat(fixture.scope.contexts.app?.viewNames).isEqualTo(listOf("/ProfileRoute")) + } + + @Test + fun `onBackStackChanged does not emit a screen name when screen tracking is disabled`() { + val fixture = Fixture() + val sut = fixture.getSut(config = ObserverConfig(enableScreenTracking = false)) + + sut.onBackStackChanged(listOf(HomeRoute())) + + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.contexts.app?.viewNames).isNull() + assertThat(fixture.startedTransactions.single().contexts.app?.viewNames).isNull() + } + + @Test + fun `onBackStackChanged emits a copy of the back stack up to max captured entries when enabled`() { + val fixture = Fixture() + val sut = + fixture.getSut( + config = ObserverConfig(captureBackStack = true, maxCapturedBackStackEntries = 2) + ) + + sut.onBackStackChanged(listOf(HomeRoute(), ProfileRoute("123"), SettingsRoute("privacy"))) + + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo(listOf(mapOf("route" to "/SettingsRoute"), mapOf("route" to "/ProfileRoute"))) + } + + @Test + fun `onBackStackChanged preserves top entry arguments when lower entries exhaust the shared budget`() { + val fixture = Fixture() + val sut = + fixture.getSut( + config = ObserverConfig(captureBackStack = true), + argumentsExtractor = + RouteArgumentsExtractor { entry -> + when (entry) { + is HomeRoute -> mapOf("values" to List(999) { it }) + is ProfileRoute -> mapOf("userId" to entry.userId) + else -> emptyMap() + } + }, + ) + + sut.onBackStackChanged(listOf(HomeRoute(), ProfileRoute("123"))) + + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("route" to "/ProfileRoute", "args" to mapOf("userId" to "123")), + mapOf("route" to "/HomeRoute"), + ) + ) + assertThat(fixture.startedTransactions.single().getData("arguments")) + .isEqualTo(mapOf("userId" to "123")) + } + + @Test + fun `onBackStackChanged emits an updated copy of the back stack even when the top entry is unchanged`() { + val fixture = Fixture() + val sut = fixture.getSut(config = ObserverConfig(captureBackStack = true)) + val home = HomeRoute() + val profile = ProfileRoute("123") + + sut.onBackStackChanged(listOf(home, profile)) + sut.onBackStackChanged(listOf(home, SettingsRoute("privacy"), profile)) + + assertThat(fixture.breadcrumbs).hasSize(1) + assertThat(fixture.startedTransactions).hasSize(1) + assertThat(fixture.scope.screen).isEqualTo("/ProfileRoute") + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("route" to "/ProfileRoute"), + mapOf("route" to "/SettingsRoute"), + mapOf("route" to "/HomeRoute"), + ) + ) + } + + @Test + fun `onBackStackChanged emits new top-entry data when the top entry is replaced by an equal new instance`() { + val fixture = Fixture() + val sut = fixture.getSut(config = ObserverConfig(captureBackStack = true)) + val home = HomeRoute() + val firstProfile = ProfileRoute("123") + val replacementProfile = ProfileRoute("123") + + sut.onBackStackChanged(listOf(home, firstProfile)) + sut.onBackStackChanged(listOf(home, replacementProfile)) + + assertThat(fixture.breadcrumbs).hasSize(2) + assertThat(fixture.breadcrumbs.last().data["from"]).isEqualTo("/ProfileRoute") + assertThat(fixture.breadcrumbs.last().data["to"]).isEqualTo("/ProfileRoute") + assertThat(fixture.breadcrumbHints.last().get(TypeCheckHint.ANDROID_NAV3_DESTINATION)) + .isSameInstanceAs(replacementProfile) + assertThat(fixture.startedTransactions).hasSize(2) + assertThat(fixture.startedTransactions.last().name).isEqualTo("/ProfileRoute") + assertThat(fixture.startedTransactions.first().isFinished).isTrue() + assertThat(fixture.scope.screen).isEqualTo("/ProfileRoute") + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo(listOf(mapOf("route" to "/ProfileRoute"), mapOf("route" to "/HomeRoute"))) + } + + @Test + fun `onBackStackChanged does not emit a back stack copy when max captured entries is 0`() { + val fixture = Fixture() + val sut = + fixture.getSut( + config = ObserverConfig(captureBackStack = true, maxCapturedBackStackEntries = 0) + ) + fixture.scope.setContexts( + "navigation", + mapOf("backstack" to listOf(mapOf("route" to "/Stale"))), + ) + + sut.onBackStackChanged(listOf(HomeRoute())) + + // Doesn't emit a back stack... + assertThat(fixture.scope.contexts.containsKey("navigation")).isFalse() + + // ...but continues to emit all other Sentry data. + assertThat(fixture.breadcrumbs.single().data["to"]).isEqualTo("/HomeRoute") + assertThat(fixture.startedTransactions).hasSize(1) + assertThat(fixture.startedTransactions.single().name).isEqualTo("/HomeRoute") + assertThat(fixture.scope.screen).isEqualTo("/HomeRoute") + } + + @Test + fun `onBackStackChanged does not emit a back stack copy when back stack capture is disabled`() { + val fixture = Fixture() + val sut = fixture.getSut(config = ObserverConfig(captureBackStack = false)) + fixture.scope.setContexts( + "navigation", + mapOf("backstack" to listOf(mapOf("route" to "/Stale"))), + ) + + sut.onBackStackChanged(listOf(HomeRoute())) + + // Doesn't emit a back stack... + assertThat(fixture.scope.contexts.containsKey("navigation")).isFalse() + + // ...but continues to emit all other Sentry data. + assertThat(fixture.breadcrumbs.single().data["to"]).isEqualTo("/HomeRoute") + assertThat(fixture.startedTransactions).hasSize(1) + assertThat(fixture.startedTransactions.single().name).isEqualTo("/HomeRoute") + assertThat(fixture.scope.screen).isEqualTo("/HomeRoute") + } + + // Like `onBackStackChanged does not emit a back stack copy when back stack capture is disabled`, + // but here we actually verify that no unnecessary work is done. + @Test + fun `onBackStackChanged skips lower back stack resolution when back stack capture is disabled`() { + val fixture = Fixture() + val home = HomeRoute() + val profile = ProfileRoute("123") + val nameCalls = mutableMapOf() + val argumentCalls = mutableMapOf() + val sut = + fixture.getSut( + config = ObserverConfig(captureBackStack = false), + nameExtractor = { entry -> + nameCalls[entry] = (nameCalls[entry] ?: 0) + 1 + entry::class.simpleName ?: "unknown" + }, + argumentsExtractor = { entry -> + argumentCalls[entry] = (argumentCalls[entry] ?: 0) + 1 + when (entry) { + is HomeRoute -> mapOf("tab" to entry.id) + is ProfileRoute -> mapOf("userId" to entry.userId) + else -> emptyMap() + } + }, + ) + + sut.onBackStackChanged(listOf(home, profile)) + + assertThat(nameCalls[profile]).isEqualTo(1) + assertThat(argumentCalls[profile]).isEqualTo(1) + assertThat(nameCalls).doesNotContainKey(home) + assertThat(argumentCalls).doesNotContainKey(home) + } + + @Test + fun `onBackStackChanged resolves top entry arguments once per update`() { + val fixture = Fixture() + val home = HomeRoute() + val profile = ProfileRoute("123") + val argumentCalls = mutableMapOf() + val sut = + fixture.getSut( + argumentsExtractor = + RouteArgumentsExtractor { entry -> + argumentCalls[entry] = (argumentCalls[entry] ?: 0) + 1 + when (entry) { + is HomeRoute -> mapOf("tab" to entry.id) + is ProfileRoute -> mapOf("userId" to entry.userId) + else -> emptyMap() + } + } + ) + + sut.onBackStackChanged(listOf(home, profile)) + + assertThat(argumentCalls[profile]).isEqualTo(1) + assertThat(argumentCalls[home]).isEqualTo(1) + } + + @Test + fun `onBackStackChanged creates a nav transaction when enabled and no ambient transaction is active`() { + val fixture = Fixture() + val sut = + fixture.getSut( + config = ObserverConfig(enableNavigationTransactions = true), + argumentsExtractor = + RouteArgumentsExtractor { entry -> + when (entry) { + is ProfileRoute -> mapOf("userId" to entry.userId) + else -> emptyMap() + } + }, + ) + + sut.onBackStackChanged(listOf(HomeRoute(), ProfileRoute("123"))) + + val transaction = fixture.startedTransactions.single() + + assertThat(transaction.name).isEqualTo("/ProfileRoute") + assertThat(transaction.transactionNameSource).isEqualTo(TransactionNameSource.ROUTE) + assertThat(transaction.operation).isEqualTo("navigation") + assertThat(transaction.spanContext.origin).isEqualTo("auto.navigation.nav3") + assertThat(transaction.getData("arguments")).isEqualTo(mapOf("userId" to "123")) + assertThat(transaction.contexts.app?.viewNames).isEqualTo(listOf("/ProfileRoute")) + assertThat(transaction.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("route" to "/ProfileRoute", "args" to mapOf("userId" to "123")), + mapOf("route" to "/HomeRoute"), + ) + ) + assertThat(fixture.scope.transaction).isSameInstanceAs(transaction) + } + + // Regression test: Setting origin after starting the transaction breaks the ignoredSpanOrigins + // check (see SentryOptions.getIgnoredSpanOrigins()). + @Test + fun `onBackStackChanged sets nav transaction origin before starting the transaction`() { + val fixture = Fixture() + val transactionOptionsCaptor = argumentCaptor() + whenever( + fixture.scopes.startTransaction( + any(), + transactionOptionsCaptor.capture(), + ) + ) + .thenAnswer { + val transactionContext = it.arguments[0] as TransactionContext + val transactionOptions = it.arguments[1] as TransactionOptions + SentryTracer(transactionContext, fixture.scopes, transactionOptions) + .also(fixture.startedTransactions::add) + } + val sut = fixture.getSut(config = ObserverConfig(enableNavigationTransactions = true)) + + sut.onBackStackChanged(listOf(HomeRoute())) + + assertThat(transactionOptionsCaptor.firstValue.origin).isEqualTo("auto.navigation.nav3") + } + + @Test + fun `onBackStackChanged preserves scope app fields on the nav transaction`() { + val fixture = Fixture() + val scopeApp = + App().apply { + appName = "Demo App" + appIdentifier = "io.sentry.demo" + } + fixture.scope.contexts.setApp(scopeApp) + val sut = fixture.getSut(config = ObserverConfig(enableScreenTracking = true)) + + sut.onBackStackChanged(listOf(HomeRoute(), ProfileRoute("123"))) + + val transactionApp = fixture.startedTransactions.single().contexts.app + assertThat(transactionApp).isNotNull() + assertThat(transactionApp).isNotSameInstanceAs(scopeApp) + assertThat(transactionApp?.appName).isEqualTo("Demo App") + assertThat(transactionApp?.appIdentifier).isEqualTo("io.sentry.demo") + assertThat(transactionApp?.viewNames).isEqualTo(listOf("/ProfileRoute")) + } + + @Test + fun `onBackStackChanged creates a nav transaction when only an ambient span is active`() { + val fixture = Fixture() + val sut = fixture.getSut(config = ObserverConfig(enableNavigationTransactions = true)) + + fixture.scope.setActiveSpan(mock()) + sut.onBackStackChanged(listOf(HomeRoute())) + + assertThat(fixture.startedTransactions).hasSize(1) + assertThat(fixture.startedTransactions.single().name).isEqualTo("/HomeRoute") + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransactions.single()) + assertThat(fixture.scope.screen).isEqualTo("/HomeRoute") + } + + @Test + fun `onBackStackChanged does not create a nav transaction when an ambient transaction is active`() { + val fixture = Fixture() + val ambientTransaction = + SentryTracer( + TransactionContext("ambient", TransactionNameSource.CUSTOM, "ui.load"), + fixture.scopes, + ) + ambientTransaction.startChild("db.query") + fixture.scope.transaction = ambientTransaction + val sut = fixture.getSut(config = ObserverConfig(enableNavigationTransactions = true)) + + sut.onBackStackChanged(listOf(HomeRoute())) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isSameInstanceAs(ambientTransaction) + assertThat(fixture.scope.screen).isEqualTo("/HomeRoute") + } + + @Test + fun `onBackStackChanged does not create a nav transaction when navigation transactions are disabled`() { + val fixture = Fixture() + val sut = fixture.getSut(config = ObserverConfig(enableNavigationTransactions = false)) + val originalPropagationContext = fixture.scope.propagationContext + + sut.onBackStackChanged(listOf(HomeRoute())) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isNull() + assertThat(fixture.scope.propagationContext).isNotSameInstanceAs(originalPropagationContext) + } + + @Test + fun `onBackStackChanged clears a finished stale scope transaction before starting a fresh nav transaction`() { + val fixture = Fixture() + val staleTransaction = + SentryTracer( + TransactionContext("stale", TransactionNameSource.CUSTOM, "ui.load"), + fixture.scopes, + ) + staleTransaction.finish() + fixture.scope.transaction = staleTransaction + val sut = fixture.getSut(config = ObserverConfig(enableNavigationTransactions = true)) + + sut.onBackStackChanged(listOf(HomeRoute())) + + assertThat(fixture.startedTransactions).hasSize(1) + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransactions.single()) + } + + @Test + fun `onBackStackChanged does not bind a no-op nav transaction to the scope`() { + val fixture = Fixture() + whenever(fixture.scopes.startTransaction(any(), any())) + .thenReturn(NoOpTransaction.getInstance()) + val sut = fixture.getSut(config = ObserverConfig(enableNavigationTransactions = true)) + + sut.onBackStackChanged(listOf(HomeRoute())) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isNull() + assertThat(fixture.scope.screen).isEqualTo("/HomeRoute") + } + + @Test + fun `onBackStackChanged clears tracked scope state when the back stack becomes empty`() { + val fixture = Fixture() + val sut = fixture.getSut() + + sut.onBackStackChanged(listOf(HomeRoute())) + val transaction = fixture.startedTransactions.single() + + sut.onBackStackChanged(emptyList()) + + assertThat(transaction.isFinished).isTrue() + assertThat(fixture.scope.transaction).isNull() + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.contexts.app?.viewNames).isNull() + assertThat(fixture.scope.contexts.containsKey("navigation")).isFalse() + assertThat(fixture.breadcrumbs).hasSize(1) + } + + @Test + @Suppress("LongMethod") + fun `onBackStackChanged records unknown route names when destination route name can't be extracted`() { + val fixture = Fixture() + val home = HomeRoute() + val profile = ProfileRoute(userId = "123") + val cart = CartRoute(productId = "987") + val settings = SettingsRoute(section = "privacy") + val sut = + fixture.getSut( + nameExtractor = + RouteNameExtractor { entry -> + when (entry) { + is HomeRoute -> "home" + is ProfileRoute -> " " + is CartRoute -> error("throwing in order to simulate a buggy name extractor") + is SettingsRoute -> "settings" + else -> error("unknown route: $entry") + } + } + ) + + // Navigate to the home screen and verify that a transaction has started and related Sentry data + // have been generated (i.e., screen name, breadcrumb, and updated back stack context), as the + // host app's RouteNameExtractor returned a valid route name for the home screen entry. + sut.onBackStackChanged(listOf(home)) + val transaction = fixture.startedTransactions.single() + assertThat(transaction.isFinished).isFalse() + assertThat(fixture.scope.transaction).isNotNull() + assertThat(fixture.scope.screen).isEqualTo("/home") + assertThat(fixture.scope.contexts.app?.viewNames).isEqualTo(listOf("/home")) + assertThat(fixture.breadcrumbs).hasSize(1) + assertThat(fixture.scope.navigationBackStack()).isEqualTo(listOf(mapOf("route" to "/home"))) + + // Navigate to the profile screen and verify the invalid route name is recorded as /unknown so + // the transition history remains intact. + sut.onBackStackChanged(listOf(home, profile)) + assertThat(transaction.isFinished).isTrue() + assertThat(fixture.startedTransactions).hasSize(2) + val profileTransaction = fixture.startedTransactions.last() + assertThat(profileTransaction.isFinished).isFalse() + assertThat(profileTransaction.name).isEqualTo(RouteTranslator.UNKNOWN_ROUTE_NAME) + assertThat(fixture.scope.transaction).isSameInstanceAs(profileTransaction) + assertThat(fixture.scope.screen).isEqualTo(RouteTranslator.UNKNOWN_ROUTE_NAME) + assertThat(fixture.scope.contexts.app?.viewNames) + .isEqualTo(listOf(RouteTranslator.UNKNOWN_ROUTE_NAME)) + assertThat(fixture.breadcrumbs).hasSize(2) + assertThat(fixture.breadcrumbs.last().data) + .containsExactly("from", "/home", "to", RouteTranslator.UNKNOWN_ROUTE_NAME) + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("route" to RouteTranslator.UNKNOWN_ROUTE_NAME), + mapOf("route" to "/home"), + ) + ) + + // Navigate to the cart screen and verify the later failure is also recorded as /unknown rather + // than collapsing the route history. + sut.onBackStackChanged(listOf(home, profile, cart)) + assertThat(profileTransaction.isFinished).isTrue() + assertThat(fixture.startedTransactions).hasSize(3) + val cartTransaction = fixture.startedTransactions.last() + assertThat(cartTransaction.isFinished).isFalse() + assertThat(cartTransaction.name).isEqualTo(RouteTranslator.UNKNOWN_ROUTE_NAME) + assertThat(fixture.scope.transaction).isSameInstanceAs(cartTransaction) + assertThat(fixture.scope.screen).isEqualTo(RouteTranslator.UNKNOWN_ROUTE_NAME) + assertThat(fixture.scope.contexts.app?.viewNames) + .isEqualTo(listOf(RouteTranslator.UNKNOWN_ROUTE_NAME)) + assertThat(fixture.breadcrumbs).hasSize(3) + assertThat(fixture.breadcrumbs.last().data) + .containsExactly( + "from", + RouteTranslator.UNKNOWN_ROUTE_NAME, + "to", + RouteTranslator.UNKNOWN_ROUTE_NAME, + ) + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("route" to RouteTranslator.UNKNOWN_ROUTE_NAME), + mapOf("route" to RouteTranslator.UNKNOWN_ROUTE_NAME), + mapOf("route" to "/home"), + ) + ) + + // Navigate to the settings screen and verify a new /settings transaction is started and Sentry + // data are generated again, as we received a valid route name. + sut.onBackStackChanged(listOf(home, profile, cart, settings)) + + assertThat(cartTransaction.isFinished).isTrue() + assertThat(fixture.startedTransactions).hasSize(4) + val settingsTransaction = fixture.startedTransactions.last() + assertThat(settingsTransaction.isFinished).isFalse() + assertThat(settingsTransaction.name).isEqualTo("/settings") + assertThat(fixture.scope.transaction).isSameInstanceAs(settingsTransaction) + assertThat(fixture.scope.screen).isEqualTo("/settings") + assertThat(fixture.scope.contexts.app?.viewNames).isEqualTo(listOf("/settings")) + assertThat(fixture.breadcrumbs).hasSize(4) + assertThat(fixture.breadcrumbs.last().data) + .containsExactly("from", RouteTranslator.UNKNOWN_ROUTE_NAME, "to", "/settings") + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("route" to "/settings"), + mapOf("route" to RouteTranslator.UNKNOWN_ROUTE_NAME), + mapOf("route" to RouteTranslator.UNKNOWN_ROUTE_NAME), + mapOf("route" to "/home"), + ) + ) + } + + @Test + fun `cleanup clears observer owned tracked state`() { + val fixture = Fixture() + val sut = fixture.getSut() + + sut.onBackStackChanged(listOf(HomeRoute())) + val transaction = fixture.startedTransactions.single() + + sut.cleanup() + + assertThat(transaction.isFinished).isTrue() + assertThat(fixture.scope.transaction).isNull() + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.contexts.app?.viewNames).isNull() + assertThat(fixture.scope.contexts.containsKey("navigation")).isFalse() + } + + private fun IScope.navigationBackStack(): List>? { + val navigationContext = contexts[NAVIGATION_CONTEXT_KEY] as? Map<*, *> ?: return null + + @Suppress("UNCHECKED_CAST") + return navigationContext[BACKSTACK_KEY] as? List> + } + + private fun ITransaction.navigationBackStack(): List>? { + val navigationContext = contexts[NAVIGATION_CONTEXT_KEY] as? Map<*, *> ?: return null + + @Suppress("UNCHECKED_CAST") + return navigationContext[BACKSTACK_KEY] as? List> + } + + private companion object { + const val NAVIGATION_CONTEXT_KEY = "navigation" + const val BACKSTACK_KEY = "backstack" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/RouteExtractorsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/RouteExtractorsTest.kt index f97e5241ac..fd0d7ff6e9 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/RouteExtractorsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/RouteExtractorsTest.kt @@ -3,7 +3,7 @@ package io.sentry.compose.navigation3 import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat -import kotlin.test.Test +import org.junit.Test class RouteExtractorsTest { diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/RouteTranslatorTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/RouteTranslatorTest.kt index ca2f8db318..b6301bce18 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/RouteTranslatorTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/RouteTranslatorTest.kt @@ -7,7 +7,7 @@ import io.sentry.compose.navigation3.RouteTranslator.ArgumentSanitizer import io.sentry.compose.navigation3.RouteTranslator.RetentionPolicy import io.sentry.compose.navigation3.RouteTranslator.WarningState import java.util.AbstractCollection -import kotlin.test.Test +import org.junit.Test import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.eq import org.mockito.kotlin.mock diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt new file mode 100644 index 0000000000..742a7c0ed6 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt @@ -0,0 +1,134 @@ +package io.sentry.compose.navigation3 + +import com.google.common.truth.Truth.assertThat +import java.lang.reflect.Modifier +import org.junit.Assert.assertThrows +import org.junit.Test + +class SentryNavOptionsTest { + + @Test + fun `accepts positive max captured backstack entries`() { + val options = SentryNavOptions { maxCapturedBackStackEntries = 1 } + + assertThat(options.maxCapturedBackStackEntries).isEqualTo(1) + } + + @Test + fun `accepts zero max captured backstack entries`() { + val options = SentryNavOptions { maxCapturedBackStackEntries = 0 } + + assertThat(options.maxCapturedBackStackEntries).isEqualTo(0) + } + + @Test + fun `rejects negative max captured backstack entries`() { + val exception = + assertThrows(IllegalArgumentException::class.java) { + SentryNavOptions { maxCapturedBackStackEntries = -1 } + } + + assertThat(exception) + .hasMessageThat() + .isEqualTo("maxCapturedBackStackEntries must be non-negative, was -1") + } + + @Test + fun `equal instances share the same hash code`() { + val first = SentryNavOptions() + val second = SentryNavOptions() + + assertThat(first).isEqualTo(second) + assertThat(first.hashCode()).isEqualTo(second.hashCode()) + } + + @Test + fun `equals and hash code include every property`() { + val base = SentryNavOptions() + val instanceFields = + SentryNavOptions::class + .java + .declaredFields + .filterNot { Modifier.isStatic(it.modifiers) } + .map { it.name } + + assertThat(propertyMutators.keys).containsExactlyElementsIn(instanceFields) + + propertyMutators.forEach { (propertyName, mutate) -> + val changed = mutate(base) + + assertThat(changed).isNotEqualTo(base) + assertThat(changed.hashCode()).isNotEqualTo(base.hashCode()) + assertThat(propertyName).isIn(instanceFields) + } + } + + @Test + fun `toString includes every property`() { + val options = SentryNavOptions() + val instanceFields = + SentryNavOptions::class + .java + .declaredFields + .filterNot { Modifier.isStatic(it.modifiers) } + .associate { field -> + field.isAccessible = true + field.name to field.get(options) + } + + instanceFields.forEach { (name, value) -> + assertThat(options.toString()).contains("$name=$value") + } + } + + @Test + fun `toString changes when any property changes`() { + val base = SentryNavOptions() + + propertyMutators.forEach { (_, mutate) -> + assertThat(mutate(base).toString()).isNotEqualTo(base.toString()) + } + } + + private companion object { + val propertyMutators = + mapOf SentryNavOptions>( + "enableNavigationBreadcrumbs" to + { options -> + SentryNavOptions { + enableNavigationBreadcrumbs = !options.enableNavigationBreadcrumbs + enableNavigationTransactions = options.enableNavigationTransactions + captureBackStack = options.captureBackStack + maxCapturedBackStackEntries = options.maxCapturedBackStackEntries + } + }, + "enableNavigationTransactions" to + { options -> + SentryNavOptions { + enableNavigationBreadcrumbs = options.enableNavigationBreadcrumbs + enableNavigationTransactions = !options.enableNavigationTransactions + captureBackStack = options.captureBackStack + maxCapturedBackStackEntries = options.maxCapturedBackStackEntries + } + }, + "captureBackStack" to + { options -> + SentryNavOptions { + enableNavigationBreadcrumbs = options.enableNavigationBreadcrumbs + enableNavigationTransactions = options.enableNavigationTransactions + captureBackStack = !options.captureBackStack + maxCapturedBackStackEntries = options.maxCapturedBackStackEntries + } + }, + "maxCapturedBackStackEntries" to + { options -> + SentryNavOptions { + enableNavigationBreadcrumbs = options.enableNavigationBreadcrumbs + enableNavigationTransactions = options.enableNavigationTransactions + captureBackStack = options.captureBackStack + maxCapturedBackStackEntries = options.maxCapturedBackStackEntries + 1 + } + }, + ) + } +} diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index f28fffd6b8..c77d94cc79 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -4730,6 +4730,7 @@ public final class io/sentry/TypeCheckHint { public static final field ANDROID_FRAGMENT Ljava/lang/String; public static final field ANDROID_INTENT Ljava/lang/String; public static final field ANDROID_MOTION_EVENT Ljava/lang/String; + public static final field ANDROID_NAV3_DESTINATION Ljava/lang/String; public static final field ANDROID_NAV_DESTINATION Ljava/lang/String; public static final field ANDROID_NETWORK_CAPABILITIES Ljava/lang/String; public static final field ANDROID_SENSOR_EVENT Ljava/lang/String; diff --git a/sentry/src/main/java/io/sentry/TypeCheckHint.java b/sentry/src/main/java/io/sentry/TypeCheckHint.java index 3260b46f16..852f960192 100644 --- a/sentry/src/main/java/io/sentry/TypeCheckHint.java +++ b/sentry/src/main/java/io/sentry/TypeCheckHint.java @@ -51,6 +51,10 @@ public final class TypeCheckHint { /** Used for Navigation breadrcrumbs. */ public static final String ANDROID_NAV_DESTINATION = "android:navigationDestination"; + /** Used for Navigation 3 breadcrumbs. */ + @ApiStatus.Experimental @ApiStatus.Internal + public static final String ANDROID_NAV3_DESTINATION = "android:nav3Destination"; + /** Used for Network breadrcrumbs. */ public static final String ANDROID_NETWORK_CAPABILITIES = "android:networkCapabilities";