From 451cdc54c4662b3618677f5eca2db5d0744d3c67 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 27 Nov 2026 16:07:36 +0100 Subject: [PATCH 1/2] feat(nav3): Use the SerialName mapper in the Android samples The routes are @Serializable with the Nav2 sample's route names as their serial names. The single-stack sample names them with BackStackEntryMapper.SerialName and adds each route's own arguments, and the multi-root samples use SerialName directly. The performance scenario can run SerialName itself, to measure its name lookups, as well as the custom mapper. --- .../build.gradle.kts | 1 + .../sentry-samples-android/build.gradle.kts | 1 + .../android/navigation/nav3/Nav3Activity.kt | 71 ++++--- .../navigation/nav3/Nav3MultiActivity.kt | 6 +- .../nav3/Nav3PerformanceControls.kt | 40 +++- .../android/navigation/nav3/Nav3Routes.kt | 176 ++++++++++++++---- sentry-android-navigation3/proguard-rules.pro | 9 + .../navigation3/BackStackEntryMapper.kt | 40 +--- .../internal/backstack/BackStackConverter.kt | 2 +- .../backstack/BuiltInBackStackEntryMappers.kt | 6 +- .../kotlinx/KotlinxBackStackEntryMapper.kt | 92 +++++---- .../kotlinx/KotlinxCompatibilityCheck.kt | 24 --- .../kotlinx/KotlinxCompatibilityProbe.kt | 134 +++++++++++++ .../kotlinx/KotlinxSerializerLookup.kt | 27 ++- .../internal/backstack/kotlinx/README.md | 2 +- .../navigation3/internal/common/README.md | 9 - .../common/SerializationCompatibility.kt | 15 -- .../common/UnknownEntryReasonReporter.kt | 49 ----- .../navigation3/internal/contract/README.md | 8 - .../contract/UnknownEntryReasonReporter.kt | 41 ++++ .../navigation3/PackageBoundariesTest.kt | 24 --- .../backstack/BackStackConverterTest.kt | 2 +- .../BuiltInBackStackEntryMappersTest.kt | 4 +- .../UnavailableBackStackEntryMapperTest.kt | 2 +- .../KotlinxBackStackEntryMapperTest.kt | 174 +++-------------- .../kotlinx/KotlinxCompatibilityCheckTest.kt | 63 ------- .../kotlinx/KotlinxCompatibilityProbeTest.kt | 172 +++++++++++++++++ .../kotlinx/KotlinxMapperDiagnosticsTest.kt | 35 +++- .../kotlinx/KotlinxSerializerLookupTest.kt | 47 ++--- .../backstack/kotlinx/KotlinxTestEntries.kt | 21 +++ .../UnknownEntryReasonReporterTest.kt | 5 +- 31 files changed, 754 insertions(+), 548 deletions(-) delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt rename sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/{common => contract}/UnknownEntryReasonReporterTest.kt (95%) diff --git a/sentry-android-integration-tests/build.gradle.kts b/sentry-android-integration-tests/build.gradle.kts index 34b83c2c067..16be8b4011d 100644 --- a/sentry-android-integration-tests/build.gradle.kts +++ b/sentry-android-integration-tests/build.gradle.kts @@ -2,6 +2,7 @@ plugins { alias(libs.plugins.android.application) apply false alias(libs.plugins.kotlin.android) apply false alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.kotlin.serialization) apply false alias(libs.plugins.errorprone) apply false alias(libs.plugins.detekt) apply false alias(libs.plugins.gradle.versions) apply false diff --git a/sentry-android-integration-tests/sentry-samples-android/build.gradle.kts b/sentry-android-integration-tests/sentry-samples-android/build.gradle.kts index aee693598cb..1ad562d1258 100644 --- a/sentry-android-integration-tests/sentry-samples-android/build.gradle.kts +++ b/sentry-android-integration-tests/sentry-samples-android/build.gradle.kts @@ -13,6 +13,7 @@ plugins { id("io.sentry.jdk-target") alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) alias(libs.plugins.ksp) alias(libs.plugins.sentry) apply false alias(libs.plugins.sqldelight) diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt index 807fedad09a..67a8100a6ba 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt @@ -43,6 +43,7 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.navigation3.runtime.entryProvider import androidx.navigation3.ui.NavDisplay +import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.SentryNavEffect import io.sentry.compose.navigation3.SentryNavOptions @@ -232,16 +233,36 @@ private fun Nav3SampleApp( } val performanceExtractorMode = performanceState.extractorMode val performanceArgumentMode = performanceState.argumentMode - val backStackEntryMapper = + val performanceMapperMode = performanceState.mapperMode + val backStackEntryMapper: BackStackEntryMapper = remember( isPerformanceScenario, performanceExtractorMode, performanceArgumentMode, + performanceMapperMode, integrationMode.includeArguments, ) { - { route: Nav3Route -> - val name = - if (isPerformanceScenario) { + if (!isPerformanceScenario) { + // Names each route after its serial name, and adds the arguments the route selects. + BackStackEntryMapper { route -> + BackStackEntryMapper.SerialName.map(route)?.let { entry -> + SentryBackStackEntry(name = entry.name, arguments = route.arguments) + } + } + } else if (performanceMapperMode == Nav3PerformanceMapperMode.SERIAL_NAME) { + // Times each call to the built-in mapper, which records no arguments. Its result is + // returned as is, so a null keeps the reason the mapper reported. + BackStackEntryMapper { route -> + performanceState.recordNameExtraction("Nav3Stress.serialNameMapping") { + BackStackEntryMapper.SerialName.map(route) + } + } + } else { + // A custom mapper, so the performance scenario can time name and argument extraction + // separately and substitute synthetic arguments. It names routes without SerialName, so + // that its timings are a baseline for SerialName's. + BackStackEntryMapper { route -> + val name = performanceState.recordNameExtraction("Nav3Stress.nameExtraction") { consumeNav3PerformanceExtractorWork( performanceExtractorMode, @@ -249,34 +270,30 @@ private fun Nav3SampleApp( ) route.routeName } - } else { - route.routeName - } - val arguments = - if (isPerformanceScenario && !integrationMode.includeArguments) { - null - } else if (isPerformanceScenario) { - performanceState.recordArgumentExtraction("Nav3Stress.argumentsExtraction") { - consumeNav3PerformanceExtractorWork( - performanceExtractorMode, - route.performanceSeed, - ) - if (route is Nav3Route.Performance) { - nav3PerformanceArguments( - performanceArgumentMode, - route.index, - route.generation, + val arguments = + if (!integrationMode.includeArguments) { + null + } else { + performanceState.recordArgumentExtraction("Nav3Stress.argumentsExtraction") { + consumeNav3PerformanceExtractorWork( + performanceExtractorMode, + route.performanceSeed, ) - } else { - route.arguments + if (route is Nav3Route.Performance) { + nav3PerformanceArguments( + performanceArgumentMode, + route.index, + route.generation, + ) + } else { + route.arguments + } } } - } else { - route.arguments - } - SentryBackStackEntry(name = name, arguments = arguments) + SentryBackStackEntry(name = name, arguments = arguments) + } } } diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt index 4309cc66f08..6c9ccb0e886 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt @@ -54,7 +54,7 @@ import androidx.navigation3.ui.NavDisplay import androidx.navigationevent.compose.LocalNavigationEventDispatcherOwner import androidx.navigationevent.compose.rememberNavigationEventDispatcherOwner import io.sentry.compose.SentryModifier.sentryTag -import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryNavEffect import io.sentry.compose.navigation3.SentryNavOptions import io.sentry.samples.android.navigation.common.NavigationSampleConfig @@ -307,9 +307,7 @@ internal fun MultiRootNavDisplay( // Keep this before the NavDisplay below: TracedNav3Route's resume tagging relies on it. SentryNavEffect( backStack = backStack, - backStackEntryMapper = { route -> - SentryBackStackEntry(name = route.routeName, arguments = route.arguments) - }, + backStackEntryMapper = BackStackEntryMapper.SerialName, options = options, ) val onBack: () -> Unit = { diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt index e923948060f..e10cce8bf96 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt @@ -52,6 +52,7 @@ internal class Nav3PerformanceState( var autoNavigate by mutableStateOf(false) var extractorMode by mutableStateOf(Nav3PerformanceExtractorMode.NORMAL) var argumentMode by mutableStateOf(Nav3PerformanceArgumentMode.FLAT) + var mapperMode by mutableStateOf(Nav3PerformanceMapperMode.CUSTOM) var integrationMode by mutableStateOf(Nav3PerformanceIntegrationMode.FULL_STACK) private set @@ -321,6 +322,7 @@ internal class Nav3PerformanceState( appendLine("status=$performanceStatus") appendLine("route=$currentRoute") appendLine("tracked_stack=$backStack") + appendLine("mapper_mode=${mapperMode.label}") appendLine("recomposition_requests=$recompositionRequests") appendLine("navigation_mutations=$navigationMutations") appendLine("destination_changes=$destinationChanges") @@ -408,7 +410,7 @@ internal class Nav3PerformanceState( pendingOperation = null } - fun recordNameExtraction(sectionName: String, block: () -> String): String { + fun recordNameExtraction(sectionName: String, block: () -> T): T { val startedAt = System.nanoTime() Trace.beginSection(sectionName) try { @@ -512,6 +514,17 @@ internal enum class Nav3PerformanceArgumentMode(val label: String) { LARGE("Large"), } +/** + * Selects the performance scenario's mapper. + * + * [CUSTOM] provides synthetic arguments and separate extractor timings. [SERIAL_NAME] uses the + * built-in mapper, which extracts names only; each of its calls is timed as name extraction. + */ +internal enum class Nav3PerformanceMapperMode(val label: String) { + CUSTOM("Custom"), + SERIAL_NAME("SerialName"), +} + internal enum class Nav3PerformanceIntegrationMode( val label: String, val captureBackStack: Boolean, @@ -874,19 +887,33 @@ internal fun Nav3PerformancePanel( if (showExtractorControls) { PerfCard(title = "Extractor Inputs") { + val customExtractorControlsEnabled = + !state.performanceRunActive && state.mapperMode == Nav3PerformanceMapperMode.CUSTOM + + PerfModeRow( + label = "Mapper", + selectedLabel = state.mapperMode.label, + enabled = !state.performanceRunActive, + options = + Nav3PerformanceMapperMode.entries.map { mode -> + mode.label to { state.mapperMode = mode } + }, + ) + PerfModeRow( label = "Extractor cost", selectedLabel = state.extractorMode.label, - enabled = !state.performanceRunActive, + enabled = customExtractorControlsEnabled, options = Nav3PerformanceExtractorMode.entries.map { mode -> mode.label to { state.extractorMode = mode } }, ) + PerfModeRow( label = "Argument shape", selectedLabel = state.argumentMode.label, - enabled = !state.performanceRunActive, + enabled = customExtractorControlsEnabled, options = Nav3PerformanceArgumentMode.entries.map { mode -> mode.label to { state.argumentMode = mode } @@ -901,16 +928,19 @@ internal fun Nav3PerformancePanel( state.recompositionRequests.toString(), tag = navPerformanceTag("recomposition_requests"), ) + PerfInfoRow( "Navigation mutations", state.navigationMutations.toString(), tag = navPerformanceTag("navigation_mutations"), ) + PerfInfoRow( "Destination changes", state.destinationChanges.toString(), tag = navPerformanceTag("destination_changes"), ) + if (showExtractorControls) { if (state.performanceRunActive) { Text("Metrics are published when the fixed run completes.") @@ -972,6 +1002,7 @@ internal fun Nav3PerformancePanel( ) } } + Button( enabled = !state.performanceRunActive, onClick = { state.resetCounters() }, @@ -979,6 +1010,7 @@ internal fun Nav3PerformancePanel( ) { Text("Reset Counters") } + Button( enabled = !state.performanceRunActive, onClick = { state.publishDiagnostics(currentRoute = currentRoute, backStack = backStack) }, @@ -1243,7 +1275,7 @@ private fun Nav3PerformanceState.argumentsExtractorAverageMicros(): String = averageMicros(argumentsExtractorNanos, argumentsExtractorCalls) private fun averageMicros(totalNanos: Long, count: Int): String = - if (count == 0) "0 us" else "${totalNanos / count / 1_000} us" + if (count == 0) "0 us" else String.format(Locale.US, "%.2f us", totalNanos / count / 1_000.0) private fun formatNanos(durationNanos: Long): String = if (durationNanos < 1_000_000L) { diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt index 8dc18c45941..d292324c7e2 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt @@ -11,8 +11,15 @@ import io.sentry.samples.android.navigation.common.RouteNames import io.sentry.samples.android.navigation.common.RouteSpec import io.sentry.samples.android.navigation.common.RouteSpecs import io.sentry.samples.android.navigation.common.displayRoute +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable -internal fun Nav3Route.displayRoute(): String = routeSpec().displayRoute(arguments) +internal fun Nav3Route.displayRoute(): String = + when (this) { + // Shows the index and generation that tell the performance scenario's routes apart. + is Nav3Route.Performance -> "/$previewName" + else -> routeSpec().displayRoute(arguments) + } internal fun Nav3Route.routeSpec(): RouteSpec = when (this) { @@ -228,8 +235,26 @@ internal fun SnapshotStateList.replacePerformanceTop(generation: Int) set(lastIndex, Nav3Route.Performance(index = lastIndex, generation = generation)) } +/** + * The sample's serializable back stack keys. Each `@SerialName` supplies its Sentry route name, + * using the Nav2 sample's [RouteNames] for shared routes. Only constructor properties are + * serialized. + * + * [routeName] and [arguments] mirror the sample's mapper output so screens, tags, and transaction + * checks can read them without invoking the mapper. Mapping stays in `SentryNavEffect`, keeping + * setup and diagnostics out of composition and screens usable when mapping produces `/unknown`. + */ internal sealed interface Nav3Route { + /** + * The route's name as Sentry records it, without the leading `/`. Each route returns the constant + * it passes to `@SerialName`. + */ val routeName: String + + /** + * The route's arguments as the sample's mapper records them: each property under the Nav2 + * sample's [NavArgs] name, with a `null` campaign left out, as in the Nav2 sample. + */ val arguments: Map get() = emptyMap() @@ -239,87 +264,168 @@ internal sealed interface Nav3Route { val performanceSeed: Int get() = hashCode() + @Serializable + @SerialName(RouteNames.LANDING) data object Landing : Nav3Route { - override val routeName: String = RouteNames.LANDING + override val routeName: String + get() = RouteNames.LANDING } + @Serializable + @SerialName(RouteNames.HOME) data object SingleStack : Nav3Route { - override val routeName: String = RouteNames.HOME + override val routeName: String + get() = RouteNames.HOME } + @Serializable + @SerialName(RouteNames.CUSTOM) data object Custom : Nav3Route { - override val routeName: String = "Custom" + override val routeName: String + get() = RouteNames.CUSTOM } + @Serializable + @SerialName(MultiActivity.NAME) data object MultiActivity : Nav3Route { - override val routeName: String = "MultiActivity" + const val NAME = "MultiActivity" + + override val routeName: String + get() = NAME } + @Serializable + @SerialName(MultiFragment.NAME) data object MultiFragment : Nav3Route { - override val routeName: String = "MultiFragment" + const val NAME = "MultiFragment" + + override val routeName: String + get() = NAME } + @Serializable + @SerialName(FragmentOverlay.NAME) data object FragmentOverlay : Nav3Route { - override val routeName: String = "FragmentOverlay" + const val NAME = "FragmentOverlay" + + override val routeName: String + get() = NAME } + @Serializable + @SerialName(ViewPager2.NAME) data object ViewPager2 : Nav3Route { - override val routeName: String = "ViewPager2" + const val NAME = "ViewPager2" + + override val routeName: String + get() = NAME } + @Serializable + @SerialName(RouteNames.DEEP_LINK) data object DeepLink : Nav3Route { - override val routeName: String = RouteNames.DEEP_LINK + override val routeName: String + get() = RouteNames.DEEP_LINK } + @Serializable + @SerialName(RouteNames.PRODUCT_LIST) data object ProductList : Nav3Route { - override val routeName: String = RouteNames.PRODUCT_LIST + override val routeName: String + get() = RouteNames.PRODUCT_LIST } + @Serializable + @SerialName(RouteNames.PRODUCT_DETAIL) data class ProductDetail( val productId: String, val source: String, val campaign: String? = null, ) : Nav3Route { - override val routeName: String = RouteNames.PRODUCT_DETAIL - override val arguments: Map = - mapOf( - NavArgs.PRODUCT_ID to productId, - NavArgs.SOURCE to source, - NavArgs.CAMPAIGN to campaign, - ) - .filterValues { it != null } - override val previewName: String = "ProductDetail($productId)" + override val routeName: String + get() = RouteNames.PRODUCT_DETAIL + + override val arguments: Map + get() = buildMap { + put(NavArgs.PRODUCT_ID, productId) + put(NavArgs.SOURCE, source) + campaign?.let { put(NavArgs.CAMPAIGN, it) } + } + + override val previewName: String + get() = "ProductDetail($productId)" } + @Serializable + @SerialName(RouteNames.CHECKOUT) data class Checkout(val productId: String) : Nav3Route { - override val routeName: String = RouteNames.CHECKOUT - override val arguments: Map = mapOf(NavArgs.PRODUCT_ID to productId) - override val previewName: String = "Checkout($productId)" + override val routeName: String + get() = RouteNames.CHECKOUT + + override val arguments: Map + get() = mapOf(NavArgs.PRODUCT_ID to productId) + + override val previewName: String + get() = "Checkout($productId)" } + @Serializable + @SerialName(RouteNames.CONFIRMATION) data class Confirmation(val orderId: String) : Nav3Route { - override val routeName: String = RouteNames.CONFIRMATION - override val arguments: Map = mapOf(NavArgs.ORDER_ID to orderId) - override val previewName: String = "Confirmation($orderId)" + override val routeName: String + get() = RouteNames.CONFIRMATION + + override val arguments: Map + get() = mapOf(NavArgs.ORDER_ID to orderId) + + override val previewName: String + get() = "Confirmation($orderId)" } + @Serializable + @SerialName(RouteNames.PROMO_DIALOG) data class PromoDialog(val promoId: String) : Nav3Route { - override val routeName: String = RouteNames.PROMO_DIALOG - override val arguments: Map = mapOf(NavArgs.PROMO_ID to promoId) - override val previewName: String = "PromoDialog($promoId)" + override val routeName: String + get() = RouteNames.PROMO_DIALOG + + override val arguments: Map + get() = mapOf(NavArgs.PROMO_ID to promoId) + + override val previewName: String + get() = "PromoDialog($promoId)" } + @Serializable + @SerialName(RouteNames.SHARE_SHEET) data class ShareSheet(val productId: String) : Nav3Route { - override val routeName: String = RouteNames.SHARE_SHEET - override val arguments: Map = mapOf(NavArgs.PRODUCT_ID to productId) - override val previewName: String = "ShareSheet($productId)" + override val routeName: String + get() = RouteNames.SHARE_SHEET + + override val arguments: Map + get() = mapOf(NavArgs.PRODUCT_ID to productId) + + override val previewName: String + get() = "ShareSheet($productId)" } + @Serializable + @SerialName(Performance.NAME) data class Performance(val index: Int, val generation: Int) : Nav3Route { - override val routeName: String = "Performance" - override val arguments: Map = mapOf("index" to index, "generation" to generation) - override val previewName: String = "Performance($index:$generation)" - override val performanceSeed: Int = 31 * index + generation + override val routeName: String + get() = NAME + + override val arguments: Map + get() = mapOf("index" to index, "generation" to generation) + + override val previewName: String + get() = "Performance($index:$generation)" + + override val performanceSeed: Int + get() = 31 * index + generation + + companion object { + const val NAME = "Performance" + } } } diff --git a/sentry-android-navigation3/proguard-rules.pro b/sentry-android-navigation3/proguard-rules.pro index b34c23cc870..d9de2ff242b 100644 --- a/sentry-android-navigation3/proguard-rules.pro +++ b/sentry-android-navigation3/proguard-rules.pro @@ -8,6 +8,15 @@ ##---------------Begin: proguard configuration for kotlinx.serialization ---------- +# The kotlinx.serialization compatibility probe looks up this SDK-owned fixture's serializer via reflection, as the built-in mappers look +# up those of apps' back stack entries. kotlinx.serialization's R8 rules before 1.8.0 keep an object's serializer() only while its INSTANCE +# field is kept, and R8 full mode removes INSTANCE here, as the SDK only refers to the object's class. The probe would then be inconclusive +# for object lookups. +-keepclassmembers class io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe$ProbeObject { + public static ** INSTANCE; + kotlinx.serialization.KSerializer serializer(...); +} + # Serial names survive R8 minification because Kotlin's serialization compiler plugin fixes them at compile time. Our built-in mapper # fallback for private `@Serializable` objects relies on members preserved by kotlinx.serialization's own consumer rules. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index c24ed39db13..3c6b0ac1357 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt @@ -6,7 +6,8 @@ import org.jetbrains.annotations.ApiStatus /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * See [SerialName] for an out-of-the-box mapper, or else provide your own. + * See [SerialName] for an out-of-the-box mapper, or else provide your own. (Custom implementations + * can optionally fall back to `SerialName` for any entries that don't have to be special-cased.) * * **Privacy / PII** * @@ -30,13 +31,12 @@ import org.jetbrains.annotations.ApiStatus * **Names fall back to "/unknown"** * * If [map] throws, returns `null`, or returns a blank [name][SentryBackStackEntry.name], Sentry - * records the destination as "/unknown". (The sole exception is if [map] throws a fatal error, as - * fatal errors like [OutOfMemoryError] or [LinkageError] are propagated rather than being caught.) + * records the destination as "/unknown". Doing so signals that name extraction needs to be fixed + * while avoiding misleading gaps in nav state. * - * An "/unknown" entry signals that name extraction needs to be fixed while avoiding misleading gaps - * in nav state. For instance, if a user navigates from /home -> /detail -> /settings, but the - * mapper for /detail throws, the back stack record will be /home -> /unknown -> /settings rather - * than /home -> /settings. + * For instance, if a user navigates from /home -> /detail -> /settings, but the mapper for /detail + * throws, the back stack record will be /home -> /unknown -> /settings rather than /home -> + * /settings. * * Each "/unknown" entry records why it has no name under `unknown_entry_reason` (e.g., * `"mapping_failed"` if [map] threw). @@ -78,32 +78,6 @@ import org.jetbrains.annotations.ApiStatus * * In that case, it records why under `dropped_by_sentry` in the entry's arguments (e.g., * `"max_argument_count_exceeded"`). - * - * **Delegating to built-in mappers** - * - * Custom `BackStackEntryMapper`s may delegate to built-in mappers for entries the host app doesn't - * need to special-case: - * ```kotlin - * val mapper = BackStackEntryMapper { entry -> - * when (entry) { - * // Special-case any entries with sensitive info. - * is Cart -> SentryBackStackEntry( - * name = Cart.serializer().descriptor.serialName, - * arguments = mapOf("cartId" to entry.cartId), - * ) - * - * // Consider falling back to a built-in mapper for the rest. - * else -> BackStackEntryMapper.SerialName.map(entry) - * } - * } - * ``` - * - * Note: If a custom mapper calls a built-in mapper that returns `null`, and then the custom mapper - * returns `null` itself, the built-in mapper's `unknown_entry_reason` will be recorded. - * - * Be sure to invoke built-in mappers on the same thread that calls the custom mapper's [map] - * method, or else the original `unknown_entry_reason` may be lost and recorded as `"unmapped"` - * instead. */ @ApiStatus.Experimental public fun interface BackStackEntryMapper { diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index 9285537508e..90c65bc3f41 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt @@ -5,7 +5,6 @@ import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES @@ -17,6 +16,7 @@ import io.sentry.compose.navigation3.internal.contract.TRANSACTION_ARGUMENTS_KEY import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.util.ExceptionUtils import java.util.IdentityHashMap diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt index 3fd1247a200..85a17ca3f1d 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -8,10 +8,10 @@ import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper -import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.util.Collections import java.util.concurrent.ConcurrentHashMap @@ -51,6 +51,8 @@ internal object BuiltInBackStackEntryMappers { logger() .log( WARNING, + // Note: The compiler inlines INCOMPATIBLE_KOTLINX_ADVICE, and its use here doesn't access + // any kotlinx.serialization code. "Nav3 built-in mapper creation failed. Using $UNKNOWN_ENTRY_NAME for all entries. See " + "the attached error. $INCOMPATIBLE_KOTLINX_ADVICE", e, diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt index 07cd2ffc47d..5bc90e41323 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -5,10 +5,9 @@ import io.sentry.SentryLevel.DEBUG import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.util.ExceptionUtils import java.lang.reflect.GenericSignatureFormatError import java.lang.reflect.InvocationTargetException @@ -24,7 +23,9 @@ internal class KotlinxBackStackEntryMapper( * Returns the serializer of a back stack entry's `@Serializable` class, or `null` if there's none * (e.g. for a generic class). Only called for classes marked `@Serializable`. * - * May throw, as the lookup can run the app's serializer code for the first time. + * May throw, as the lookup can run the app's serializer code for the first time. Must rethrow a + * fatal error unwrapped if reflection wrapped it in an [InvocationTargetException], as + * [reflectiveSerializerOrNull] does, since the mapper treats every wrapped error as non-fatal. */ private val lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, /** @@ -33,8 +34,9 @@ internal class KotlinxBackStackEntryMapper( * May throw, as reading the class's annotations can fail. */ private val isAnnotatedSerializable: (Class<*>) -> Boolean = serializableAnnotationCheck(), - /** Throws a [LinkageError] if the app's kotlinx.serialization version is incompatible. */ - checkCompatibility: () -> Unit = { checkKotlinxCompatibility() }, + probe: CompatibilityProbe = { onInconclusive -> + KotlinxCompatibilityProbe.nameLookupLinkageError(onInconclusive = onInconclusive) + }, logger: () -> ILogger, ) : BackStackEntryMapper { @@ -45,18 +47,9 @@ internal class KotlinxBackStackEntryMapper( private val diagnostics = KotlinxMapperDiagnostics(logger) init { - // A LinkageError fails creation, so every back stack entry is recorded as "/unknown" with - // kotlinx_serialization_version. - try { - checkCompatibility() - } catch (e: IllegalArgumentException) { - // kotlinx.serialization reports lookup failures as SerializationException, an - // IllegalArgumentException. Neither it nor an IllegalStateException means the version is - // incompatible, so we name entries and handle any failure per type. - diagnostics.compatibilityCheckFailed(e) - } catch (e: IllegalStateException) { - diagnostics.compatibilityCheckFailed(e) - } + // Throws if the host app uses an incompatible kotlinx-serialization-core version. Causes + // creation to fail and every back stack entry to be recorded as "/unknown". + probe { error -> diagnostics.inconclusiveProbe(error) }?.let { throw it } } override fun map(backStackEntry: Any): SentryBackStackEntry? { @@ -75,20 +68,10 @@ internal class KotlinxBackStackEntryMapper( return SentryBackStackEntry(cached.name) } - private fun cachedType(type: Class<*>): CachedType { - types[type]?.let { - return it - } - - // Threads that race on a type's first entry may each look it up and log a failure, but only - // one result is ever cached. - val result = lookUp(type) - // A lookup that failed on an interrupted thread may succeed later, so we don't cache it. - if (result is CachedType.Unresolved && Thread.currentThread().isInterrupted) { - return result - } - return types.putIfAbsent(type, result) ?: result - } + private fun cachedType(type: Class<*>): CachedType = + // getOrPut may look up a type more than once if threads race on its first entry. That can cause + // a failed lookup to be logged more than once, but only one result will ever be cached. + types.getOrPut(type) { lookUp(type) } /** * Looks up [type]'s serializer and serial name. Logs if the serializer isn't available or the @@ -112,14 +95,8 @@ internal class KotlinxBackStackEntryMapper( CachedType.Resolved(serializer.descriptor.serialName) } } catch (e: InvocationTargetException) { - // The type's serializer() or descriptor threw through reflection, e.g., a custom serializer's - // ExceptionInInitializerError. A wrapped LinkageError fails only this type, so it isn't - // rethrown as fatal. - val cause = e.cause - if (cause != null && cause !is LinkageError) { - ExceptionUtils.rethrowIfFatal(cause) - } - unresolved(type, cause ?: e) + // The type's serializer() threw, e.g., a custom serializer's ExceptionInInitializerError. + unresolved(type, e.cause ?: e) } catch (e: LinkageError) { // Construction checks the library itself, so this likely comes from the type's serializer, // e.g., one compiled against another kotlinx.serialization version. It fails only this type. @@ -238,8 +215,8 @@ internal class KotlinxBackStackEntryMapper( * * Only decides what's logged. Whether a type is looked up again is up to the mapper. * - * The R8 check matches the start of [compatibilityCheckFailed]'s message, so rewording it requires - * updating `CompatibilityLogChecks.kt` + * The R8 check reads each unnamed type's reason from these messages, so rewording one requires + * updating the fragments in its `UnknownEntryReasonLogs.kt` * (`sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check`). */ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { @@ -267,17 +244,18 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { } /** - * Logs that the compatibility check threw [error], which doesn't mean kotlinx.serialization is - * incompatible. The mapper handles subsequent failures per type. + * Logs that the probe couldn't verify support for name lookups, due to [error] or a missing probe + * serializer if the error is `null`. The mapper handles subsequent failures per type. */ - fun compatibilityCheckFailed(error: RuntimeException) { - // DEBUG b/c a failed check doesn't affect what's recorded. + fun inconclusiveProbe(error: Throwable?) { + // DEBUG b/c an inconclusive probe doesn't affect what's recorded. logger() .log( DEBUG, error, - "Nav3 couldn't verify kotlinx.serialization compatibility (see the attached error). " + + "Nav3 couldn't verify kotlinx.serialization support for name lookups because %s. " + "Handling failures per entry type.", + if (error != null) PROBE_THREW else PROBE_SERIALIZER_NOT_FOUND, ) } @@ -293,8 +271,7 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { val advice = // An ExceptionInInitializerError only means the app's own initializer threw an exception. if (error is LinkageError && error !is ExceptionInInitializerError) { - // E.g., an app serializer compiled against a newer kotlinx.serialization than the app - // ships. + // The probe can miss an incompatible version, which then fails every type one at a time. "See the attached error. If all types fail, kotlinx.serialization may be incompatible. " + INCOMPATIBLE_KOTLINX_ADVICE } else if (error != null) { @@ -314,9 +291,28 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { companion object { + /** + * The oldest kotlinx.serialization version [KotlinxBackStackEntryMapper] supports. + * + * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. + */ + const val MIN_KOTLINX_SERIALIZATION_VERSION: String = "1.7.3" + + const val INCOMPATIBLE_KOTLINX_ADVICE: String = + "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + + "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + + "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + + "BackStackEntryMapper as a workaround." + /** Why a type can't be named, if reading its annotations, serializer, or descriptor threw. */ const val LOOK_UP_FAILED: String = "reading its annotations, serializer, or descriptor failed" + /** Why the compatibility probe was inconclusive, if it threw. */ + const val PROBE_THREW: String = "the compatibility probe threw (see the attached error)" + + /** Why the compatibility probe was inconclusive, if a probe type's serializer wasn't found. */ + const val PROBE_SERIALIZER_NOT_FOUND: String = "a probe serializer wasn't found" + /** Why a type can't be named, if its serializer lookup found none without throwing. */ const val SERIALIZER_NOT_FOUND: String = "no serializer was found (the type may be generic or require R8 keep rules)" diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt deleted file mode 100644 index ed5ac25d540..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt +++ /dev/null @@ -1,24 +0,0 @@ -@file:OptIn(ExperimentalSerializationApi::class) - -package io.sentry.compose.navigation3.internal.backstack.kotlinx - -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.KSerializer - -/** - * Verifies that the host app's `kotlinx-serialization-core` version is compatible with the APIs - * used by our built-in `BackStackEntryMapper`s. - * - * Does so by calling each kotlinx.serialization API that [KotlinxBackStackEntryMapper] calls, looks - * up the built-in `String` serializer, and reads its serial name. - * - * Throws a [LinkageError] if the app's `kotlinx-serialization-core` version is incompatible. A - * `LinkageError` thrown here is conclusive: unlike looking up an app type's serializer, the check - * runs no app code and no serializer generated by a compiler plugin, either of which could throw - * one for reasons that affect only its own type. - */ -internal fun checkKotlinxCompatibility( - lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, -) { - lookUpSerializer(String::class.java)?.descriptor?.serialName -} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt new file mode 100644 index 00000000000..65af42b4f6f --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt @@ -0,0 +1,134 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.util.ExceptionUtils +import java.lang.reflect.InvocationTargetException +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable + +/** + * Checks whether the app's `kotlinx-serialization-core` version successfully links against the APIs + * used by [KotlinxBackStackEntryMapper]. It does so via two built-in probe types ([ProbeClass] and + * [ProbeObject]). + * + * **Disambiguating serializer errors from library incompatibility** + * + * Without a check like this, `KotlinxBackStackEntryMapper` would have to infer an incompatible + * `kotlinx-serialization-core` version from [LinkageError]s thrown while handling the host app's + * own back stack entry types. But such errors can also come from the host app's serializer code, + * and should therefore only fail for the entry types that can't be deserialized. `ProbeClass` and + * `ProbeObject` don't execute any host app code, so a `LinkageError` while handling them means the + * app's `kotlinx-serialization-core` version is incompatible. + * + * Note: Only a `LinkageError` is conclusive, including one that reflection wrapped in an + * [InvocationTargetException] because a probe type's serializer threw it. Any other failure, or a + * probe type whose serializer can't be found, is ambiguous: it's reported to the caller's + * `onInconclusive` and otherwise ignored, as a real type that hits the same failure is handled and + * logged on its own. + */ +internal object KotlinxCompatibilityProbe { + + /** + * Checks `kotlinx-serialization-core` compatibility by retrieving serializers for [ProbeClass] + * and [ProbeObject] through [lookUpSerializer] and reading their serial names. + * + * Confines itself to methods used by our built-in [BackStackEntryMapper]s to avoid being disabled + * by incompatibilities from irrelevant APIs. + * + * Returns a [LinkageError] upon incompatibility, or `null` upon success or an inconclusive + * result. Additionally reports inconclusive results through [onInconclusive], passing the cause + * or `null` if a serializer is unavailable. + */ + fun nameLookupLinkageError( + lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, + onInconclusive: (Throwable?) -> Unit, + ): LinkageError? { + var isSerializerMissing = false + + val error = + probe(onInconclusive) { + for (type in listOf(ProbeClass::class.java, ProbeObject::class.java)) { + val descriptor = lookUpSerializer(type)?.descriptor + if (descriptor == null) { + isSerializerMissing = true + } else { + descriptor.serialName + } + } + } + + // Call outside probe() so an exception from onInconclusive isn't caught and reported back to + // the same callback. If a serializer is missing, the remaining lookup steps cannot be checked + // for that type. + if (isSerializerMissing) { + onInconclusive(null) + } + return error + } + + /** + * Runs [check], returning any [LinkageError] and rethrowing fatal errors. Returns `null` if the + * check succeeds or is inconclusive. + * + * Reports other errors to [onInconclusive], passing the cause. + */ + private inline fun probe( + onInconclusive: (Throwable) -> Unit, + check: () -> Unit, + ): LinkageError? = + try { + check() + null + } catch (e: LinkageError) { + e + } catch (e: InvocationTargetException) { + // A probe type's serializer runs only SDK and kotlinx.serialization code, so a LinkageError + // it throws means the library is incompatible. (The lookup keeps such errors wrapped, as an + // app type's serializer could throw them for unrelated reasons.) + val cause = e.cause + if (cause is LinkageError) { + cause + } else { + val error = cause ?: e + ExceptionUtils.rethrowIfFatal(error) + onInconclusive(error) + null + } + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because the app's kotlinx.serialization version may throw anything. Only + // LinkageError confirms incompatibility. Other non-fatal failures are inconclusive. + // Failures for actual back stack types are handled and logged per type. + ExceptionUtils.rethrowIfFatal(t) + onInconclusive(t) + null + } + + /** + * A known serializable type used to test whether the app's kotlinx.serialization version supports + * serializer lookup, without running host app code. + * + * Internal visibility lets the probe look up its serializer the same way + * [KotlinxBackStackEntryMapper] looks up serializers for the host app's public back stack entry + * types. + */ + @Serializable internal data class ProbeClass(val name: String = "probe") + + /** + * A known serializable object used to test serializer lookup for the host app's object-based back + * stack entries. This lookup reads the object's singleton instance. + */ + @Serializable internal object ProbeObject +} + +/** + * Checks whether the app's `kotlinx-serialization-core` version supports retrieving serializers and + * reading their serial names. Returns a [LinkageError] for incompatibility, or `null` for success + * or an inconclusive check. + * + * Reports inconclusive results through `onInconclusive`, passing the error or `null` if a + * serializer couldn't be found. + */ +internal typealias CompatibilityProbe = (onInconclusive: (Throwable?) -> Unit) -> LinkageError? diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt index 919c915535c..310007c04e5 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -1,5 +1,6 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx +import io.sentry.util.ExceptionUtils import java.lang.reflect.InvocationTargetException import kotlinx.serialization.KSerializer import kotlinx.serialization.serializerOrNull @@ -9,24 +10,32 @@ import kotlinx.serialization.serializerOrNull * Extends [serializerOrNull] to support private `@Serializable` objects. Also supports built-in * types and unannotated enums. * - * May execute serializer code and throw. What that code throws through reflection, including fatal - * errors such as [OutOfMemoryError], arrives wrapped in an [InvocationTargetException]. + * May execute serializer code and throw. Unwraps fatal causes such as [OutOfMemoryError] from + * [InvocationTargetException] so that fatal-error checks can recognize them. Keeps [LinkageError] + * causes wrapped because they affect only this type. */ @Suppress("SwallowedException") internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = try { - serializerOrNull(type) - } catch (_: IllegalAccessException) { - // kotlinx.serialization reads a serializable object's INSTANCE field without making it - // accessible, which will fail for private objects. - privateObjectSerializerOrNull(type) + try { + serializerOrNull(type) + } catch (_: IllegalAccessException) { + // kotlinx.serialization reads a serializable object's INSTANCE field without making it + // accessible, which will fail for private objects. + privateObjectSerializerOrNull(type) + } + } catch (e: InvocationTargetException) { + val cause = e.cause + if (cause != null && cause !is LinkageError) { + ExceptionUtils.rethrowIfFatal(cause) + } + throw e } /** * Uses reflection to look up the serializer of a private `@Serializable object` through the members * the serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules - * keep both members.) kotlinx.serialization's own object lookup reads the same two members, so this - * fallback can break only if that lookup breaks too. + * keep both members.) * * Propagates any exception thrown by the reflective lookup. */ diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md index ba524b283c2..ddadd318837 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -42,7 +42,7 @@ Recommended rules for raising the floor: - Raise it in a reviewed change of its own, with a CHANGELOG entry and a corresponding update to the [Sentry Nav3 docs](https://docs.sentry.io/platforms/android/integrations/navigation/#navigation-3). -- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `internal/common/KotlinxSerializationSupport.kt` to match. A unit test will fail if the two differ. +- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `KotlinxBackStackEntryMapper.kt` to match. A unit test will fail if the two differ. ## Minification diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md deleted file mode 100644 index b1eb7e8c1db..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# `io.sentry.compose.navigation3.internal.common` - -Package contains internal code that more than one `io.sentry.compose.navigation3` package needs, but that isn't part of what the Sentry UI -shows (see the `contract` package). - -## Dependencies - -This package may depend only on the `contract` package among `io.sentry.compose.navigation3` packages. As `backstack.kotlinx` depends on it, -it may ***not*** depend on Android, AndroidX, or kotlinx.serialization. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt deleted file mode 100644 index 9326a8a9ff4..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt +++ /dev/null @@ -1,15 +0,0 @@ -package io.sentry.compose.navigation3.internal.common - -/** - * The oldest kotlinx.serialization version the built-in mappers support. - * - * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. - */ -internal const val MIN_KOTLINX_SERIALIZATION_VERSION = "1.7.3" - -/** Advice logged when the app's kotlinx.serialization version may be incompatible. */ -internal const val INCOMPATIBLE_KOTLINX_ADVICE = - "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + - "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + - "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + - "BackStackEntryMapper as a workaround." diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt deleted file mode 100644 index d2e97d6f209..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt +++ /dev/null @@ -1,49 +0,0 @@ -package io.sentry.compose.navigation3.internal.common - -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason - -/** - * A side channel for built-in `BackStackEntryMapper`s to report [UnknownEntryReason]s for - * "/unknown" entries. - * - * Needed because mappers report failures only by returning `null`, and the - * `BackStackEntryMapper.map()`'s return type is a public API. - * - * **Custom `BackStackEntryMapper`s inherit reasons from any built-in mappers they delegate to** - * - * Built-in mappers [report] reasons before returning `null`. The converter [collect]s the last - * reason reported while the app's mapper runs, and records the reason only if the app's mapper - * returns `null`. As a result, a custom mapper that returns `null` after any built-in mapper - * returned `null` will record the built-in mapper's reason. - * - * Reasons are maintained per thread, so the converter collects only reasons reported on its own - * thread, where it runs the host app's mapper. If a custom mapper calls a built-in mapper on - * another thread, the reason will be lost and the entry will record `unmapped`. - */ -internal object UnknownEntryReasonReporter { - - private val reports = ThreadLocal() - - /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ - fun report(reason: UnknownEntryReason) { - reports.set(reason) - } - - /** - * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none - * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to - * another entry. - */ - fun collect(map: () -> R): Collected { - reports.remove() - try { - val result = map() - return Collected(result, reports.get()) - } finally { - reports.remove() - } - } - - /** What [collect] returns: the mapper's [result] and the [reason] reported while it ran. */ - data class Collected(val result: R, val reason: UnknownEntryReason?) -} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md deleted file mode 100644 index 94d7d9d55cc..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# `io.sentry.compose.navigation3.internal.contract` - -Package contains internal values that are effectively part of our public contract because the Sentry UI displays them or they define -observable behavior. - -## Dependencies - -This package may ***not*** depend on any other `io.sentry.compose.navigation3` package, so that every other package can depend on it. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt new file mode 100644 index 00000000000..f7954b95866 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt @@ -0,0 +1,41 @@ +package io.sentry.compose.navigation3.internal.contract + +/** + * Passes the [UnknownEntryReason] a built-in mapper knows to the back stack converter, as the + * mapper reports a failure by returning `null`, which is public API. + * + * A built-in mapper [report]s the reason right before returning `null`, and the converter + * [collect]s it around each call to the app's mapper. So a custom mapper that forwards a built-in + * mapper's `null` forwards its reason too, while one that returns `null` itself reports nothing, + * and one that returns a name has its reason ignored. If a custom mapper calls built-in mappers + * several times for one entry, the last reason reported is kept. + * + * Kept per thread, as mappers run on the converter's thread. + */ +internal object UnknownEntryReasonReporter { + + private val reports = ThreadLocal() + + /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ + fun report(reason: UnknownEntryReason) { + reports.set(reason) + } + + /** + * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none + * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to + * another entry. + */ + fun collect(map: () -> R): Collected { + reports.remove() + try { + val result = map() + return Collected(result, reports.get()) + } finally { + reports.remove() + } + } + + /** What [collect] returns: the mapper's [result] and the [reason] reported while it ran. */ + data class Collected(val result: R, val reason: UnknownEntryReason?) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt index ba5553ac51a..f83a32a9eca 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -102,29 +102,6 @@ class PackageBoundariesTest { assertThat(violations).isEmpty() } - @Test - fun `the common package imports only the contract package from other Sentry navigation3 packages`() { - val commonSources = sources.filter { it.packageName.isIn(COMMON) } - - val violations = commonSources.importsMatching { - it.isIn(ROOT) && !it.isIn(COMMON) && !it.isIn(CONTRACT) - } - - assertThat(commonSources).isNotEmpty() - assertThat(violations).isEmpty() - } - - @Test - fun `the common package has no imports from Android or AndroidX`() { - // The kotlinx package, which may not import them, depends on the common package. - val commonSources = sources.filter { it.packageName.isIn(COMMON) } - - val violations = commonSources.importsMatching { it.isIn("android") || it.isIn("androidx") } - - assertThat(commonSources).isNotEmpty() - assertThat(violations).isEmpty() - } - // Check that the import reader finds the declarations the rules inspect. @Test @@ -191,7 +168,6 @@ class PackageBoundariesTest { const val KOTLINX = "$BACKSTACK.kotlinx" const val LIFECYCLE = "$ROOT.internal.lifecycle" const val CONTRACT = "$ROOT.internal.contract" - const val COMMON = "$ROOT.internal.common" const val MAPPER_FACTORY_PATH = "$SOURCE_ROOT/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt" diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index 6e2e5f7854e..75dc883540a 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -10,10 +10,10 @@ import io.sentry.SentryOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.io.StringWriter import kotlin.test.assertFailsWith import org.junit.Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt index 92a433e38d6..758ce9c864b 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -7,9 +7,9 @@ import io.sentry.SentryLevel import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper -import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.test.initForTest import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt index 0e2d510e024..c2be6bf0f59 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt @@ -3,8 +3,8 @@ package io.sentry.compose.navigation3.internal.backstack import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt index 7a71d52b043..3cad4011b7b 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt @@ -4,10 +4,12 @@ import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.FakeCompatibilityProbe.Inconclusive import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.lang.annotation.AnnotationFormatError import java.lang.reflect.InvocationTargetException import kotlin.test.assertFailsWith @@ -61,64 +63,55 @@ class KotlinxBackStackEntryMapperTest { // Construction @Test - fun `logs nothing when created and the compatibility check passes`() { + fun `logs nothing when created and the compatibility probe finds kotlinx serialization compatible`() { val logger = mock() - KotlinxBackStackEntryMapper(logger = { logger }) + KotlinxBackStackEntryMapper(probe = FakeCompatibilityProbe(), logger = { logger }) verifyNoInteractions(logger) } @Test - fun `fails creation with the LinkageError the compatibility check throws`() { + fun `fails creation with the LinkageError the compatibility probe returns`() { val error = NoSuchMethodError("serializerOrNull") + val probe = FakeCompatibilityProbe(linkageError = error) val thrown = assertFailsWith { - KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { mock() }) + KotlinxBackStackEntryMapper(probe = probe, logger = { mock() }) } assertThat(thrown).isSameInstanceAs(error) } @Test - fun `logs nothing when the compatibility check throws a LinkageError`() { + fun `logs nothing when the compatibility probe returns a LinkageError`() { // BuiltInBackStackEntryMappers logs the error it catches, so the mapper doesn't log it too. val logger = mock() + val probe = FakeCompatibilityProbe(linkageError = NoSuchMethodError()) assertFailsWith { - KotlinxBackStackEntryMapper( - checkCompatibility = { throw NoSuchMethodError() }, - logger = { logger }, - ) + KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) } verifyNoInteractions(logger) } @Test - fun `logs an IllegalArgumentException the compatibility check throws at debug level`() { - val error = IllegalArgumentException("lookup failed") - val logger = mock() - - KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { logger }) - - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any()) - } - - @Test - fun `logs an IllegalStateException the compatibility check throws at debug level`() { - val error = IllegalStateException("lookup failed") + fun `logs the compatibility probe's error at debug level when the probe is inconclusive`() { + val error = IllegalStateException("probe failed") val logger = mock() + val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(error)) - KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { logger }) + KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any()) + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any(), eq(PROBE_THREW)) } @Test - fun `names entries when the compatibility check throws an IllegalStateException`() { - val fixture = Fixture.create(checkLinkage = { throw IllegalStateException() }) + fun `names entries when the compatibility probe is inconclusive`() { + val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(IllegalStateException())) + val fixture = Fixture.create(probe = probe) val mapper = fixture.mapper val mapped = mapper.map(Detail("1")) @@ -126,18 +119,6 @@ class KotlinxBackStackEntryMapperTest { assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) } - @Test - fun `fails creation with another exception the compatibility check throws`() { - val error = UnsupportedOperationException() - - val thrown = - assertFailsWith { - KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { mock() }) - } - - assertThat(thrown).isSameInstanceAs(error) - } - // Naming @Test @@ -354,8 +335,8 @@ class KotlinxBackStackEntryMapperTest { } @Test - fun `returns null and logs the cause when the serializer lookup throws a wrapped LinkageError`() { - val cause = NoSuchMethodError("serializer() failed to link") + fun `returns null and logs the cause when the serializer lookup throws a wrapped fatal error`() { + val cause = OutOfMemoryError("serializer() failed fatally") val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) val mapper = fixture.mapper @@ -365,49 +346,6 @@ class KotlinxBackStackEntryMapperTest { verifyLookUpFailureLogged(fixture.logger, cause) } - @Test - fun `propagates a wrapped fatal error the serializer lookup throws, unwrapped`() { - val cause = OutOfMemoryError("serializer() failed fatally") - val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) - val mapper = fixture.mapper - - val thrown = assertFailsWith { mapper.map(Detail("1")) } - - assertThat(thrown).isSameInstanceAs(cause) - } - - @Test - fun `propagates a wrapped fatal error the serializer's descriptor throws, unwrapped`() { - val cause = OutOfMemoryError("descriptor failed fatally") - val serializer = - object : NamingOnlySerializer() { - override val descriptor: SerialDescriptor - get() = throw InvocationTargetException(cause) - } - val fixture = Fixture.create(lookUpSerializer = { serializer }) - val mapper = fixture.mapper - - val thrown = assertFailsWith { mapper.map(Detail("1")) } - - assertThat(thrown).isSameInstanceAs(cause) - } - - @Test - fun `restores the interrupt flag when the serializer lookup throws a wrapped InterruptedException`() { - val fixture = - Fixture.create(lookUpSerializer = { throw InvocationTargetException(InterruptedException()) }) - val mapper = fixture.mapper - - try { - val mapped = mapper.map(Detail("1")) - - assertThat(mapped).isNull() - assertThat(Thread.currentThread().isInterrupted).isTrue() - } finally { - Thread.interrupted() - } - } - @Test fun `returns null and logs the InvocationTargetException when the serializer lookup throws one without a cause`() { val error = InvocationTargetException(null) @@ -558,57 +496,6 @@ class KotlinxBackStackEntryMapperTest { assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) } - @Test - fun `looks up a type's serializer again after the serializer lookup is interrupted`() { - var hasThrown = false - val fixture = - Fixture.create( - lookUpSerializer = { - if (!hasThrown) { - hasThrown = true - throw InvocationTargetException(InterruptedException()) - } - Detail.serializer() - }, - ) - val mapper = fixture.mapper - try { - assertThat(mapper.map(Detail("1"))).isNull() - } finally { - Thread.interrupted() - } - - val mapped = mapper.map(Detail("2")) - - assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) - assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java, Detail::class.java) - } - - @Test - fun `checks a type's annotation again after the annotation check is interrupted`() { - var hasThrown = false - val fixture = - Fixture.create( - isAnnotatedSerializable = { - if (!hasThrown) { - hasThrown = true - throw InterruptedException() - } - true - }, - ) - val mapper = fixture.mapper - try { - assertThat(mapper.map(Detail("1"))).isNull() - } finally { - Thread.interrupted() - } - - val mapped = mapper.map(Detail("2")) - - assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) - } - @Test fun `logs each type that isn't annotated @Serializable once`() { val fixture = Fixture.create() @@ -846,7 +733,7 @@ class KotlinxBackStackEntryMapperTest { private constructor( lookUpSerializer: (Class<*>) -> KSerializer<*>?, isAnnotatedSerializable: ((Class<*>) -> Boolean)?, - checkLinkage: () -> Unit, + probe: CompatibilityProbe, ) { val logger = mock() val lookedUpTypes = mutableListOf>() @@ -859,18 +746,9 @@ class KotlinxBackStackEntryMapperTest { } mapper = if (isAnnotatedSerializable == null) { - KotlinxBackStackEntryMapper( - recordingLookUp, - checkCompatibility = checkLinkage, - logger = { logger }, - ) + KotlinxBackStackEntryMapper(recordingLookUp, probe = probe, logger = { logger }) } else { - KotlinxBackStackEntryMapper( - recordingLookUp, - isAnnotatedSerializable, - checkLinkage, - { logger }, - ) + KotlinxBackStackEntryMapper(recordingLookUp, isAnnotatedSerializable, probe, { logger }) } } @@ -878,8 +756,8 @@ class KotlinxBackStackEntryMapperTest { fun create( lookUpSerializer: (Class<*>) -> KSerializer<*>? = { SERIALIZERS[it] }, isAnnotatedSerializable: ((Class<*>) -> Boolean)? = null, - checkLinkage: () -> Unit = {}, - ) = Fixture(lookUpSerializer, isAnnotatedSerializable, checkLinkage) + probe: CompatibilityProbe = FakeCompatibilityProbe(), + ) = Fixture(lookUpSerializer, isAnnotatedSerializable, probe) } } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt deleted file mode 100644 index 5e64aeefd3b..00000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt +++ /dev/null @@ -1,63 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack.kotlinx - -import com.google.common.truth.Truth.assertThat -import kotlin.test.assertFailsWith -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.builtins.serializer -import kotlinx.serialization.descriptors.SerialDescriptor -import org.junit.Test -import org.mockito.kotlin.doThrow -import org.mockito.kotlin.mock - -/** - * Runs the default check against the kotlinx.serialization version on the test classpath, which CI - * also sets to the latest stable release with `-Pnav3TestKotlinx=latestStable`. - */ -class KotlinxCompatibilityCheckTest { - - @Test - fun `checkKotlinxCompatibility() - succeeds for the kotlinx serialization version on the classpath`() { - checkKotlinxCompatibility() - } - - @Test - fun `checkKotlinxCompatibility() - looks up only the built-in String serializer`() { - val lookedUpTypes = mutableListOf>() - - checkKotlinxCompatibility { type -> - lookedUpTypes += type - String.serializer() - } - - assertThat(lookedUpTypes).containsExactly(String::class.java) - } - - @Test - fun `checkKotlinxCompatibility() - throws the LinkageError the serializer lookup throws`() { - val error = NoSuchMethodError("serializerOrNull") - - val thrown = assertFailsWith { checkKotlinxCompatibility { throw error } } - - assertThat(thrown).isSameInstanceAs(error) - } - - @OptIn(ExperimentalSerializationApi::class) - @Test - fun `checkKotlinxCompatibility() - throws the LinkageError reading the serial name throws`() { - val error = NoSuchMethodError("getSerialName") - val descriptor = mock { on { serialName } doThrow error } - val serializer = - object : NamingOnlySerializer() { - override val descriptor = descriptor - } - - val thrown = assertFailsWith { checkKotlinxCompatibility { serializer } } - - assertThat(thrown).isSameInstanceAs(error) - } - - @Test - fun `checkKotlinxCompatibility() - succeeds without reading a serial name when no serializer is found`() { - checkKotlinxCompatibility { null } - } -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt new file mode 100644 index 00000000000..53e3e06f837 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt @@ -0,0 +1,172 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.ProbeClass +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.ProbeObject +import java.lang.reflect.InvocationTargetException +import kotlin.test.assertFailsWith +import org.junit.Test + +/** + * Runs the default probe against the kotlinx.serialization version on the test classpath, which CI + * also sets to the latest stable release with `-Pnav3TestKotlinx=latestStable`. + */ +class KotlinxCompatibilityProbeTest { + + // nameLookupLinkageError() + + @Test + fun `nameLookupLinkageError() - returns null without an inconclusive result for a compatible version`() { + val inconclusive = mutableListOf() + + val error = KotlinxCompatibilityProbe.nameLookupLinkageError { inconclusive += it } + + assertThat(error).isNull() + assertThat(inconclusive).isEmpty() + } + + @Test + fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer lookup throws`() { + val error = NoSuchMethodError("serializerOrNull") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } + + assertThat(returned).isSameInstanceAs(error) + assertThat(inconclusive).isEmpty() + } + + @Test + fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer throws through reflection`() { + val error = NoSuchMethodError("PluginGeneratedSerialDescriptor") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw InvocationTargetException(error) }) { + inconclusive += it + } + + assertThat(returned).isSameInstanceAs(error) + assertThat(inconclusive).isEmpty() + } + + @Test + fun `nameLookupLinkageError() - reports another error a probe serializer throws via reflection as inconclusive`() { + val error = IllegalStateException("serializer failed") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw InvocationTargetException(error) }) { + inconclusive += it + } + + assertThat(returned).isNull() + assertThat(inconclusive).containsExactly(error) + } + + @Test + fun `nameLookupLinkageError() - propagates a fatal error a probe type's serializer throws through reflection`() { + val error = OutOfMemoryError() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError( + { + throw InvocationTargetException(error) + }, + ) {} + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `nameLookupLinkageError() - reports a non-fatal exception as inconclusive and returns null`() { + val error = IllegalStateException("lookup failed") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } + + assertThat(returned).isNull() + assertThat(inconclusive).containsExactly(error) + } + + @Test + fun `nameLookupLinkageError() - propagates a fatal error that isn't a LinkageError`() { + val error = OutOfMemoryError() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) {} + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `nameLookupLinkageError() - reports a missing probe serializer as inconclusive without an error`() { + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError( + { type -> if (type == ProbeObject::class.java) null else reflectiveSerializerOrNull(type) }, + ) { + inconclusive += it + } + + assertThat(returned).isNull() + assertThat(inconclusive).containsExactly(null) + } + + @Test + fun `nameLookupLinkageError() - doesn't re-report onInconclusive's exception for a missing probe serializer`() { + val error = IllegalStateException("callback failed") + val inconclusive = mutableListOf() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ null }) { + inconclusive += it + throw error + } + } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(inconclusive).containsExactly(null) + } + + @Test + fun `nameLookupLinkageError() - doesn't re-report onInconclusive's exception for a lookup exception`() { + val lookupError = IllegalStateException("lookup failed") + val callbackError = IllegalArgumentException("callback failed") + val inconclusive = mutableListOf() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw lookupError }) { + inconclusive += it + throw callbackError + } + } + + assertThat(thrown).isSameInstanceAs(callbackError) + assertThat(inconclusive).containsExactly(lookupError) + } + + // Probe types + + @Test + fun `the serializer lookup names the probe's types`() { + // A probe type the lookup couldn't find would make the check pass without looking up a name. + val names = + listOf(ProbeClass::class.java, ProbeObject::class.java).map { + reflectiveSerializerOrNull(it)?.descriptor?.serialName + } + + assertThat(names) + .containsExactly(ProbeClass::class.qualifiedName, ProbeObject::class.qualifiedName) + .inOrder() + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt index b500c609c3c..a72868dd03f 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt @@ -3,13 +3,16 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.MIN_KOTLINX_SERIALIZATION_VERSION +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND -import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE -import io.sentry.compose.navigation3.internal.common.MIN_KOTLINX_SERIALIZATION_VERSION import org.junit.Test import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -44,18 +47,34 @@ class KotlinxMapperDiagnosticsTest { assertThat(message.firstValue).contains("Use a custom BackStackEntryMapper") } - // compatibilityCheckFailed() + // inconclusiveProbe() @Test - fun `compatibilityCheckFailed() - logs the error at debug level`() { - val error = IllegalStateException("lookup failed") + fun `inconclusiveProbe() - logs the error at debug level with the reason that the probe threw`() { + val error = IllegalStateException("probe failed") + + diagnostics.inconclusiveProbe(error) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), message.capture(), eq(PROBE_THREW)) + assertThat(message.firstValue) + .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") + } - diagnostics.compatibilityCheckFailed(error) + @Test + fun `inconclusiveProbe() - logs at debug level that no probe serializer was found when there's no error`() { + diagnostics.inconclusiveProbe(null) val message = argumentCaptor() - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), message.capture()) + verify(logger) + .log( + eq(SentryLevel.DEBUG), + isNull(), + message.capture(), + eq(PROBE_SERIALIZER_NOT_FOUND), + ) assertThat(message.firstValue) - .startsWith("Nav3 couldn't verify kotlinx.serialization compatibility") + .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") } // unresolved() diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt index a2c998a76cd..bb3b036ed79 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt @@ -8,7 +8,6 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor -import kotlinx.serialization.serializerOrNull import org.junit.Test class KotlinxSerializerLookupTest { @@ -215,16 +214,6 @@ class KotlinxSerializerLookupTest { assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateObject") } - /** - * Fails once a kotlinx.serialization release can look up a private object's serializer itself, - * e.g., when CI runs the latest stable release. The private object fallback can then be removed - * once `kotlinxSerialization-floor` reaches that release. - */ - @Test - fun `kotlinx serialization's own lookup still throws IllegalAccessException for a private object`() { - assertFailsWith { serializerOrNull(PrivateObject::class.java) } - } - @Test fun `returns the serializer of a private @Serializable class`() { val serializer = reflectiveSerializerOrNull(PrivateClass::class.java) @@ -336,38 +325,38 @@ class KotlinxSerializerLookupTest { } @Test - fun `throws an interruption of a class's serializer construction wrapped in an InvocationTargetException`() { - val thrown = - assertFailsWith { - reflectiveSerializerOrNull(InterruptedConstruction::class.java) - } - - assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) + fun `restores the interrupt flag when a class's serializer construction is interrupted`() { + try { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(InterruptedConstruction::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) + assertThat(Thread.currentThread().isInterrupted).isTrue() + } finally { + Thread.interrupted() + } } @Test - fun `throws a class's fatal serializer initializer error wrapped in an InvocationTargetException`() { + fun `propagates a class's fatal serializer initializer error unwrapped`() { val thrown = - assertFailsWith { + assertFailsWith { reflectiveSerializerOrNull(FatallyUninitializable::class.java) } - assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) - assertThat(thrown) - .hasCauseThat() - .hasMessageThat() - .isEqualTo("class serializer init failed fatally") + assertThat(thrown).hasMessageThat().isEqualTo("class serializer init failed fatally") } @Test - fun `throws a private object's fatal serializer initializer error wrapped in an InvocationTargetException`() { + fun `propagates a private object's fatal serializer initializer error unwrapped`() { val thrown = - assertFailsWith { + assertFailsWith { reflectiveSerializerOrNull(PrivateFatal::class.java) } - assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) - assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed fatally") + assertThat(thrown).hasMessageThat().isEqualTo("serializer init failed fatally") } // Private object lookups that find no serializer diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt index d06ebe92abb..1a1339a038c 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -20,3 +20,24 @@ internal abstract class NamingOnlySerializer : KSerializer { override fun deserialize(decoder: Decoder): T = throw UnsupportedOperationException() } + +/** + * A compatibility probe that finds kotlinx.serialization compatible by default. Set [linkageError] + * to report an incompatible version, or [inconclusive] to report an inconclusive result. + */ +internal class FakeCompatibilityProbe( + private val linkageError: LinkageError? = null, + private val inconclusive: Inconclusive? = null, +) : CompatibilityProbe { + + override fun invoke(onInconclusive: (Throwable?) -> Unit): LinkageError? { + linkageError?.let { + return it + } + inconclusive?.let { onInconclusive(it.error) } + return null + } + + /** Why the probe is inconclusive: [error], or `null` if a probe serializer wasn't found. */ + class Inconclusive(val error: Throwable?) +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt similarity index 95% rename from sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt rename to sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt index 7c19e9e70c9..eea71458579 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt @@ -1,8 +1,7 @@ -package io.sentry.compose.navigation3.internal.common +package io.sentry.compose.navigation3.internal.contract import com.google.common.truth.Truth.assertThat -import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter.Collected -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter.Collected import kotlin.concurrent.thread import kotlin.test.assertFailsWith import org.junit.Test From ab115373d5d97b041df331c9ef1243953360c049 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 11:01:58 +0100 Subject: [PATCH 2/2] fix(samples): Reset the Nav3 performance counters when the mapper changes Switching between the Custom and SerialName mappers kept the previous mapper's timings, so interactive diagnostics could report mapper_mode=SerialName alongside Custom's argument extractions. Co-Authored-By: Claude Opus 5.5 --- .../nav3/Nav3PerformanceControls.kt | 12 +- sentry-android-navigation3/proguard-rules.pro | 9 - .../navigation3/BackStackEntryMapper.kt | 40 +++- .../internal/backstack/BackStackConverter.kt | 2 +- .../backstack/BuiltInBackStackEntryMappers.kt | 6 +- .../kotlinx/KotlinxBackStackEntryMapper.kt | 92 ++++----- .../kotlinx/KotlinxCompatibilityCheck.kt | 24 +++ .../kotlinx/KotlinxCompatibilityProbe.kt | 134 -------------- .../kotlinx/KotlinxSerializerLookup.kt | 27 +-- .../internal/backstack/kotlinx/README.md | 2 +- .../navigation3/internal/common/README.md | 9 + .../common/SerializationCompatibility.kt | 15 ++ .../common/UnknownEntryReasonReporter.kt | 49 +++++ .../navigation3/internal/contract/README.md | 8 + .../contract/UnknownEntryReasonReporter.kt | 41 ----- .../navigation3/PackageBoundariesTest.kt | 24 +++ .../backstack/BackStackConverterTest.kt | 2 +- .../BuiltInBackStackEntryMappersTest.kt | 4 +- .../UnavailableBackStackEntryMapperTest.kt | 2 +- .../KotlinxBackStackEntryMapperTest.kt | 174 +++++++++++++++--- .../kotlinx/KotlinxCompatibilityCheckTest.kt | 63 +++++++ .../kotlinx/KotlinxCompatibilityProbeTest.kt | 172 ----------------- .../kotlinx/KotlinxMapperDiagnosticsTest.kt | 35 +--- .../kotlinx/KotlinxSerializerLookupTest.kt | 47 +++-- .../backstack/kotlinx/KotlinxTestEntries.kt | 21 --- .../UnknownEntryReasonReporterTest.kt | 5 +- 26 files changed, 489 insertions(+), 530 deletions(-) create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt rename sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/{contract => common}/UnknownEntryReasonReporterTest.kt (95%) diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt index e10cce8bf96..b5f432009bd 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt @@ -53,6 +53,8 @@ internal class Nav3PerformanceState( var extractorMode by mutableStateOf(Nav3PerformanceExtractorMode.NORMAL) var argumentMode by mutableStateOf(Nav3PerformanceArgumentMode.FLAT) var mapperMode by mutableStateOf(Nav3PerformanceMapperMode.CUSTOM) + private set + var integrationMode by mutableStateOf(Nav3PerformanceIntegrationMode.FULL_STACK) private set @@ -179,6 +181,14 @@ internal class Nav3PerformanceState( suppressNextDestinationChange = true } + /** Resets the counters on a change, as each mapper records different measurements. */ + fun updateMapperMode(mode: Nav3PerformanceMapperMode) { + if (mapperMode != mode) { + mapperMode = mode + resetCounters() + } + } + fun updateIntegrationMode(mode: Nav3PerformanceIntegrationMode) { if (integrationMode != mode) { discardNextSentryNavEffectMeasurement = true @@ -896,7 +906,7 @@ internal fun Nav3PerformancePanel( enabled = !state.performanceRunActive, options = Nav3PerformanceMapperMode.entries.map { mode -> - mode.label to { state.mapperMode = mode } + mode.label to { state.updateMapperMode(mode) } }, ) diff --git a/sentry-android-navigation3/proguard-rules.pro b/sentry-android-navigation3/proguard-rules.pro index d9de2ff242b..b34c23cc870 100644 --- a/sentry-android-navigation3/proguard-rules.pro +++ b/sentry-android-navigation3/proguard-rules.pro @@ -8,15 +8,6 @@ ##---------------Begin: proguard configuration for kotlinx.serialization ---------- -# The kotlinx.serialization compatibility probe looks up this SDK-owned fixture's serializer via reflection, as the built-in mappers look -# up those of apps' back stack entries. kotlinx.serialization's R8 rules before 1.8.0 keep an object's serializer() only while its INSTANCE -# field is kept, and R8 full mode removes INSTANCE here, as the SDK only refers to the object's class. The probe would then be inconclusive -# for object lookups. --keepclassmembers class io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe$ProbeObject { - public static ** INSTANCE; - kotlinx.serialization.KSerializer serializer(...); -} - # Serial names survive R8 minification because Kotlin's serialization compiler plugin fixes them at compile time. Our built-in mapper # fallback for private `@Serializable` objects relies on members preserved by kotlinx.serialization's own consumer rules. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index 3c6b0ac1357..c24ed39db13 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt @@ -6,8 +6,7 @@ import org.jetbrains.annotations.ApiStatus /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * See [SerialName] for an out-of-the-box mapper, or else provide your own. (Custom implementations - * can optionally fall back to `SerialName` for any entries that don't have to be special-cased.) + * See [SerialName] for an out-of-the-box mapper, or else provide your own. * * **Privacy / PII** * @@ -31,12 +30,13 @@ import org.jetbrains.annotations.ApiStatus * **Names fall back to "/unknown"** * * If [map] throws, returns `null`, or returns a blank [name][SentryBackStackEntry.name], Sentry - * records the destination as "/unknown". Doing so signals that name extraction needs to be fixed - * while avoiding misleading gaps in nav state. + * records the destination as "/unknown". (The sole exception is if [map] throws a fatal error, as + * fatal errors like [OutOfMemoryError] or [LinkageError] are propagated rather than being caught.) * - * For instance, if a user navigates from /home -> /detail -> /settings, but the mapper for /detail - * throws, the back stack record will be /home -> /unknown -> /settings rather than /home -> - * /settings. + * An "/unknown" entry signals that name extraction needs to be fixed while avoiding misleading gaps + * in nav state. For instance, if a user navigates from /home -> /detail -> /settings, but the + * mapper for /detail throws, the back stack record will be /home -> /unknown -> /settings rather + * than /home -> /settings. * * Each "/unknown" entry records why it has no name under `unknown_entry_reason` (e.g., * `"mapping_failed"` if [map] threw). @@ -78,6 +78,32 @@ import org.jetbrains.annotations.ApiStatus * * In that case, it records why under `dropped_by_sentry` in the entry's arguments (e.g., * `"max_argument_count_exceeded"`). + * + * **Delegating to built-in mappers** + * + * Custom `BackStackEntryMapper`s may delegate to built-in mappers for entries the host app doesn't + * need to special-case: + * ```kotlin + * val mapper = BackStackEntryMapper { entry -> + * when (entry) { + * // Special-case any entries with sensitive info. + * is Cart -> SentryBackStackEntry( + * name = Cart.serializer().descriptor.serialName, + * arguments = mapOf("cartId" to entry.cartId), + * ) + * + * // Consider falling back to a built-in mapper for the rest. + * else -> BackStackEntryMapper.SerialName.map(entry) + * } + * } + * ``` + * + * Note: If a custom mapper calls a built-in mapper that returns `null`, and then the custom mapper + * returns `null` itself, the built-in mapper's `unknown_entry_reason` will be recorded. + * + * Be sure to invoke built-in mappers on the same thread that calls the custom mapper's [map] + * method, or else the original `unknown_entry_reason` may be lost and recorded as `"unmapped"` + * instead. */ @ApiStatus.Experimental public fun interface BackStackEntryMapper { diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index 90c65bc3f41..9285537508e 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt @@ -5,6 +5,7 @@ import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_DEPTH import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_VALUES @@ -16,7 +17,6 @@ import io.sentry.compose.navigation3.internal.contract.TRANSACTION_ARGUMENTS_KEY import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.util.ExceptionUtils import java.util.IdentityHashMap diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt index 85a17ca3f1d..3fd1247a200 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -8,10 +8,10 @@ import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.util.Collections import java.util.concurrent.ConcurrentHashMap @@ -51,8 +51,6 @@ internal object BuiltInBackStackEntryMappers { logger() .log( WARNING, - // Note: The compiler inlines INCOMPATIBLE_KOTLINX_ADVICE, and its use here doesn't access - // any kotlinx.serialization code. "Nav3 built-in mapper creation failed. Using $UNKNOWN_ENTRY_NAME for all entries. See " + "the attached error. $INCOMPATIBLE_KOTLINX_ADVICE", e, diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt index 5bc90e41323..07cd2ffc47d 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -5,9 +5,10 @@ import io.sentry.SentryLevel.DEBUG import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.util.ExceptionUtils import java.lang.reflect.GenericSignatureFormatError import java.lang.reflect.InvocationTargetException @@ -23,9 +24,7 @@ internal class KotlinxBackStackEntryMapper( * Returns the serializer of a back stack entry's `@Serializable` class, or `null` if there's none * (e.g. for a generic class). Only called for classes marked `@Serializable`. * - * May throw, as the lookup can run the app's serializer code for the first time. Must rethrow a - * fatal error unwrapped if reflection wrapped it in an [InvocationTargetException], as - * [reflectiveSerializerOrNull] does, since the mapper treats every wrapped error as non-fatal. + * May throw, as the lookup can run the app's serializer code for the first time. */ private val lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, /** @@ -34,9 +33,8 @@ internal class KotlinxBackStackEntryMapper( * May throw, as reading the class's annotations can fail. */ private val isAnnotatedSerializable: (Class<*>) -> Boolean = serializableAnnotationCheck(), - probe: CompatibilityProbe = { onInconclusive -> - KotlinxCompatibilityProbe.nameLookupLinkageError(onInconclusive = onInconclusive) - }, + /** Throws a [LinkageError] if the app's kotlinx.serialization version is incompatible. */ + checkCompatibility: () -> Unit = { checkKotlinxCompatibility() }, logger: () -> ILogger, ) : BackStackEntryMapper { @@ -47,9 +45,18 @@ internal class KotlinxBackStackEntryMapper( private val diagnostics = KotlinxMapperDiagnostics(logger) init { - // Throws if the host app uses an incompatible kotlinx-serialization-core version. Causes - // creation to fail and every back stack entry to be recorded as "/unknown". - probe { error -> diagnostics.inconclusiveProbe(error) }?.let { throw it } + // A LinkageError fails creation, so every back stack entry is recorded as "/unknown" with + // kotlinx_serialization_version. + try { + checkCompatibility() + } catch (e: IllegalArgumentException) { + // kotlinx.serialization reports lookup failures as SerializationException, an + // IllegalArgumentException. Neither it nor an IllegalStateException means the version is + // incompatible, so we name entries and handle any failure per type. + diagnostics.compatibilityCheckFailed(e) + } catch (e: IllegalStateException) { + diagnostics.compatibilityCheckFailed(e) + } } override fun map(backStackEntry: Any): SentryBackStackEntry? { @@ -68,10 +75,20 @@ internal class KotlinxBackStackEntryMapper( return SentryBackStackEntry(cached.name) } - private fun cachedType(type: Class<*>): CachedType = - // getOrPut may look up a type more than once if threads race on its first entry. That can cause - // a failed lookup to be logged more than once, but only one result will ever be cached. - types.getOrPut(type) { lookUp(type) } + private fun cachedType(type: Class<*>): CachedType { + types[type]?.let { + return it + } + + // Threads that race on a type's first entry may each look it up and log a failure, but only + // one result is ever cached. + val result = lookUp(type) + // A lookup that failed on an interrupted thread may succeed later, so we don't cache it. + if (result is CachedType.Unresolved && Thread.currentThread().isInterrupted) { + return result + } + return types.putIfAbsent(type, result) ?: result + } /** * Looks up [type]'s serializer and serial name. Logs if the serializer isn't available or the @@ -95,8 +112,14 @@ internal class KotlinxBackStackEntryMapper( CachedType.Resolved(serializer.descriptor.serialName) } } catch (e: InvocationTargetException) { - // The type's serializer() threw, e.g., a custom serializer's ExceptionInInitializerError. - unresolved(type, e.cause ?: e) + // The type's serializer() or descriptor threw through reflection, e.g., a custom serializer's + // ExceptionInInitializerError. A wrapped LinkageError fails only this type, so it isn't + // rethrown as fatal. + val cause = e.cause + if (cause != null && cause !is LinkageError) { + ExceptionUtils.rethrowIfFatal(cause) + } + unresolved(type, cause ?: e) } catch (e: LinkageError) { // Construction checks the library itself, so this likely comes from the type's serializer, // e.g., one compiled against another kotlinx.serialization version. It fails only this type. @@ -215,8 +238,8 @@ internal class KotlinxBackStackEntryMapper( * * Only decides what's logged. Whether a type is looked up again is up to the mapper. * - * The R8 check reads each unnamed type's reason from these messages, so rewording one requires - * updating the fragments in its `UnknownEntryReasonLogs.kt` + * The R8 check matches the start of [compatibilityCheckFailed]'s message, so rewording it requires + * updating `CompatibilityLogChecks.kt` * (`sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check`). */ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { @@ -244,18 +267,17 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { } /** - * Logs that the probe couldn't verify support for name lookups, due to [error] or a missing probe - * serializer if the error is `null`. The mapper handles subsequent failures per type. + * Logs that the compatibility check threw [error], which doesn't mean kotlinx.serialization is + * incompatible. The mapper handles subsequent failures per type. */ - fun inconclusiveProbe(error: Throwable?) { - // DEBUG b/c an inconclusive probe doesn't affect what's recorded. + fun compatibilityCheckFailed(error: RuntimeException) { + // DEBUG b/c a failed check doesn't affect what's recorded. logger() .log( DEBUG, error, - "Nav3 couldn't verify kotlinx.serialization support for name lookups because %s. " + + "Nav3 couldn't verify kotlinx.serialization compatibility (see the attached error). " + "Handling failures per entry type.", - if (error != null) PROBE_THREW else PROBE_SERIALIZER_NOT_FOUND, ) } @@ -271,7 +293,8 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { val advice = // An ExceptionInInitializerError only means the app's own initializer threw an exception. if (error is LinkageError && error !is ExceptionInInitializerError) { - // The probe can miss an incompatible version, which then fails every type one at a time. + // E.g., an app serializer compiled against a newer kotlinx.serialization than the app + // ships. "See the attached error. If all types fail, kotlinx.serialization may be incompatible. " + INCOMPATIBLE_KOTLINX_ADVICE } else if (error != null) { @@ -291,28 +314,9 @@ internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { companion object { - /** - * The oldest kotlinx.serialization version [KotlinxBackStackEntryMapper] supports. - * - * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. - */ - const val MIN_KOTLINX_SERIALIZATION_VERSION: String = "1.7.3" - - const val INCOMPATIBLE_KOTLINX_ADVICE: String = - "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + - "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + - "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + - "BackStackEntryMapper as a workaround." - /** Why a type can't be named, if reading its annotations, serializer, or descriptor threw. */ const val LOOK_UP_FAILED: String = "reading its annotations, serializer, or descriptor failed" - /** Why the compatibility probe was inconclusive, if it threw. */ - const val PROBE_THREW: String = "the compatibility probe threw (see the attached error)" - - /** Why the compatibility probe was inconclusive, if a probe type's serializer wasn't found. */ - const val PROBE_SERIALIZER_NOT_FOUND: String = "a probe serializer wasn't found" - /** Why a type can't be named, if its serializer lookup found none without throwing. */ const val SERIALIZER_NOT_FOUND: String = "no serializer was found (the type may be generic or require R8 keep rules)" diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt new file mode 100644 index 00000000000..ed5ac25d540 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheck.kt @@ -0,0 +1,24 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer + +/** + * Verifies that the host app's `kotlinx-serialization-core` version is compatible with the APIs + * used by our built-in `BackStackEntryMapper`s. + * + * Does so by calling each kotlinx.serialization API that [KotlinxBackStackEntryMapper] calls, looks + * up the built-in `String` serializer, and reads its serial name. + * + * Throws a [LinkageError] if the app's `kotlinx-serialization-core` version is incompatible. A + * `LinkageError` thrown here is conclusive: unlike looking up an app type's serializer, the check + * runs no app code and no serializer generated by a compiler plugin, either of which could throw + * one for reasons that affect only its own type. + */ +internal fun checkKotlinxCompatibility( + lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, +) { + lookUpSerializer(String::class.java)?.descriptor?.serialName +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt deleted file mode 100644 index 65af42b4f6f..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt +++ /dev/null @@ -1,134 +0,0 @@ -@file:OptIn(ExperimentalSerializationApi::class) - -package io.sentry.compose.navigation3.internal.backstack.kotlinx - -import io.sentry.compose.navigation3.BackStackEntryMapper -import io.sentry.util.ExceptionUtils -import java.lang.reflect.InvocationTargetException -import kotlinx.serialization.ExperimentalSerializationApi -import kotlinx.serialization.KSerializer -import kotlinx.serialization.Serializable - -/** - * Checks whether the app's `kotlinx-serialization-core` version successfully links against the APIs - * used by [KotlinxBackStackEntryMapper]. It does so via two built-in probe types ([ProbeClass] and - * [ProbeObject]). - * - * **Disambiguating serializer errors from library incompatibility** - * - * Without a check like this, `KotlinxBackStackEntryMapper` would have to infer an incompatible - * `kotlinx-serialization-core` version from [LinkageError]s thrown while handling the host app's - * own back stack entry types. But such errors can also come from the host app's serializer code, - * and should therefore only fail for the entry types that can't be deserialized. `ProbeClass` and - * `ProbeObject` don't execute any host app code, so a `LinkageError` while handling them means the - * app's `kotlinx-serialization-core` version is incompatible. - * - * Note: Only a `LinkageError` is conclusive, including one that reflection wrapped in an - * [InvocationTargetException] because a probe type's serializer threw it. Any other failure, or a - * probe type whose serializer can't be found, is ambiguous: it's reported to the caller's - * `onInconclusive` and otherwise ignored, as a real type that hits the same failure is handled and - * logged on its own. - */ -internal object KotlinxCompatibilityProbe { - - /** - * Checks `kotlinx-serialization-core` compatibility by retrieving serializers for [ProbeClass] - * and [ProbeObject] through [lookUpSerializer] and reading their serial names. - * - * Confines itself to methods used by our built-in [BackStackEntryMapper]s to avoid being disabled - * by incompatibilities from irrelevant APIs. - * - * Returns a [LinkageError] upon incompatibility, or `null` upon success or an inconclusive - * result. Additionally reports inconclusive results through [onInconclusive], passing the cause - * or `null` if a serializer is unavailable. - */ - fun nameLookupLinkageError( - lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, - onInconclusive: (Throwable?) -> Unit, - ): LinkageError? { - var isSerializerMissing = false - - val error = - probe(onInconclusive) { - for (type in listOf(ProbeClass::class.java, ProbeObject::class.java)) { - val descriptor = lookUpSerializer(type)?.descriptor - if (descriptor == null) { - isSerializerMissing = true - } else { - descriptor.serialName - } - } - } - - // Call outside probe() so an exception from onInconclusive isn't caught and reported back to - // the same callback. If a serializer is missing, the remaining lookup steps cannot be checked - // for that type. - if (isSerializerMissing) { - onInconclusive(null) - } - return error - } - - /** - * Runs [check], returning any [LinkageError] and rethrowing fatal errors. Returns `null` if the - * check succeeds or is inconclusive. - * - * Reports other errors to [onInconclusive], passing the cause. - */ - private inline fun probe( - onInconclusive: (Throwable) -> Unit, - check: () -> Unit, - ): LinkageError? = - try { - check() - null - } catch (e: LinkageError) { - e - } catch (e: InvocationTargetException) { - // A probe type's serializer runs only SDK and kotlinx.serialization code, so a LinkageError - // it throws means the library is incompatible. (The lookup keeps such errors wrapped, as an - // app type's serializer could throw them for unrelated reasons.) - val cause = e.cause - if (cause is LinkageError) { - cause - } else { - val error = cause ?: e - ExceptionUtils.rethrowIfFatal(error) - onInconclusive(error) - null - } - } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { - // Broad because the app's kotlinx.serialization version may throw anything. Only - // LinkageError confirms incompatibility. Other non-fatal failures are inconclusive. - // Failures for actual back stack types are handled and logged per type. - ExceptionUtils.rethrowIfFatal(t) - onInconclusive(t) - null - } - - /** - * A known serializable type used to test whether the app's kotlinx.serialization version supports - * serializer lookup, without running host app code. - * - * Internal visibility lets the probe look up its serializer the same way - * [KotlinxBackStackEntryMapper] looks up serializers for the host app's public back stack entry - * types. - */ - @Serializable internal data class ProbeClass(val name: String = "probe") - - /** - * A known serializable object used to test serializer lookup for the host app's object-based back - * stack entries. This lookup reads the object's singleton instance. - */ - @Serializable internal object ProbeObject -} - -/** - * Checks whether the app's `kotlinx-serialization-core` version supports retrieving serializers and - * reading their serial names. Returns a [LinkageError] for incompatibility, or `null` for success - * or an inconclusive check. - * - * Reports inconclusive results through `onInconclusive`, passing the error or `null` if a - * serializer couldn't be found. - */ -internal typealias CompatibilityProbe = (onInconclusive: (Throwable?) -> Unit) -> LinkageError? diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt index 310007c04e5..919c915535c 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -1,6 +1,5 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx -import io.sentry.util.ExceptionUtils import java.lang.reflect.InvocationTargetException import kotlinx.serialization.KSerializer import kotlinx.serialization.serializerOrNull @@ -10,32 +9,24 @@ import kotlinx.serialization.serializerOrNull * Extends [serializerOrNull] to support private `@Serializable` objects. Also supports built-in * types and unannotated enums. * - * May execute serializer code and throw. Unwraps fatal causes such as [OutOfMemoryError] from - * [InvocationTargetException] so that fatal-error checks can recognize them. Keeps [LinkageError] - * causes wrapped because they affect only this type. + * May execute serializer code and throw. What that code throws through reflection, including fatal + * errors such as [OutOfMemoryError], arrives wrapped in an [InvocationTargetException]. */ @Suppress("SwallowedException") internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = try { - try { - serializerOrNull(type) - } catch (_: IllegalAccessException) { - // kotlinx.serialization reads a serializable object's INSTANCE field without making it - // accessible, which will fail for private objects. - privateObjectSerializerOrNull(type) - } - } catch (e: InvocationTargetException) { - val cause = e.cause - if (cause != null && cause !is LinkageError) { - ExceptionUtils.rethrowIfFatal(cause) - } - throw e + serializerOrNull(type) + } catch (_: IllegalAccessException) { + // kotlinx.serialization reads a serializable object's INSTANCE field without making it + // accessible, which will fail for private objects. + privateObjectSerializerOrNull(type) } /** * Uses reflection to look up the serializer of a private `@Serializable object` through the members * the serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules - * keep both members.) + * keep both members.) kotlinx.serialization's own object lookup reads the same two members, so this + * fallback can break only if that lookup breaks too. * * Propagates any exception thrown by the reflective lookup. */ diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md index ddadd318837..ba524b283c2 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -42,7 +42,7 @@ Recommended rules for raising the floor: - Raise it in a reviewed change of its own, with a CHANGELOG entry and a corresponding update to the [Sentry Nav3 docs](https://docs.sentry.io/platforms/android/integrations/navigation/#navigation-3). -- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `KotlinxBackStackEntryMapper.kt` to match. A unit test will fail if the two differ. +- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `internal/common/KotlinxSerializationSupport.kt` to match. A unit test will fail if the two differ. ## Minification diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md new file mode 100644 index 00000000000..b1eb7e8c1db --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/README.md @@ -0,0 +1,9 @@ +# `io.sentry.compose.navigation3.internal.common` + +Package contains internal code that more than one `io.sentry.compose.navigation3` package needs, but that isn't part of what the Sentry UI +shows (see the `contract` package). + +## Dependencies + +This package may depend only on the `contract` package among `io.sentry.compose.navigation3` packages. As `backstack.kotlinx` depends on it, +it may ***not*** depend on Android, AndroidX, or kotlinx.serialization. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt new file mode 100644 index 00000000000..9326a8a9ff4 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/SerializationCompatibility.kt @@ -0,0 +1,15 @@ +package io.sentry.compose.navigation3.internal.common + +/** + * The oldest kotlinx.serialization version the built-in mappers support. + * + * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. + */ +internal const val MIN_KOTLINX_SERIALIZATION_VERSION = "1.7.3" + +/** Advice logged when the app's kotlinx.serialization version may be incompatible. */ +internal const val INCOMPATIBLE_KOTLINX_ADVICE = + "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + + "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + + "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + + "BackStackEntryMapper as a workaround." diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt new file mode 100644 index 00000000000..d2e97d6f209 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporter.kt @@ -0,0 +1,49 @@ +package io.sentry.compose.navigation3.internal.common + +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason + +/** + * A side channel for built-in `BackStackEntryMapper`s to report [UnknownEntryReason]s for + * "/unknown" entries. + * + * Needed because mappers report failures only by returning `null`, and the + * `BackStackEntryMapper.map()`'s return type is a public API. + * + * **Custom `BackStackEntryMapper`s inherit reasons from any built-in mappers they delegate to** + * + * Built-in mappers [report] reasons before returning `null`. The converter [collect]s the last + * reason reported while the app's mapper runs, and records the reason only if the app's mapper + * returns `null`. As a result, a custom mapper that returns `null` after any built-in mapper + * returned `null` will record the built-in mapper's reason. + * + * Reasons are maintained per thread, so the converter collects only reasons reported on its own + * thread, where it runs the host app's mapper. If a custom mapper calls a built-in mapper on + * another thread, the reason will be lost and the entry will record `unmapped`. + */ +internal object UnknownEntryReasonReporter { + + private val reports = ThreadLocal() + + /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ + fun report(reason: UnknownEntryReason) { + reports.set(reason) + } + + /** + * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none + * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to + * another entry. + */ + fun collect(map: () -> R): Collected { + reports.remove() + try { + val result = map() + return Collected(result, reports.get()) + } finally { + reports.remove() + } + } + + /** What [collect] returns: the mapper's [result] and the [reason] reported while it ran. */ + data class Collected(val result: R, val reason: UnknownEntryReason?) +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md new file mode 100644 index 00000000000..94d7d9d55cc --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/README.md @@ -0,0 +1,8 @@ +# `io.sentry.compose.navigation3.internal.contract` + +Package contains internal values that are effectively part of our public contract because the Sentry UI displays them or they define +observable behavior. + +## Dependencies + +This package may ***not*** depend on any other `io.sentry.compose.navigation3` package, so that every other package can depend on it. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt deleted file mode 100644 index f7954b95866..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporter.kt +++ /dev/null @@ -1,41 +0,0 @@ -package io.sentry.compose.navigation3.internal.contract - -/** - * Passes the [UnknownEntryReason] a built-in mapper knows to the back stack converter, as the - * mapper reports a failure by returning `null`, which is public API. - * - * A built-in mapper [report]s the reason right before returning `null`, and the converter - * [collect]s it around each call to the app's mapper. So a custom mapper that forwards a built-in - * mapper's `null` forwards its reason too, while one that returns `null` itself reports nothing, - * and one that returns a name has its reason ignored. If a custom mapper calls built-in mappers - * several times for one entry, the last reason reported is kept. - * - * Kept per thread, as mappers run on the converter's thread. - */ -internal object UnknownEntryReasonReporter { - - private val reports = ThreadLocal() - - /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ - fun report(reason: UnknownEntryReason) { - reports.set(reason) - } - - /** - * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none - * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to - * another entry. - */ - fun collect(map: () -> R): Collected { - reports.remove() - try { - val result = map() - return Collected(result, reports.get()) - } finally { - reports.remove() - } - } - - /** What [collect] returns: the mapper's [result] and the [reason] reported while it ran. */ - data class Collected(val result: R, val reason: UnknownEntryReason?) -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt index f83a32a9eca..ba5553ac51a 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -102,6 +102,29 @@ class PackageBoundariesTest { assertThat(violations).isEmpty() } + @Test + fun `the common package imports only the contract package from other Sentry navigation3 packages`() { + val commonSources = sources.filter { it.packageName.isIn(COMMON) } + + val violations = commonSources.importsMatching { + it.isIn(ROOT) && !it.isIn(COMMON) && !it.isIn(CONTRACT) + } + + assertThat(commonSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `the common package has no imports from Android or AndroidX`() { + // The kotlinx package, which may not import them, depends on the common package. + val commonSources = sources.filter { it.packageName.isIn(COMMON) } + + val violations = commonSources.importsMatching { it.isIn("android") || it.isIn("androidx") } + + assertThat(commonSources).isNotEmpty() + assertThat(violations).isEmpty() + } + // Check that the import reader finds the declarations the rules inspect. @Test @@ -168,6 +191,7 @@ class PackageBoundariesTest { const val KOTLINX = "$BACKSTACK.kotlinx" const val LIFECYCLE = "$ROOT.internal.lifecycle" const val CONTRACT = "$ROOT.internal.contract" + const val COMMON = "$ROOT.internal.common" const val MAPPER_FACTORY_PATH = "$SOURCE_ROOT/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt" diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index 75dc883540a..6e2e5f7854e 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -10,10 +10,10 @@ import io.sentry.SentryOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import io.sentry.compose.navigation3.internal.contract.UNKNOWN_ENTRY_NAME import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.io.StringWriter import kotlin.test.assertFailsWith import org.junit.Test diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt index 758ce9c864b..92a433e38d6 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -7,9 +7,9 @@ import io.sentry.SentryLevel import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import io.sentry.test.initForTest import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt index c2be6bf0f59..0e2d510e024 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt @@ -3,8 +3,8 @@ package io.sentry.compose.navigation3.internal.backstack import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.eq diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt index 3cad4011b7b..7a71d52b043 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt @@ -4,12 +4,10 @@ import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.backstack.kotlinx.FakeCompatibilityProbe.Inconclusive import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter import java.lang.annotation.AnnotationFormatError import java.lang.reflect.InvocationTargetException import kotlin.test.assertFailsWith @@ -63,55 +61,64 @@ class KotlinxBackStackEntryMapperTest { // Construction @Test - fun `logs nothing when created and the compatibility probe finds kotlinx serialization compatible`() { + fun `logs nothing when created and the compatibility check passes`() { val logger = mock() - KotlinxBackStackEntryMapper(probe = FakeCompatibilityProbe(), logger = { logger }) + KotlinxBackStackEntryMapper(logger = { logger }) verifyNoInteractions(logger) } @Test - fun `fails creation with the LinkageError the compatibility probe returns`() { + fun `fails creation with the LinkageError the compatibility check throws`() { val error = NoSuchMethodError("serializerOrNull") - val probe = FakeCompatibilityProbe(linkageError = error) val thrown = assertFailsWith { - KotlinxBackStackEntryMapper(probe = probe, logger = { mock() }) + KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { mock() }) } assertThat(thrown).isSameInstanceAs(error) } @Test - fun `logs nothing when the compatibility probe returns a LinkageError`() { + fun `logs nothing when the compatibility check throws a LinkageError`() { // BuiltInBackStackEntryMappers logs the error it catches, so the mapper doesn't log it too. val logger = mock() - val probe = FakeCompatibilityProbe(linkageError = NoSuchMethodError()) assertFailsWith { - KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) + KotlinxBackStackEntryMapper( + checkCompatibility = { throw NoSuchMethodError() }, + logger = { logger }, + ) } verifyNoInteractions(logger) } @Test - fun `logs the compatibility probe's error at debug level when the probe is inconclusive`() { - val error = IllegalStateException("probe failed") + fun `logs an IllegalArgumentException the compatibility check throws at debug level`() { + val error = IllegalArgumentException("lookup failed") + val logger = mock() + + KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { logger }) + + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any()) + } + + @Test + fun `logs an IllegalStateException the compatibility check throws at debug level`() { + val error = IllegalStateException("lookup failed") val logger = mock() - val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(error)) - KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) + KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { logger }) - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any(), eq(PROBE_THREW)) + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any()) } @Test - fun `names entries when the compatibility probe is inconclusive`() { - val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(IllegalStateException())) - val fixture = Fixture.create(probe = probe) + fun `names entries when the compatibility check throws an IllegalStateException`() { + val fixture = Fixture.create(checkLinkage = { throw IllegalStateException() }) val mapper = fixture.mapper val mapped = mapper.map(Detail("1")) @@ -119,6 +126,18 @@ class KotlinxBackStackEntryMapperTest { assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) } + @Test + fun `fails creation with another exception the compatibility check throws`() { + val error = UnsupportedOperationException() + + val thrown = + assertFailsWith { + KotlinxBackStackEntryMapper(checkCompatibility = { throw error }, logger = { mock() }) + } + + assertThat(thrown).isSameInstanceAs(error) + } + // Naming @Test @@ -335,8 +354,8 @@ class KotlinxBackStackEntryMapperTest { } @Test - fun `returns null and logs the cause when the serializer lookup throws a wrapped fatal error`() { - val cause = OutOfMemoryError("serializer() failed fatally") + fun `returns null and logs the cause when the serializer lookup throws a wrapped LinkageError`() { + val cause = NoSuchMethodError("serializer() failed to link") val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) val mapper = fixture.mapper @@ -346,6 +365,49 @@ class KotlinxBackStackEntryMapperTest { verifyLookUpFailureLogged(fixture.logger, cause) } + @Test + fun `propagates a wrapped fatal error the serializer lookup throws, unwrapped`() { + val cause = OutOfMemoryError("serializer() failed fatally") + val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(cause) + } + + @Test + fun `propagates a wrapped fatal error the serializer's descriptor throws, unwrapped`() { + val cause = OutOfMemoryError("descriptor failed fatally") + val serializer = + object : NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = throw InvocationTargetException(cause) + } + val fixture = Fixture.create(lookUpSerializer = { serializer }) + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(cause) + } + + @Test + fun `restores the interrupt flag when the serializer lookup throws a wrapped InterruptedException`() { + val fixture = + Fixture.create(lookUpSerializer = { throw InvocationTargetException(InterruptedException()) }) + val mapper = fixture.mapper + + try { + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + assertThat(Thread.currentThread().isInterrupted).isTrue() + } finally { + Thread.interrupted() + } + } + @Test fun `returns null and logs the InvocationTargetException when the serializer lookup throws one without a cause`() { val error = InvocationTargetException(null) @@ -496,6 +558,57 @@ class KotlinxBackStackEntryMapperTest { assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) } + @Test + fun `looks up a type's serializer again after the serializer lookup is interrupted`() { + var hasThrown = false + val fixture = + Fixture.create( + lookUpSerializer = { + if (!hasThrown) { + hasThrown = true + throw InvocationTargetException(InterruptedException()) + } + Detail.serializer() + }, + ) + val mapper = fixture.mapper + try { + assertThat(mapper.map(Detail("1"))).isNull() + } finally { + Thread.interrupted() + } + + val mapped = mapper.map(Detail("2")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java, Detail::class.java) + } + + @Test + fun `checks a type's annotation again after the annotation check is interrupted`() { + var hasThrown = false + val fixture = + Fixture.create( + isAnnotatedSerializable = { + if (!hasThrown) { + hasThrown = true + throw InterruptedException() + } + true + }, + ) + val mapper = fixture.mapper + try { + assertThat(mapper.map(Detail("1"))).isNull() + } finally { + Thread.interrupted() + } + + val mapped = mapper.map(Detail("2")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + } + @Test fun `logs each type that isn't annotated @Serializable once`() { val fixture = Fixture.create() @@ -733,7 +846,7 @@ class KotlinxBackStackEntryMapperTest { private constructor( lookUpSerializer: (Class<*>) -> KSerializer<*>?, isAnnotatedSerializable: ((Class<*>) -> Boolean)?, - probe: CompatibilityProbe, + checkLinkage: () -> Unit, ) { val logger = mock() val lookedUpTypes = mutableListOf>() @@ -746,9 +859,18 @@ class KotlinxBackStackEntryMapperTest { } mapper = if (isAnnotatedSerializable == null) { - KotlinxBackStackEntryMapper(recordingLookUp, probe = probe, logger = { logger }) + KotlinxBackStackEntryMapper( + recordingLookUp, + checkCompatibility = checkLinkage, + logger = { logger }, + ) } else { - KotlinxBackStackEntryMapper(recordingLookUp, isAnnotatedSerializable, probe, { logger }) + KotlinxBackStackEntryMapper( + recordingLookUp, + isAnnotatedSerializable, + checkLinkage, + { logger }, + ) } } @@ -756,8 +878,8 @@ class KotlinxBackStackEntryMapperTest { fun create( lookUpSerializer: (Class<*>) -> KSerializer<*>? = { SERIALIZERS[it] }, isAnnotatedSerializable: ((Class<*>) -> Boolean)? = null, - probe: CompatibilityProbe = FakeCompatibilityProbe(), - ) = Fixture(lookUpSerializer, isAnnotatedSerializable, probe) + checkLinkage: () -> Unit = {}, + ) = Fixture(lookUpSerializer, isAnnotatedSerializable, checkLinkage) } } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt new file mode 100644 index 00000000000..5e64aeefd3b --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityCheckTest.kt @@ -0,0 +1,63 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import kotlin.test.assertFailsWith +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Test +import org.mockito.kotlin.doThrow +import org.mockito.kotlin.mock + +/** + * Runs the default check against the kotlinx.serialization version on the test classpath, which CI + * also sets to the latest stable release with `-Pnav3TestKotlinx=latestStable`. + */ +class KotlinxCompatibilityCheckTest { + + @Test + fun `checkKotlinxCompatibility() - succeeds for the kotlinx serialization version on the classpath`() { + checkKotlinxCompatibility() + } + + @Test + fun `checkKotlinxCompatibility() - looks up only the built-in String serializer`() { + val lookedUpTypes = mutableListOf>() + + checkKotlinxCompatibility { type -> + lookedUpTypes += type + String.serializer() + } + + assertThat(lookedUpTypes).containsExactly(String::class.java) + } + + @Test + fun `checkKotlinxCompatibility() - throws the LinkageError the serializer lookup throws`() { + val error = NoSuchMethodError("serializerOrNull") + + val thrown = assertFailsWith { checkKotlinxCompatibility { throw error } } + + assertThat(thrown).isSameInstanceAs(error) + } + + @OptIn(ExperimentalSerializationApi::class) + @Test + fun `checkKotlinxCompatibility() - throws the LinkageError reading the serial name throws`() { + val error = NoSuchMethodError("getSerialName") + val descriptor = mock { on { serialName } doThrow error } + val serializer = + object : NamingOnlySerializer() { + override val descriptor = descriptor + } + + val thrown = assertFailsWith { checkKotlinxCompatibility { serializer } } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `checkKotlinxCompatibility() - succeeds without reading a serial name when no serializer is found`() { + checkKotlinxCompatibility { null } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt deleted file mode 100644 index 53e3e06f837..00000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt +++ /dev/null @@ -1,172 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack.kotlinx - -import com.google.common.truth.Truth.assertThat -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.ProbeClass -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.ProbeObject -import java.lang.reflect.InvocationTargetException -import kotlin.test.assertFailsWith -import org.junit.Test - -/** - * Runs the default probe against the kotlinx.serialization version on the test classpath, which CI - * also sets to the latest stable release with `-Pnav3TestKotlinx=latestStable`. - */ -class KotlinxCompatibilityProbeTest { - - // nameLookupLinkageError() - - @Test - fun `nameLookupLinkageError() - returns null without an inconclusive result for a compatible version`() { - val inconclusive = mutableListOf() - - val error = KotlinxCompatibilityProbe.nameLookupLinkageError { inconclusive += it } - - assertThat(error).isNull() - assertThat(inconclusive).isEmpty() - } - - @Test - fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer lookup throws`() { - val error = NoSuchMethodError("serializerOrNull") - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } - - assertThat(returned).isSameInstanceAs(error) - assertThat(inconclusive).isEmpty() - } - - @Test - fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer throws through reflection`() { - val error = NoSuchMethodError("PluginGeneratedSerialDescriptor") - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw InvocationTargetException(error) }) { - inconclusive += it - } - - assertThat(returned).isSameInstanceAs(error) - assertThat(inconclusive).isEmpty() - } - - @Test - fun `nameLookupLinkageError() - reports another error a probe serializer throws via reflection as inconclusive`() { - val error = IllegalStateException("serializer failed") - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw InvocationTargetException(error) }) { - inconclusive += it - } - - assertThat(returned).isNull() - assertThat(inconclusive).containsExactly(error) - } - - @Test - fun `nameLookupLinkageError() - propagates a fatal error a probe type's serializer throws through reflection`() { - val error = OutOfMemoryError() - - val thrown = - assertFailsWith { - KotlinxCompatibilityProbe.nameLookupLinkageError( - { - throw InvocationTargetException(error) - }, - ) {} - } - - assertThat(thrown).isSameInstanceAs(error) - } - - @Test - fun `nameLookupLinkageError() - reports a non-fatal exception as inconclusive and returns null`() { - val error = IllegalStateException("lookup failed") - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } - - assertThat(returned).isNull() - assertThat(inconclusive).containsExactly(error) - } - - @Test - fun `nameLookupLinkageError() - propagates a fatal error that isn't a LinkageError`() { - val error = OutOfMemoryError() - - val thrown = - assertFailsWith { - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) {} - } - - assertThat(thrown).isSameInstanceAs(error) - } - - @Test - fun `nameLookupLinkageError() - reports a missing probe serializer as inconclusive without an error`() { - val inconclusive = mutableListOf() - - val returned = - KotlinxCompatibilityProbe.nameLookupLinkageError( - { type -> if (type == ProbeObject::class.java) null else reflectiveSerializerOrNull(type) }, - ) { - inconclusive += it - } - - assertThat(returned).isNull() - assertThat(inconclusive).containsExactly(null) - } - - @Test - fun `nameLookupLinkageError() - doesn't re-report onInconclusive's exception for a missing probe serializer`() { - val error = IllegalStateException("callback failed") - val inconclusive = mutableListOf() - - val thrown = - assertFailsWith { - KotlinxCompatibilityProbe.nameLookupLinkageError({ null }) { - inconclusive += it - throw error - } - } - - assertThat(thrown).isSameInstanceAs(error) - assertThat(inconclusive).containsExactly(null) - } - - @Test - fun `nameLookupLinkageError() - doesn't re-report onInconclusive's exception for a lookup exception`() { - val lookupError = IllegalStateException("lookup failed") - val callbackError = IllegalArgumentException("callback failed") - val inconclusive = mutableListOf() - - val thrown = - assertFailsWith { - KotlinxCompatibilityProbe.nameLookupLinkageError({ throw lookupError }) { - inconclusive += it - throw callbackError - } - } - - assertThat(thrown).isSameInstanceAs(callbackError) - assertThat(inconclusive).containsExactly(lookupError) - } - - // Probe types - - @Test - fun `the serializer lookup names the probe's types`() { - // A probe type the lookup couldn't find would make the check pass without looking up a name. - val names = - listOf(ProbeClass::class.java, ProbeObject::class.java).map { - reflectiveSerializerOrNull(it)?.descriptor?.serialName - } - - assertThat(names) - .containsExactly(ProbeClass::class.qualifiedName, ProbeObject::class.qualifiedName) - .inOrder() - } -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt index a72868dd03f..b500c609c3c 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt @@ -3,16 +3,13 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx import com.google.common.truth.Truth.assertThat import io.sentry.ILogger import io.sentry.SentryLevel -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.MIN_KOTLINX_SERIALIZATION_VERSION -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_SERIALIZER_NOT_FOUND -import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.common.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.common.MIN_KOTLINX_SERIALIZATION_VERSION import org.junit.Test import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.eq -import org.mockito.kotlin.isNull import org.mockito.kotlin.mock import org.mockito.kotlin.verify @@ -47,34 +44,18 @@ class KotlinxMapperDiagnosticsTest { assertThat(message.firstValue).contains("Use a custom BackStackEntryMapper") } - // inconclusiveProbe() + // compatibilityCheckFailed() @Test - fun `inconclusiveProbe() - logs the error at debug level with the reason that the probe threw`() { - val error = IllegalStateException("probe failed") - - diagnostics.inconclusiveProbe(error) - - val message = argumentCaptor() - verify(logger).log(eq(SentryLevel.DEBUG), eq(error), message.capture(), eq(PROBE_THREW)) - assertThat(message.firstValue) - .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") - } + fun `compatibilityCheckFailed() - logs the error at debug level`() { + val error = IllegalStateException("lookup failed") - @Test - fun `inconclusiveProbe() - logs at debug level that no probe serializer was found when there's no error`() { - diagnostics.inconclusiveProbe(null) + diagnostics.compatibilityCheckFailed(error) val message = argumentCaptor() - verify(logger) - .log( - eq(SentryLevel.DEBUG), - isNull(), - message.capture(), - eq(PROBE_SERIALIZER_NOT_FOUND), - ) + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), message.capture()) assertThat(message.firstValue) - .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") + .startsWith("Nav3 couldn't verify kotlinx.serialization compatibility") } // unresolved() diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt index bb3b036ed79..a2c998a76cd 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt @@ -8,6 +8,7 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.serializerOrNull import org.junit.Test class KotlinxSerializerLookupTest { @@ -214,6 +215,16 @@ class KotlinxSerializerLookupTest { assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateObject") } + /** + * Fails once a kotlinx.serialization release can look up a private object's serializer itself, + * e.g., when CI runs the latest stable release. The private object fallback can then be removed + * once `kotlinxSerialization-floor` reaches that release. + */ + @Test + fun `kotlinx serialization's own lookup still throws IllegalAccessException for a private object`() { + assertFailsWith { serializerOrNull(PrivateObject::class.java) } + } + @Test fun `returns the serializer of a private @Serializable class`() { val serializer = reflectiveSerializerOrNull(PrivateClass::class.java) @@ -325,38 +336,38 @@ class KotlinxSerializerLookupTest { } @Test - fun `restores the interrupt flag when a class's serializer construction is interrupted`() { - try { - val thrown = - assertFailsWith { - reflectiveSerializerOrNull(InterruptedConstruction::class.java) - } - - assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) - assertThat(Thread.currentThread().isInterrupted).isTrue() - } finally { - Thread.interrupted() - } + fun `throws an interruption of a class's serializer construction wrapped in an InvocationTargetException`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(InterruptedConstruction::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) } @Test - fun `propagates a class's fatal serializer initializer error unwrapped`() { + fun `throws a class's fatal serializer initializer error wrapped in an InvocationTargetException`() { val thrown = - assertFailsWith { + assertFailsWith { reflectiveSerializerOrNull(FatallyUninitializable::class.java) } - assertThat(thrown).hasMessageThat().isEqualTo("class serializer init failed fatally") + assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("class serializer init failed fatally") } @Test - fun `propagates a private object's fatal serializer initializer error unwrapped`() { + fun `throws a private object's fatal serializer initializer error wrapped in an InvocationTargetException`() { val thrown = - assertFailsWith { + assertFailsWith { reflectiveSerializerOrNull(PrivateFatal::class.java) } - assertThat(thrown).hasMessageThat().isEqualTo("serializer init failed fatally") + assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed fatally") } // Private object lookups that find no serializer diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt index 1a1339a038c..d06ebe92abb 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -20,24 +20,3 @@ internal abstract class NamingOnlySerializer : KSerializer { override fun deserialize(decoder: Decoder): T = throw UnsupportedOperationException() } - -/** - * A compatibility probe that finds kotlinx.serialization compatible by default. Set [linkageError] - * to report an incompatible version, or [inconclusive] to report an inconclusive result. - */ -internal class FakeCompatibilityProbe( - private val linkageError: LinkageError? = null, - private val inconclusive: Inconclusive? = null, -) : CompatibilityProbe { - - override fun invoke(onInconclusive: (Throwable?) -> Unit): LinkageError? { - linkageError?.let { - return it - } - inconclusive?.let { onInconclusive(it.error) } - return null - } - - /** Why the probe is inconclusive: [error], or `null` if a probe serializer wasn't found. */ - class Inconclusive(val error: Throwable?) -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt similarity index 95% rename from sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt rename to sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt index eea71458579..7c19e9e70c9 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/common/UnknownEntryReasonReporterTest.kt @@ -1,7 +1,8 @@ -package io.sentry.compose.navigation3.internal.contract +package io.sentry.compose.navigation3.internal.common import com.google.common.truth.Truth.assertThat -import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter.Collected +import io.sentry.compose.navigation3.internal.common.UnknownEntryReasonReporter.Collected +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReason import kotlin.concurrent.thread import kotlin.test.assertFailsWith import org.junit.Test