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 dca0c54ea5..ac1fda1744 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -16,6 +16,9 @@ android { defaultConfig { minSdk = libs.versions.minSdk.get().toInt() + + // for AGP 4.1 + buildConfigField("String", "VERSION_NAME", "\"${project.version}\"") } buildTypes { @@ -33,6 +36,10 @@ android { compilerOptions.apiVersion = KotlinVersion.KOTLIN_1_9 } + testOptions { + unitTests.isReturnDefaultValues = true + } + lint { warningsAsErrors = true checkDependencies = true @@ -41,6 +48,8 @@ android { checkReleaseBuilds = false } + buildFeatures { buildConfig = true } + androidComponents.beforeVariants { it.enable = !Config.Android.shouldSkipDebugVariant(it.buildType) } 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..1adf8d7a03 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt @@ -0,0 +1,457 @@ +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.ERROR +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.protocol.App +import io.sentry.protocol.TransactionNameSource +import io.sentry.util.ExceptionUtils +import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion +import java.lang.ref.WeakReference + +/** + * 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). + */ +@Suppress("TooManyFunctions") +internal class BackStackObserver( + private val scopes: IScopes, + private val options: SentryNavOptions, + private val resolvers: () -> RouteResolvers, +) { + + private val navTransactions = NavTransactionManager(scopes, NAVIGATION_OP, TRANSACTION_ORIGIN) + private val screenTracker = ScreenTracker() + private val routeTranslator = RouteTranslator(resolvers, scopes.options.logger) + + 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 { + + private const val BACKSTACK_KEY = "backstack" + private const val NAVIGATION_CONTEXT_KEY = "navigation" + private const val NAVIGATION_OP: String = "navigation" + private const val TRANSACTION_ORIGIN = "auto.navigation.nav3" + + init { + SentryIntegrationPackageStorage.getInstance() + .addPackage("maven:io.sentry:sentry-android-navigation3", BuildConfig.VERSION_NAME) + } + } + + /** + * Updates recorded Sentry data based on the provided [backStack]. + * + * Note: This method is ***not*** idempotent. Callers should protect against repeat invocations + * with the same back stack. + */ + internal fun onBackStackChanged(backStack: List) { + guard("onBackStackChanged") { + val change = prepareChange(backStack) + scopes.configureScope { scope -> applyPreparedChange(scope, change) } + } + } + + internal fun cleanup() { + guard("cleanup") { + previousTopEntry = null + previousTopRoute = null + + scopes.configureScope { scope -> + navTransactions.stop(scope) + screenTracker.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. + scope.removeNavigationContext() + } + } + } + } + + 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 applyPreparedChange(scope: IScope, change: PreparedChange) { + when (change) { + is BackStackIsEmpty -> handleEmptyBackStack(scope) + + is BackStackHasNewTop -> { + handleNewTop(scope, change.previousTopRoute, change.data) + storeAsPreviousTop(change.data.topEntry, change.data.topRoute) + } + + is BackStackHasSameTop -> { + handleSameTop(scope, change.data) + storeAsPreviousTop(change.data.topEntry, change.data.topRoute) + } + } + } + + /** + * Extracts Sentry 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(entriesToTranslate) + + 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 + + scope.updateNavigationContext(currentBackStack.capturedRoutes) + + if (scopes.options.isEnableScreenTracking) { + screenTracker.track(scope, currentTopRoute.name) + } + + if (options.enableNavigationBreadcrumbs) { + scopes.addNav3Breadcrumb( + from = previousTop, + toEntry = currentBackStack.topEntry, + toRoute = currentBackStack.topRoute, + ) + } + + navTransactions.stop(scope) + + if (areNavigationTransactionsEnabled) { + navTransactions + .start( + scope, + currentTopRoute.name, + currentTopRoute.arguments, + ) + ?.updateNavigationContext(scope, currentBackStack) + } else { + // Rotate the propagation context. + scope.withPropagationContext { scope.setPropagationContext(PropagationContext()) } + } + } + + private fun handleSameTop(scope: IScope, backStack: BackStackData) { + scope.updateNavigationContext(backStack.capturedRoutes) + } + + private fun handleEmptyBackStack(scope: IScope) { + scope.updateNavigationContext(emptyList()) + navTransactions.stop(scope) + screenTracker.clear(scope) + previousTopEntry = null + previousTopRoute = null + } + + private fun storeAsPreviousTop(topEntry: T, topRoute: Route) { + previousTopEntry = WeakReference(topEntry) + previousTopRoute = topRoute + } + + private fun IScope.updateNavigationContext(capturedRoutes: List) { + if (capturedRoutes.isEmpty()) { + this.removeNavigationContext() + } else { + this.setContexts(NAVIGATION_CONTEXT_KEY, capturedRoutes.toNavigationContext()) + } + } + + private fun IScope.removeNavigationContext() { + // We purposefully don't call IScope.removeContexts(), as it doesn't notify IScopeObserver and + // therefore doesn't write its updates to disk ¯\_ (ツ)_/¯. + this.setContexts(NAVIGATION_CONTEXT_KEY, null as Any?) + } + + /** + * Updates the receiver's context 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. + */ + private fun ITransaction.updateNavigationContext(scope: IScope, backStack: BackStackData) { + if (scopes.options.isEnableScreenTracking) { + val appContext = contexts.app ?: io.sentry.protocol.Contexts(scope.contexts).app ?: App() + + appContext.viewNames = listOf(backStack.topRoute.name) + contexts.setApp(appContext) + } + + if (options.captureBackStack && backStack.capturedRoutes.isNotEmpty()) { + setContext(NAVIGATION_CONTEXT_KEY, backStack.capturedRoutes.toNavigationContext()) + } + } + + /** Builds the `{"backstack": [...]}` map bound under [NAVIGATION_CONTEXT_KEY]. */ + private fun List.toNavigationContext(): Map = + mapOf(BACKSTACK_KEY to serialize()) + + private fun IScopes.addNav3Breadcrumb( + 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) + this.addBreadcrumb(breadcrumb, hint) + } + + @Suppress("TooGenericExceptionCaught") + private inline fun guard(operation: String, body: () -> Unit) { + try { + body() + } catch (t: Throwable) { + // Nav instrumentation can invoke host code through route translation and scope mutation. + ExceptionUtils.rethrowIfFatal(t) + scopes.options.logger.log( + ERROR, + t, + "Nav3 instrumentation failed during %s. Skipping this navigation update.", + operation, + ) + } + } +} + +/** + * 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 previousTopRoute: Route?, + val data: BackStackData, + ) : PreparedChange + + /** The top of the back stack is unchanged, but one or more entries below it have been updated. */ + data class BackStackHasSameTop(val data: 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, +) + +/** Tracks a provided name as the current visible screen. */ +private class ScreenTracker { + + private var lastScreenName: String? = null + + fun track(scope: IScope, screenName: String) { + scope.screen = screenName + lastScreenName = screenName + } + + fun clear(scope: IScope) { + val routeName = lastScreenName ?: return + if (scope.screen == routeName) { + scope.screen = null + } + lastScreenName = null + } +} + +private class NavTransactionManager( + private val scopes: IScopes, + private val navigationOp: String, + private val transactionOrigin: String, +) { + + private var activeNavTransaction: ITransaction? = null + + /** Starts an idle navigation transaction, or no-ops if another transaction is already active. */ + fun start( + scope: IScope, + routeName: String, + arguments: Map, + ): ITransaction? { + clearFinishedScopeTransaction(scope) + + if (scope.transaction != null) { + scopes.options.logger.log( + DEBUG, + "Nav3 transaction for route %s won't be created because another transaction is active.", + routeName, + ) + + 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 + } + + val transaction = + scopes.startTransaction( + TransactionContext(routeName, TransactionNameSource.ROUTE, navigationOp), + transactionOptions, + ) + + activeNavTransaction = transaction + + transaction.apply { + spanContext.origin = transactionOrigin + 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 clearFinishedScopeTransaction(scope: IScope) { + scope.withTransaction { tx -> + if (tx?.isFinished == true) { + scope.clearTransaction() + } + } + } +} 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..d1598fedb8 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt @@ -0,0 +1,105 @@ +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 + } +} + +/** Creates [SentryNavOptions]. Optionally configure it via [configure]. */ +@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..6efad1a918 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt @@ -0,0 +1,687 @@ +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.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 kotlin.test.Test +import kotlin.test.assertNull +import org.mockito.kotlin.any +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 + }, + resolvers = { RouteResolvers(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 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) + } + + @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 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() + assertNull(fixture.scope.contexts.app?.viewNames) + 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() + assertNull(fixture.scope.contexts.app?.viewNames) + 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/SentryNavOptionsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt new file mode 100644 index 0000000000..0833e2cbe2 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt @@ -0,0 +1,107 @@ +package io.sentry.compose.navigation3 + +import com.google.common.truth.Truth.assertThat +import java.lang.reflect.Modifier +import kotlin.test.Test +import kotlin.test.assertFailsWith + +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 = + assertFailsWith { + 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) + } + } + + 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";