From 1765464abba872413a4bc45d8c1a9f83c6a4b082 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 27 Nov 2026 16:07:36 +0100 Subject: [PATCH] feat(nav3): Add the SerialName back stack mapper BackStackEntryMapper.SerialName names each back stack entry after its kotlinx.serialization serial name, which R8 doesn't obfuscate, and records no properties. kotlinx-serialization-core is a compileOnly dependency at 1.7.3 or later. If the app's version can't be linked, the mapper falls back to naming every entry /unknown. The mapper returns null, which is public API, for entries it can't name, so it reports why through an internal per-thread side channel that the converter reads around each mapping call. Its reasons are entry_not_annotated, generic_entry_type, serializer_not_found, serializer_access_threw, and kotlinx_serialization_version. Unit tests run against the 1.7.3 floor by default, and against the latest stable release with -Pnav3TestKotlinx=latestStable. --- CHANGELOG.md | 4 + gradle/dependency-matrix.versions.toml | 60 ++ gradle/libs.versions.toml | 1 + sentry-android-navigation3/README.md | 5 +- .../api/sentry-android-navigation3.api | 5 + sentry-android-navigation3/build.gradle.kts | 22 +- sentry-android-navigation3/proguard-rules.pro | 26 + .../navigation3/BackStackEntryMapper.kt | 240 +++--- .../compose/navigation3/SentryNavEffect.kt | 4 +- .../internal/backstack/BackStackConverter.kt | 9 +- .../backstack/BuiltInBackStackEntryMappers.kt | 131 +++ .../ForwardingBackStackEntryMapper.kt | 26 - .../navigation3/internal/backstack/README.md | 23 +- .../kotlinx/KotlinxBackStackEntryMapper.kt | 320 ++++++++ .../kotlinx/KotlinxCompatibilityProbe.kt | 134 +++ .../kotlinx/KotlinxSerializerLookup.kt | 46 ++ .../internal/backstack/kotlinx/README.md | 58 ++ .../internal/contract/NavDataContract.kt | 47 +- .../contract/UnknownEntryReasonReporter.kt | 41 + .../navigation3/BackStackEntryMapperTest.kt | 17 + .../navigation3/PackageBoundariesTest.kt | 60 ++ .../navigation3/SentryNavEffectTest.kt | 43 + .../backstack/BackStackConverterTest.kt | 78 +- .../BuiltInBackStackEntryMappersTest.kt | 321 ++++++++ .../DeferredBackStackEntryMapperTest.kt | 88 ++ .../UnavailableBackStackEntryMapperTest.kt | 59 ++ .../KotlinxBackStackEntryMapperTest.kt | 763 ++++++++++++++++++ .../kotlinx/KotlinxCompatibilityProbeTest.kt | 172 ++++ .../kotlinx/KotlinxMapperDiagnosticsTest.kt | 151 ++++ .../kotlinx/KotlinxSerializerLookupTest.kt | 380 +++++++++ .../backstack/kotlinx/KotlinxTestEntries.kt | 43 + .../internal/contract/NavDataContractTest.kt | 10 + .../UnknownEntryReasonReporterTest.kt | 97 +++ settings.gradle.kts | 5 + 34 files changed, 3329 insertions(+), 160 deletions(-) create mode 100644 gradle/dependency-matrix.versions.toml create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapper.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt create 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/backstack/kotlinx/KotlinxSerializerLookup.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md create 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/BackStackEntryMapperTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/DeferredBackStackEntryMapperTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 8150cf12465..9868074937a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ ## Unreleased +### Features + +- Nav3: Add `BackStackEntryMapper.SerialName`, a convenience mapper that names back stack entries after their [serial names](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.descriptors/-serial-descriptor/serial-name.html) ([#6703](https://github.com/getsentry/sentry-java/pull/6703)) + ### Improvements - Nav3: Record why a back stack entry is `/unknown` via an `unknown_entry_reason` next to it in the Sentry UI ([#6801](https://github.com/getsentry/sentry-java/pull/6801)) diff --git a/gradle/dependency-matrix.versions.toml b/gradle/dependency-matrix.versions.toml new file mode 100644 index 00000000000..5fc8c4a25d6 --- /dev/null +++ b/gradle/dependency-matrix.versions.toml @@ -0,0 +1,60 @@ +# Dependency matrices that let builds compile against a stable oldest supported version, while testing +# against that version and newer, automatically-updating releases. Helps ensure our source code only uses +# APIs available in the oldest supported version, while remaining compatible with subsequent releases. +# +# Each matrix defines two `[versions]`: +# +# - -floor: The oldest supported version. Only changed manually via a reviewed PR. +# Should not be referenced by any `version.ref` so that Dependabot leaves it alone. Instead, +# build files should apply it explicitly, e.g., with `version { strictly(...) }`. +# +# - -latestStable: The latest stable release. An unused -latestStable entry in `[libraries]` +# should point to the -latestStable key so that Dependabot can update it. Build files can +# select between floor and latestStable. +# +# An example: +# +# // In dependency-matrix.versions.toml +# [versions] +# example-floor = "1.0.0" +# example-latestStable = "1.5.0" +# +# [libraries] +# example-core = { module = "com.example:core" } +# example-latestStable = { module = "com.example:core", version.ref = "example-latestStable" } +# +# // In build.gradle.kts +# val testVersion = +# // CI, etc. can use -PtestExample= to set the desired version. +# when (providers.gradleProperty("testExample").getOrElse("floor")) { +# "floor" -> matrixLibs.versions.example.floor.get() +# "latestStable" -> matrixLibs.versions.example.latestStable.get() +# else -> error("testExample must be floor or latestStable") +# } +# +# dependencies { +# testImplementation(matrixLibs.example.core) { +# version { strictly(testVersion) } +# } +# } +# +# Additional rules: +# +# - Never give the floor key a library entry with `version.ref`, and never protect it with a +# Dependabot `ignore` rule. Ignore rules match a dependency's group and name, so they'd also +# prevent Dependabot from bumping -latestStable. +# +# - A latestStable library entry mustn't share its module with any entry or build file declaration that +# Dependabot also updates (e.g., in libs.versions.toml). Dependabot merges declarations of one +# module and bumps them all to one version. If they would collide, track a sibling artifact +# instead (e.g., `-jvm`). + +[versions] +# The oldest kotlinx.serialization version sentry-android-navigation3 supports. Before changing it, read the rules under "Version floor" in +# that module's .kotlinx package README. +kotlinxSerialization-floor = "1.7.3" +kotlinxSerialization-latestStable = "1.13.0" + +[libraries] +kotlinxSerialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core" } +kotlinxSerialization-latestStable = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinxSerialization-latestStable" } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e7ab038d9d6..40a24fab5c7 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -70,6 +70,7 @@ kotlin-spring = { id = "org.jetbrains.kotlin.plugin.spring", version.ref = "kotl kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } buildconfig = { id = "com.github.gmazzo.buildconfig", version = "5.6.5" } dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } diff --git a/sentry-android-navigation3/README.md b/sentry-android-navigation3/README.md index 95bbbeb006b..5b80d74bd91 100644 --- a/sentry-android-navigation3/README.md +++ b/sentry-android-navigation3/README.md @@ -5,8 +5,11 @@ Use `SentryNavEffect` alongside your `NavDisplay` to record navigation transactions, breadcrumbs, screen names, and back stack context as users move around your app. Configure the data you want captured via `SentryNavOptions`. +This module requires Nav3. It doesn't declare its own dependencies on Compose, lifecycle, or kotlinx.serialization, but uses the versions +your Nav3 dependency brings in. + Because Nav3 back stacks can have arbitrary key types, host apps need to provide `SentryNavEffect` with a mapping between their back stack -keys and the data Sentry should display for each (see `BackStackEntryMapper`). +keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` mapper). See the [Navigation for Android docs](https://docs.sentry.io/platforms/android/integrations/navigation/) for additional details, including configuration, supported setups, and limitations. diff --git a/sentry-android-navigation3/api/sentry-android-navigation3.api b/sentry-android-navigation3/api/sentry-android-navigation3.api index 45f0482ed82..04c3349cd46 100644 --- a/sentry-android-navigation3/api/sentry-android-navigation3.api +++ b/sentry-android-navigation3/api/sentry-android-navigation3.api @@ -1,7 +1,12 @@ public abstract interface class io/sentry/compose/navigation3/BackStackEntryMapper { + public static final field Companion Lio/sentry/compose/navigation3/BackStackEntryMapper$Companion; public abstract fun map (Ljava/lang/Object;)Lio/sentry/compose/navigation3/SentryBackStackEntry; } +public final class io/sentry/compose/navigation3/BackStackEntryMapper$Companion { + public final fun getSerialName ()Lio/sentry/compose/navigation3/BackStackEntryMapper; +} + public final class io/sentry/compose/navigation3/BuildConfig { public static final field BUILD_TYPE Ljava/lang/String; public static final field DEBUG Z diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index 7a6cf51d181..e57e96a9fa7 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -7,6 +7,7 @@ plugins { alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.compose) alias(libs.plugins.gradle.versions) + alias(libs.plugins.kotlin.serialization) id("io.sentry.detekt") id("io.sentry.spotless") id("io.sentry.jdk-target") @@ -15,6 +16,8 @@ plugins { id("io.sentry.robolectric") } +val kotlinxSerializationFloor = matrixLibs.versions.kotlinxSerialization.floor.get() + android { compileSdk = libs.versions.compileSdk.get().toInt() namespace = "io.sentry.compose.navigation3" @@ -45,6 +48,8 @@ android { // AGP 9.5 can't create the Compose Preview task without it, which breaks any // build that creates every task, such as an LSP's Gradle import. isIncludeAndroidResources = true + // Lets tests check that MIN_KOTLINX_SERIALIZATION_VERSION matches the catalog's floor. + all { it.systemProperty("nav3.kotlinxSerializationFloor", kotlinxSerializationFloor) } } } @@ -72,12 +77,24 @@ android { kotlin { explicitApi() } +// Unit tests run against the kotlinx.serialization floor by default. CI also runs them against the +// latest stable release, as apps may ship a newer kotlinx.serialization dependency. +val testKotlinxVersion = + when (val selection = providers.gradleProperty("nav3TestKotlinx").getOrElse("floor")) { + "floor" -> kotlinxSerializationFloor + "latestStable" -> matrixLibs.versions.kotlinxSerialization.latestStable.get() + else -> error("nav3TestKotlinx must be floor or latestStable, but was $selection.") + } + dependencies { implementation(projects.sentry) - compileOnly(libs.androidx.lifecycle.runtime.compose) compileOnly(libs.androidx.compose.runtime) compileOnly(libs.androidx.compose.ui) + compileOnly(libs.androidx.lifecycle.runtime.compose) + compileOnly(matrixLibs.kotlinxSerialization.core) { + version { strictly(kotlinxSerializationFloor) } + } testImplementation(projects.sentryAndroidCore) testImplementation(projects.sentryTestSupport) @@ -91,6 +108,9 @@ dependencies { testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) testImplementation(libs.roboelectric) + testImplementation(matrixLibs.kotlinxSerialization.core) { + version { strictly(testKotlinxVersion) } + } } tasks.withType().configureEach { diff --git a/sentry-android-navigation3/proguard-rules.pro b/sentry-android-navigation3/proguard-rules.pro index 244282115a5..d9de2ff242b 100644 --- a/sentry-android-navigation3/proguard-rules.pro +++ b/sentry-android-navigation3/proguard-rules.pro @@ -5,3 +5,29 @@ -keepattributes LineNumberTable,SourceFile ##---------------End: proguard configuration for Compose ---------- + +##---------------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. + +# We don't ship rules for `@Serializable` classes with named companion objects. kotlinx.serialization's rules cover them but only from +# 1.10.0 on. A generic rule set that fixes older versions exists, but we don't apply it because it would keep `InnerClasses` and +# named-companion class names in every host app. + +# We don't include a -dontwarn rule for kotlinx.serialization even though it's a compileOnly dependency. The only apps potentially affected +# are those that use sentry-android-navigation3 but not Nav3 (which brings in kotlinx-serialization-core via navigation3-runtime). Adding a +# broad `-dontwarn kotlinx.serialization.**` rule could suppress legitimate – and unrelated – R8 missing-class errors for apps that use +# Nav3, causing them to crash at runtime rather than fail at buildtime. Apps that need the -dontwarn rule (likely the null set) can add it +# themselves. + +##---------------End: proguard configuration for kotlinx.serialization ---------- 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 057fb6d83da..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 @@ -1,74 +1,29 @@ package io.sentry.compose.navigation3 +import io.sentry.compose.navigation3.internal.backstack.BuiltInBackStackEntryMappers import org.jetbrains.annotations.ApiStatus -/** Info about a given back stack entry, suitable for display in Sentry. */ -@ApiStatus.Experimental -public class SentryBackStackEntry( - /** - * A host-app defined name for a given back stack entry. - * - * Sentry interprets the name as a navigation destination. For instance, the following - * `SentryBackStackEntry` instances: - * ```kotlin - * SentryBackStackEntry(name = "Home") - * SentryBackStackEntry(name = "ProductDetail", arguments = mapOf("product_id" to 1234)) - * ``` - * - * will produce a breadcrumb like this: - * ```json - * { - * "from": "/Home", - * "to": "/ProductDetail", - * "to_arguments": { - * "product_id": 1234 - * } - * } - * ``` - * - * Note that the Sentry SDK normalizes `name` to include a "/" prefix. - */ - public val name: String, - /** - * Arguments from a given back stack entry, as selected by the host app. - * - * Useful for capturing any properties in the back stack key that have diagnostic value. - * - * Sentry treats these as metadata to be displayed alongside [name] in appropriate contexts. (See - * the `name` KDoc for an example.) - */ - public val arguments: Map? = null, -) { - - override fun equals(other: Any?): Boolean = - this === other || - (other is SentryBackStackEntry && name == other.name && arguments == other.arguments) - - override fun hashCode(): Int = 31 * name.hashCode() + (arguments?.hashCode() ?: 0) - - /** Omits arguments because they may contain sensitive host-app data. */ - override fun toString(): String = "SentryBackStackEntry(name=$name)" -} - /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * To be implemented by the host app. + * 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** * - * Values returned from [map] are ***not*** scrubbed by the Sentry SDK before being sent to Sentry. - * Only return names and arguments that are known to be safe or have been pre-scrubbed. + * Host apps are responsible for filtering their own arguments, including removing any sensitive or + * personal information. Only return names and arguments that are known to be safe or have been + * pre-scrubbed. * * **Performance** * - * This mapper is invoked synchronously from [SentryNavEffect] on the same apply thread that runs - * the effect. Avoid non-performant mappings. + * Mappers are invoked synchronously from [SentryNavEffect] on the same apply thread that runs the + * effect. Avoid non-performant mappings. * * **Choosing appropriate names** * - * Return stable, low-cardinality names that don't depend on object identity, argument values, or - * runtime class-name preservation. E.g., `Home`, `DetailScreen`, etc. + * Return stable, low-cardinality names (e.g., `Home`, `DetailScreen`, etc.) that don't depend on + * object identity, argument values, or runtime class-name preservation. * * In particular, avoid `::class.simpleName`, as R8 obfuscates class names and may associate them * with different symbols across builds. @@ -79,9 +34,9 @@ public class SentryBackStackEntry( * records the destination as "/unknown". Doing so 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). @@ -95,62 +50,141 @@ public class SentryBackStackEntry( * - [Char] * - [Boolean] * - any [Number] (`NaN` and infinite values are sent as the strings `"NaN"`, `"Infinity"`, and - * `"-Infinity"`, which JSON can represent) + * `"-Infinity"`) * - enums (via [Enum.name]) * - `null` * * Or any of the following container types: * - * - [Array]s * - primitive arrays - * - [Map]s + * - [Array]s * - [Collection]s + * - [Map]s * * Containers may be nested, but they must bottom out in supported scalar types. * - * **Arguments fall back to `toString()` or nothing** - * - * All non-supported argument types are stringified via `toString()`, as are map keys. - * - * No arguments will be recorded for a back stack entry if [map] throws or returns `null`, or if its - * arguments are cyclic, too deeply nested, or too large, or contain a map with two keys that are - * stringified the same way (e.g., `1` and `"1"`). If the SDK drops an entry's arguments, it adds a - * `dropped_by_sentry` field and corresponding reason (e.g., `duplicate_key`) in the Sentry UI. - * - * **Using kotlinx.serialization** - * - * If your back stack contains `@Serializable` entry types, consider giving each entry an explicit - * `@SerialName` and using its `descriptor.serialName`. For performance reasons, don't serialize - * back stack keys in their entirety as `arguments` if they might be large, deeply nested, or - * contain PII or other sensitive information. - * - * For instance: - * ```kotlin - * @Serializable - * @SerialName("Home") - * data class Home(val userName: String) : NavKey - * - * @Serializable - * @SerialName("ProductDetail") - * data class ProductDetail(val userName: String, val productId: String) : NavKey - * - * ... - * - * val backStackItemMapper = BackStackEntryMapper { entry -> - * when (entry) { - * is Home -> SentryBackStackEntry(Home.serializer().descriptor.serialName) - * is ProductDetail -> SentryBackStackEntry( - * name = ProductDetail.serializer().descriptor.serialName, - * // Select a subset of diagnostic arguments when serialization is unsafe - * // or non-performant. - * arguments = mapOf("product_id" to entry.productId) - * ) - * ... - * } - * } - * ``` + * **Unsupported arguments types are stringified or dropped** + * + * All non-supported argument types are stringified via `toString()`. + * + * No arguments are recorded for a back stack entry if [map] throws or returns `null`. + * + * The SDK also drops an entry's arguments if they are: + * + * - cyclic, + * - too deeply nested, + * - too large, or + * - contain a map with two keys stringified the same way (e.g., `1` and `"1"`). + * + * In that case, it records why under `dropped_by_sentry` in the entry's arguments (e.g., + * `"max_argument_count_exceeded"`). */ @ApiStatus.Experimental -public fun interface BackStackEntryMapper { +public fun interface BackStackEntryMapper { + public fun map(backStackEntry: T): SentryBackStackEntry? + + public companion object { + + /** + * A convenience [BackStackEntryMapper] for apps that use kotlinx.serialization and only need to + * track the [serial names][kotlinx.serialization.descriptors.SerialDescriptor.serialName] of + * their back stack entries. + * + * For instance, given: + * ``` + * @Serializable + * @SerialName("ProductDetailScreen") + * data class ProductDetail(val productId: String) : NavKey + * ``` + * + * this mapper returns `"ProductDetailScreen"` for `ProductDetail(productId = "zyx987")` but + * omits the destination's properties (`productId`). + * + * **Name == SerialDescriptor.serialName** + * + * Each back stack entry is named after its + * [`SerialDescriptor.serialName`][kotlinx.serialization.descriptors.SerialDescriptor.serialName], + * i.e.: + * + * - the entry's `@SerialName` if it has one; or else + * - the entry's fully qualified class name (e.g., "com.example.Home"). + * + * **Sharing names** + * + * Entries will share a Sentry name if their serializers have the same serial name. In + * particular: + * + * - All constants of an enum share the enum class's serial name, regardless of any + * `@SerialName` on the constants. + * + * - Classes that share a custom serializer (`@Serializable(with = ...)`) share its descriptor's + * serial name, regardless of any `@SerialName` on the classes. + * + * To tell such entries apart, define a custom [BackStackEntryMapper], e.g., one that names enum + * constants after [Enum.name]. + * + * **Unknown names** + * + * This mapper returns `null` for back stack entries that lack a `@Serializable` annotation, are + * generic, or whose serializers can't be found or used. + * + * Sentry displays `null` entries as "/unknown" with an `unknown_entry_reason`. With SDK + * debugging enabled, the first unnamed entry of each class also logs a warning. + * + * See the + * [Troubleshooting Guide](https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers) + * for more details. + */ + public val SerialName: BackStackEntryMapper + get() = BuiltInBackStackEntryMappers.serialName + } +} + +/** Info about a given back stack entry, suitable for display in Sentry. */ +@ApiStatus.Experimental +public class SentryBackStackEntry( + /** + * A host-app defined name for a given back stack entry. + * + * Sentry interprets the name as a navigation destination. For instance, the following + * `SentryBackStackEntry` instances: + * ```kotlin + * SentryBackStackEntry(name = "Home") + * SentryBackStackEntry(name = "ProductDetail", arguments = mapOf("product_id" to 1234)) + * ``` + * + * will produce a breadcrumb like this: + * ```json + * { + * "from": "/Home", + * "to": "/ProductDetail", + * "to_arguments": { + * "product_id": 1234 + * } + * } + * ``` + * + * Note that the Sentry SDK normalizes `name` to include a "/" prefix. + */ + public val name: String, + /** + * Arguments from a given back stack entry, as selected by the host app. + * + * Useful for capturing any properties in the back stack key that have diagnostic value. + * + * Sentry treats these as metadata to be displayed alongside [name] in appropriate contexts. (See + * the `name` KDoc for an example.) + */ + public val arguments: Map? = null, +) { + + override fun equals(other: Any?): Boolean = + this === other || + (other is SentryBackStackEntry && name == other.name && arguments == other.arguments) + + override fun hashCode(): Int = 31 * name.hashCode() + (arguments?.hashCode() ?: 0) + + /** Omits arguments because they may contain sensitive host-app data. */ + override fun toString(): String = "SentryBackStackEntry(name=$name)" } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt index 0646c13ad90..9e5ff2d0946 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt @@ -33,9 +33,7 @@ import org.jetbrains.annotations.ApiStatus * // destination are attributed to the appropriate nav transaction. * SentryNavEffect( * backStack = navBackStack, - * backStackEntryMapper = { entry -> - * SentryBackStackEntry(entry.toName(), entry.extractArguments()) - * }, + * backStackEntryMapper = BackStackEntryMapper.SerialName, * options = SentryNavOptions(), * ) * 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 fe2a881c982..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 @@ -16,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 @@ -75,9 +76,9 @@ internal class BackStackConverter( sanitizer: ArgumentSanitizer, warningState: WarningState, ): NormalizedSentryBackStackEntry { - val info = + val (info, reportedReason) = try { - entryMapper.map(backStackEntry) + UnknownEntryReasonReporter.collect { entryMapper.map(backStackEntry) } } catch (t: Throwable) { // Back stack entry mappers are host app callbacks. ExceptionUtils.rethrowIfFatal(t) @@ -91,7 +92,7 @@ internal class BackStackConverter( if (info == null) { return NormalizedSentryBackStackEntry( name = UNKNOWN_ENTRY_NAME, - unknownEntryReason = UnknownEntryReason.UNMAPPED, + unknownEntryReason = reportedReason ?: UnknownEntryReason.UNMAPPED, ) } @@ -429,7 +430,7 @@ internal data class NormalizedSentryBackStackEntry( * ``` * { * "entry": "/unknown" - * "unknown_entry_reason": "unmapped" + * "unknown_entry_reason": "entry_not_annotated" * } * ``` */ 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 new file mode 100644 index 00000000000..85a17ca3f1d --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -0,0 +1,131 @@ +package io.sentry.compose.navigation3.internal.backstack + +import androidx.annotation.VisibleForTesting +import androidx.compose.runtime.snapshots.Snapshot +import io.sentry.ILogger +import io.sentry.ScopesAdapter +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.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 + +internal object BuiltInBackStackEntryMappers { + + private val logger: () -> ILogger = { ScopesAdapter.getInstance().options.logger } + + /** + * A built-in [BackStackEntryMapper] for apps that use kotlinx.serialization and only need to + * track the serial name of each of their back stack entries (and not each entry's properties). + * + * Falls back to [UnavailableBackStackEntryMapper] if the kotlinx mapper can't be created. + * + * See [BackStackEntryMapper.SerialName] for more details. + */ + val serialName: BackStackEntryMapper = + // Uses a deferred map because apps may read this while composing, which Compose can discard. + // SentryNavEffect is careful to call serialName.map() only from an effect. + DeferredBackStackEntryMapper { + create(logger) { KotlinxBackStackEntryMapper(logger = logger) } + } + + /** + * Returns the mapper created by [newKotlinxMapper], or an [UnavailableBackStackEntryMapper] if + * the mapper can't be linked or initialized. + */ + @VisibleForTesting + fun create( + logger: () -> ILogger, + newKotlinxMapper: () -> BackStackEntryMapper, + ): BackStackEntryMapper { + return try { + newKotlinxMapper() + } catch (e: LinkageError) { + // A missing or incompatible kotlinx-serialization-core version will throw a LinkageError, as + // will a failed initializer in it or in the SDK. Fall back instead of crashing. + 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, + ) + UnavailableBackStackEntryMapper(logger) + } + } +} + +/** + * A fallback for situations where the host app doesn't support a built-in [BackStackEntryMapper]. + * + * Maps every back stack entry to `null`, which Sentry records as [UNKNOWN_ENTRY_NAME] with + * [UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION]. Logs once per entry type. + */ +internal class UnavailableBackStackEntryMapper( + private val logger: () -> ILogger, +) : BackStackEntryMapper { + + private val loggedTypes = Collections.newSetFromMap(ConcurrentHashMap, Boolean>()) + + override fun map(backStackEntry: Any): SentryBackStackEntry? { + val type = backStackEntry.javaClass + + if (loggedTypes.add(type)) { + logger() + .log( + WARNING, + "Nav3 mapper unavailable for type %s. Using $UNKNOWN_ENTRY_NAME. Use a custom " + + "BackStackEntryMapper.", + type.name, + ) + } + + UnknownEntryReasonReporter.report(UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION) + return null + } +} + +/** + * A [BackStackEntryMapper] that creates the mapper it delegates to on its first [map] call, rather + * than when it's constructed. + * + * If [create] throws, [map] throws too and the next [map] call will try to create the mapper again. + */ +internal class DeferredBackStackEntryMapper( + create: () -> BackStackEntryMapper, +) : BackStackEntryMapper { + + // PUBLICATION avoids holding a lock while mapper creation calls the app's logger. + private val mapper by lazy(LazyThreadSafetyMode.PUBLICATION, create) + + override fun map(backStackEntry: Any): SentryBackStackEntry? = mapper.map(backStackEntry) +} + +/** + * A Compose-compatible version of [BackStackEntryMapper] that generates [SentryBackStackEntry]s by + * forwarding the request to the host app mapper in effect at the time [map] is called. + * + * Dynamically determining the current mapper lets us separate two concerns: + * + * 1. the lifetime of a consumer that tracks navigation state over time (e.g., [BackStackObserver]); + * and + * 2. the lifetime of the mapper used to generate `SentryBackStackEntry`s. + * + * Without that separation, a long-lived consumer would have to choose between holding stale mapping + * logic or recreating its own state whenever the mapper changed. + */ +internal class ForwardingBackStackEntryMapper( + private val currentMapper: () -> BackStackEntryMapper, +) { + + fun map(backStackEntry: T): SentryBackStackEntry? = Snapshot.withoutReadObservation { + currentMapper().map(backStackEntry) + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapper.kt deleted file mode 100644 index 3891b03bbf6..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapper.kt +++ /dev/null @@ -1,26 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack - -import androidx.compose.runtime.snapshots.Snapshot -import io.sentry.compose.navigation3.BackStackEntryMapper -import io.sentry.compose.navigation3.SentryBackStackEntry - -/** - * A Compose-compatible version of [BackStackEntryMapper] that generates [SentryBackStackEntry]s by - * forwarding the request to the host app mapper in effect at the time [map] is called. - * - * Dynamically determining the current mapper lets us separate two concerns: - * - * 1. the lifetime of a consumer that tracks navigation state over time (e.g., [BackStackObserver]); - * and - * 2. the lifetime of the mapper used to generate `SentryBackStackEntry`s. - * - * Without that separation, a long-lived consumer would have to choose between holding stale mapping - * logic or recreating its own state whenever the mapper changed. - */ -internal class ForwardingBackStackEntryMapper( - private val currentMapper: () -> BackStackEntryMapper, -) { - fun map(backStackEntry: T): SentryBackStackEntry? = Snapshot.withoutReadObservation { - currentMapper().map(backStackEntry) - } -} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md index bc8bb10067e..a2a4fc99cd2 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md @@ -1,22 +1,7 @@ # `io.sentry.compose.navigation3.internal.backstack` -This package converts a host app's back stack into Sentry navigation data: screen names, navigation -breadcrumbs, transactions, and the captured back stack. +This package contains logic for observing a host app's back stack so that it can be converted into Sentry navigation data, including screen +names, navigation breadcrumbs, and transactions. -## Mapping and sanitization - -The host app's `BackStackEntryMapper` supplies each entry's name and optional arguments in a -`SentryBackStackEntry`. Properties are the fields and values on the host's back stack entry; -arguments are the values the mapper chooses to expose as `SentryBackStackEntry.arguments`. - -Arguments are the mapper's output before sanitization. `BackStackConverter` normalizes entry names -and sanitizes arguments before they are recorded. Sanitization can stringify values or drop an -entry's arguments when they are invalid or exceed the limits in `ArgumentConstraints`. -The value and character budgets are shared across the entries captured in one back stack update. - -## Observation and coordination - -`BackStackObserver` detects changes and records navigation data for one back stack. -`CoordinatedBackStackObserver` connects that observer to `NavScopes`, which coordinates access to -shared scope state with other navigation roots. The lifecycle and ownership rules live in the -[sibling lifecycle package](../lifecycle/README.md). +It also contains implementations of our built-in `BackStackEntryMapper`s that host apps can use to generate names and optional arguments +from their back stack. 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 new file mode 100644 index 00000000000..5bc90e41323 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -0,0 +1,320 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.ILogger +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.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 +import java.lang.reflect.MalformedParameterizedTypeException +import java.util.concurrent.ConcurrentHashMap +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable + +/** Implementation of [BackStackEntryMapper.SerialName]. */ +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. + */ + private val lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, + /** + * Whether a back stack entry's class is annotated with `@Serializable`. + * + * May throw, as reading the class's annotations can fail. + */ + private val isAnnotatedSerializable: (Class<*>) -> Boolean = serializableAnnotationCheck(), + probe: CompatibilityProbe = { onInconclusive -> + KotlinxCompatibilityProbe.nameLookupLinkageError(onInconclusive = onInconclusive) + }, + logger: () -> ILogger, +) : BackStackEntryMapper { + + // Serializer lookups use reflection and mapping runs on every navigation, so we cache each + // class's name. Cache size is bounded by the number of back stack entry types. + private val types = ConcurrentHashMap, CachedType>() + + 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 } + } + + override fun map(backStackEntry: Any): SentryBackStackEntry? { + // An enum constant with a body is an instance of an anonymous subclass, which isn't + // @Serializable itself, so we look up the enum class instead. + val type = (backStackEntry as? Enum<*>)?.declaringJavaClass ?: backStackEntry.javaClass + val cached = + when (val cachedType = cachedType(type)) { + is CachedType.Resolved -> cachedType + is CachedType.Unresolved -> { + UnknownEntryReasonReporter.report(cachedType.reason) + return null + } + } + + 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) } + + /** + * Looks up [type]'s serializer and serial name. Logs if the serializer isn't available or the + * name can't be resolved. + * + * The lookup can run the app's serializer code and fail for the provided `type`. Rather than + * throw, this method returns [CachedType.Unresolved] with the reason. That allows the caller to + * cache the returned value, so that failing lookups are queried and logged only once per type. + */ + @OptIn(ExperimentalSerializationApi::class) + private fun lookUp(type: Class<*>): CachedType { + checkEligibleForLookup(type)?.let { + return CachedType.Unresolved(reason = it) + } + + return try { + val serializer = lookUpSerializer(type) + if (serializer == null) { + unresolved(type, error = null) + } else { + 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) + } 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. + unresolved(type, e) + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad b/c reflection throws its own unchecked exceptions (e.g., TypeNotPresentException + // when R8 removed a custom serializer), and custom descriptors may throw anything. The type + // is cached as unresolved to prevent re-failing on every navigation. + ExceptionUtils.rethrowIfFatal(t) + unresolved(type, t) + } + } + + /** + * Checks whether [type] is eligible for serializer retrieval. + * + * Returns `null` if eligible; otherwise returns the reason for ineligibility and logs. + */ + private fun checkEligibleForLookup(type: Class<*>): UnknownEntryReason? = + checkSerializableAnnotation(type) + ?: if (isGeneric(type)) { + diagnostics.genericType(type) + UnknownEntryReason.GENERIC_ENTRY_TYPE + } else { + null + } + + /** + * Checks that [type] is annotated with `@Serializable` so that built-in types and unannotated + * enums aren't named using unhelpful or potentially obfuscated serial names. + * + * Returns `null` if the annotation is present; otherwise returns the failure reason and logs. + */ + private fun checkSerializableAnnotation(type: Class<*>): UnknownEntryReason? = + try { + if (isAnnotatedSerializable(type)) { + null + } else { + diagnostics.notSerializable(type) + UnknownEntryReason.ENTRY_NOT_ANNOTATED + } + } catch (e: LinkageError) { + // Fails only this type. + unresolved(type, e).reason + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad b/c annotation parsing has undocumented failure modes. + ExceptionUtils.rethrowIfFatal(t) + unresolved(type, t).reason + } + + /** + * Whether [type] is generic (i.e., has type parameters). If so, serialization requires type + * arguments that can't be recovered from an entry at runtime. + * + * Returns `false` if `type`'s generic signature can't be read (e.g., because it's malformed, the + * type was removed by R8, etc.). + */ + private fun isGeneric(type: Class<*>): Boolean = + try { + type.typeParameters.isNotEmpty() + } catch (_: GenericSignatureFormatError) { + false + } catch (_: MalformedParameterizedTypeException) { + false + } catch (_: TypeNotPresentException) { + false + } + + /** + * Returns an unresolved cached type based on the provided [type], and logs. + * + * [error] is the exception thrown when trying to read the `type`'s annotations, serializer, or + * descriptor. + */ + private fun unresolved(type: Class<*>, error: Throwable?): CachedType.Unresolved { + diagnostics.unresolved(type, error) + return CachedType.Unresolved( + reason = + if (error == null) { + UnknownEntryReason.SERIALIZER_NOT_FOUND + } else { + UnknownEntryReason.SERIALIZER_ACCESS_THREW + }, + ) + } + + /** What [lookUp] found for a back stack entry type, cached so each type is looked up once. */ + private sealed interface CachedType { + + /** A type that can be named, and its [name]. */ + class Resolved(val name: String) : CachedType + + /** + * A type that can't be named, e.g., because it isn't `@Serializable` or reading its serializer + * failed. Its entries are recorded as [UNKNOWN_ENTRY_NAME], with [reason]. + */ + class Unresolved(val reason: UnknownEntryReason) : CachedType + } + + private companion object { + + /** Returns whether a class is annotated with `@Serializable`. */ + private fun serializableAnnotationCheck(): (Class<*>) -> Boolean { + // Resolved here, when the mapper is created, rather than on the first map() call, so that if + // the annotation class can't be linked, creating this mapper fails and + // BuiltInBackStackEntryMappers falls back to UnavailableBackStackEntryMapper. + val serializableAnnotation: Class = Serializable::class.java + return { type -> type.isAnnotationPresent(serializableAnnotation) } + } + } +} + +/** + * The warnings [KotlinxBackStackEntryMapper] logs if it can't find the serializer for a back stack + * entry or resolve the entry's name. + * + * 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` + * (`sentry-android-integration-tests/nav3-built-in-back-stack-mappers-r8-check`). + */ +internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { + + /** Logs that entries of [type] can't be named because the type isn't `@Serializable`. */ + fun notSerializable(type: Class<*>) { + logger() + .log( + WARNING, + "Nav3 can't name entries of type %s because the type is not @Serializable. Using " + + "$UNKNOWN_ENTRY_NAME. Add @Serializable or use a custom BackStackEntryMapper.", + type.name, + ) + } + + /** Logs that serial names for entries of [type] can't be resolved because the type is generic. */ + fun genericType(type: Class<*>) { + logger() + .log( + WARNING, + "Nav3 can't name entries of type %s because the type has type parameters. Using " + + "$UNKNOWN_ENTRY_NAME. Use a custom BackStackEntryMapper.", + type.name, + ) + } + + /** + * 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 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 support for name lookups because %s. " + + "Handling failures per entry type.", + if (error != null) PROBE_THREW else PROBE_SERIALIZER_NOT_FOUND, + ) + } + + /** + * Logs why [type] can't be named. [error] is what reading its annotations, serializer, or + * descriptor threw, or `null` if the serializer lookup found none without throwing. + * + * [error] is attached in full. The lookup never sees an entry's values, so it only contains the + * app's own messages (e.g., from a custom serializer) rather than nav route info. + */ + fun unresolved(type: Class<*>, error: Throwable?) { + val reason = if (error != null) LOOK_UP_FAILED else SERIALIZER_NOT_FOUND + 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. + "See the attached error. If all types fail, kotlinx.serialization may be incompatible. " + + INCOMPATIBLE_KOTLINX_ADVICE + } else if (error != null) { + "See the attached error or use a custom BackStackEntryMapper." + } else { + "See BackStackEntryMapper.SerialName's documentation or use a custom BackStackEntryMapper." + } + logger() + .log( + WARNING, + error, + "Nav3 can't name entries of type %s because %s. Using $UNKNOWN_ENTRY_NAME. $advice", + type.name, + reason, + ) + } + + 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/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 new file mode 100644 index 00000000000..310007c04e5 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -0,0 +1,46 @@ +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 + +/** + * Returns [type]'s serializer, or `null` if unavailable, including when type arguments are needed. + * 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. + */ +@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 + } + +/** + * 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.) + * + * Propagates any exception thrown by the reflective lookup. + */ +private fun privateObjectSerializerOrNull(type: Class<*>): KSerializer<*>? { + val instance = type.getDeclaredField("INSTANCE").apply { isAccessible = true }.get(null) + return type.getDeclaredMethod("serializer").apply { isAccessible = true }.invoke(instance) + as? KSerializer<*> +} 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 new file mode 100644 index 00000000000..ddadd318837 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -0,0 +1,58 @@ +# `io.sentry.compose.navigation3.internal.backstack.kotlinx` + +This package isolates access to kotlinx.serialization APIs used by our Nav3 integration. + +## Dependency isolation + +`kotlinx-serialization-core` is a `compileOnly` dependency of `sentry-android-navigation3` assumed always to be present, as every Nav3 app +depends on it via `navigation3-runtime`. We compile against the lowest version required. + +The actual `kotlinx-serialization-core` version available at runtime is determined by the host app, and may be incompatible with the APIs we +compile against. To protect against crashes, only classes in the `kotlinx` subpackage may reference kotlinx.serialization APIs, and code +outside is limited to a single entry point, viz., `BuiltInBackStackEntryMappers.create`. That entry point is where we catch any +`LinkageError`s thrown if the host app uses an incompatible `kotlinx-serialization-core` version. + +To keep our isolation policy intact: + +- put any new classes that reference kotlinx.serialization in the `.kotlinx` subpackage and name them using a `Kotlinx*` prefix; +- don't expose kotlinx.serialization types outside the `Kotlinx*` classes; and +- reference `Kotlinx*` classes from outside the `.kotlinx` subpackage only via `BuiltInBackStackEntryMappers.create`. + +## Version floor + +The `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml` is the earliest `kotlinx-serialization-core` version our +built-in mappers support. It matches the oldest supported Nav3 release's dependency, viz., 1.7.3 for `navigation3-runtime` 1.0.0. + +Support behavior that only newer `kotlinx-serialization-core` versions need with guarded, version-specific code paths. + +CI runs all of `sentry-android-navigation3`'s unit tests against: + +1. the `kotlinxSerialization-floor`, and +2. the latest stable release (bumped by Dependabot). + +For failure handling, see "When a kotlinx.serialization bump fails" in the `nav3-built-in-back-stack-mappers-r8-check` README. + +Recommended rules for raising the floor: + +- Keep the current floor as long as our built-in mappers can support it. Raise it only when the oldest supported Nav3 release mandates it or + a required SDK change is incompatible with the current floor. (In particular, verify Kotlin compiler, language version, and serialization + plugin upgrades against the current floor. A test dependency that needs a newer version doesn't change what the floor tests run: the + unit tests pin the version under test strictly.) + +- 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. + +## Minification + +The `nav3-built-in-back-stack-mappers-r8-check` verifies the behavior of our built-in mappers after minification. + +See the `proguard-rules.pro` file in `sentry-android-navigation3` for info about the minification rules applied by kotlinx.serialization. + +## What if a host app doesn't use kotlinx-serialization-core? + +If a host app uses `sentry-android-navigation3` without also depending on `kotlinx-serialization-core` (via Nav3 or otherwise), R8 will fail +the app's release builds, as we do not include a `-dontwarn` proguard rule for kotlinx.serialization. The host app can add that rule itself +or – more likely – remove an unintended `sentry-android-navigation3` dependency. (See the `proguard-rules.pro` file in +`sentry-android-navigation3` for more info.) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt index 9ba05e32eb3..e9dbf053899 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt @@ -37,14 +37,57 @@ internal const val UNKNOWN_ENTRY_NAME = "/unknown" */ internal enum class UnknownEntryReason(val serializedValue: String) { + // General reasons + /** The mapper returned a name that was empty after trimming. */ BLANK_NAME("blank_name"), /** The mapper threw. */ MAPPING_FAILED("mapping_failed"), - /** The mapper returned `null`, i.e., it chose not to name the entry. */ - UNMAPPED("unmapped"); + /** + * The mapper returned `null` without a built-in mapper reporting why, i.e., a custom mapper chose + * not to name the entry. + */ + UNMAPPED("unmapped"), + + // Reasons specific to built-in mappers + + /** + * A built-in mapper couldn't name the entry because the entry's class wasn't annotated with + * `@Serializable`. + */ + ENTRY_NOT_ANNOTATED("entry_not_annotated"), + + /** + * A built-in mapper couldn't name the entry because the entry's `@Serializable` class had one or + * more type parameters (of any sort). + * + * Looking up a generic type's serializer requires serializers for its type arguments, which the + * mapper can't recover from the entry at runtime. + * + * Detected from the entry class's generic signature. If R8 removes that signature, the entry will + * be assigned [SERIALIZER_NOT_FOUND] instead. + */ + GENERIC_ENTRY_TYPE("generic_entry_type"), + + /** + * A built-in mapper couldn't be created because the host app uses a missing or incompatible + * version of `kotlinx-serialization-core`. + */ + KOTLINX_SERIALIZATION_VERSION("kotlinx_serialization_version"), + + /** + * A built-in mapper couldn't name the entry because an exception was thrown while trying to read + * the entry's class's annotations, serializer, or descriptor. + */ + SERIALIZER_ACCESS_THREW("serializer_access_threw"), + + /** + * A built-in mapper can't name the entry because it couldn't find the entry class's serializer, + * e.g., because R8 removed what the lookup needs. + */ + SERIALIZER_NOT_FOUND("serializer_not_found"); companion object { 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/BackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt new file mode 100644 index 00000000000..6722f66584d --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackEntryMapperTest.kt @@ -0,0 +1,17 @@ +package io.sentry.compose.navigation3 + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.BuiltInBackStackEntryMappers +import org.junit.Test + +class BackStackEntryMapperTest { + + private data object Home + + @Test + fun `SerialName - returns the built-in serial name mapper as a mapper for any entry type`() { + val homeMapper: BackStackEntryMapper = BackStackEntryMapper.SerialName + + assertThat(homeMapper).isSameInstanceAs(BuiltInBackStackEntryMappers.serialName) + } +} 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 4b82a1df66e..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 @@ -14,6 +14,60 @@ class PackageBoundariesTest { .map(SourceFile::parse) .toList() + @Test + fun `only the kotlinx package may import kotlinx serialization`() { + val otherSources = sources.filterNot { it.packageName.isIn(KOTLINX) } + + val violations = otherSources.importsMatching { it.isIn("kotlinx.serialization") } + + assertThat(otherSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `source files in the kotlinx package have names that start with Kotlinx`() { + val kotlinxSources = sources.filter { it.packageName.isIn(KOTLINX) } + + val violations = kotlinxSources.filterNot { it.name.startsWith("Kotlinx") }.map { it.path } + + assertThat(kotlinxSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `only the kotlinx package and the mapper factory may import the kotlinx package`() { + val otherSources = sources.filterNot { + it.packageName.isIn(KOTLINX) || it.path == MAPPER_FACTORY_PATH + } + + val violations = otherSources.importsMatching { it.isIn(KOTLINX) } + + assertThat(otherSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `the kotlinx package has no imports from Android, AndroidX, or the lifecycle package`() { + val kotlinxSources = sources.filter { it.packageName.isIn(KOTLINX) } + + val violations = kotlinxSources.importsMatching { + it.isIn("android") || it.isIn("androidx") || it.isIn(LIFECYCLE) + } + + assertThat(kotlinxSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `the kotlinx package has no imports from its parent backstack package`() { + val kotlinxSources = sources.filter { it.packageName.isIn(KOTLINX) } + + val violations = kotlinxSources.importsMatching { it.isIn(BACKSTACK) && !it.isIn(KOTLINX) } + + assertThat(kotlinxSources).isNotEmpty() + assertThat(violations).isEmpty() + } + @Test fun `the lifecycle package imports only the contract package from other Sentry navigation3 packages`() { val lifecycleSources = sources.filter { it.packageName.isIn(LIFECYCLE) } @@ -86,6 +140,7 @@ class PackageBoundariesTest { /** A source file's location, package, and import targets. */ private class SourceFile( val path: String, + val name: String, val packageName: String, val imports: List, ) { @@ -97,6 +152,7 @@ class PackageBoundariesTest { val lines = file.readLines().map(String::trim) return SourceFile( path = file.invariantSeparatorsPath, + name = file.name, packageName = lines.firstNotNullOfOrNull { PACKAGE.find(it)?.groupValues?.get(1) }.orEmpty(), imports = lines.mapNotNull { IMPORT.find(it)?.groupValues?.get(1) }, @@ -108,8 +164,12 @@ class PackageBoundariesTest { private companion object { const val SOURCE_ROOT = "src/main/kotlin" const val ROOT = "io.sentry.compose.navigation3" + const val BACKSTACK = "$ROOT.internal.backstack" + const val KOTLINX = "$BACKSTACK.kotlinx" const val LIFECYCLE = "$ROOT.internal.lifecycle" const val CONTRACT = "$ROOT.internal.contract" + const val MAPPER_FACTORY_PATH = + "$SOURCE_ROOT/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt" /** Whether this name is [packageName] or lies inside it. */ fun String.isIn(packageName: String): Boolean = diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt index 850802400a4..f75f7063b92 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt @@ -34,6 +34,8 @@ import io.sentry.SentryTracer import io.sentry.TransactionContext import io.sentry.TransactionOptions import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.junit.Rule import org.junit.Test import org.junit.rules.TestWatcher @@ -75,6 +77,10 @@ class SentryNavEffectTest { private data class ProfileRoute(val userId: String) + @Serializable @SerialName("SerializableHome") private data object SerializableHomeRoute + + @Serializable private data class SerializableProfileRoute(val userId: String) + private class Fixture { val options = SentryOptions().apply { @@ -353,6 +359,43 @@ class SentryNavEffectTest { assertThat(observedTransactionNames).containsExactly("/HomeRoute", "/ProfileRoute").inOrder() } + @Test + fun `SerialName records serial names, and unknown names with their reason for entries that aren't @Serializable`() { + val fixture = Fixture() + val backStack = mutableStateListOf(SerializableHomeRoute) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialName, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + composeRule.runOnIdle { + backStack.add(SerializableProfileRoute("123")) + backStack.add(ProfileRoute("456")) + } + composeRule.waitForIdle() + + val profileName = "/io.sentry.compose.navigation3.SentryNavEffectTest.SerializableProfileRoute" + assertThat(fixture.breadcrumbs.first().data["to"]).isEqualTo("/SerializableHome") + assertThat(fixture.transactions.first().name).isEqualTo("/SerializableHome") + assertThat(fixture.scope.screen).isEqualTo("/unknown") + assertThat(fixture.breadcrumbs.last().data["to_unknown_entry_reason"]) + .isEqualTo("entry_not_annotated") + assertThat(fixture.scope.navigationBackStack()) + .containsExactly( + mapOf("entry" to "/unknown", "unknown_entry_reason" to "entry_not_annotated"), + mapOf("entry" to profileName), + mapOf("entry" to "/SerializableHome"), + ) + .inOrder() + } + @Test fun `updated entry mapper is used for later navigation changes`() { val fixture = Fixture() 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 c58b931bc02..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 @@ -13,6 +13,7 @@ import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.Reten 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 @@ -46,6 +47,13 @@ class BackStackConverterTest { SentryBackStackEntry(entry::class.simpleName ?: "") } + /** Reports a reason and returns `null`, like a built-in mapper that can't name an entry. */ + private val entryNotAnnotatedMapper = + BackStackEntryMapper { + UnknownEntryReasonReporter.report(UnknownEntryReason.ENTRY_NOT_ANNOTATED) + null + } + @Test fun `convert() - returns normalized back stack entries`() { val converter = @@ -222,7 +230,7 @@ class BackStackConverterTest { } @Test - fun `convert() - returns unknown name with the unmapped reason if mapper returns null`() { + fun `convert() - returns unknown name with the unmapped reason if mapper returns null without a report`() { val converter = newConverter(entryMapper = { null }) assertThat(converter.convert(HomeScreen())) @@ -234,6 +242,60 @@ class BackStackConverterTest { ) } + @Test + fun `convert() - returns unknown name with the reported reason if mapper reports one and returns null`() { + val converter = newConverter(entryMapper = entryNotAnnotatedMapper) + + assertThat(converter.convert(HomeScreen())) + .isEqualTo( + NormalizedSentryBackStackEntry( + UNKNOWN_ENTRY_NAME, + unknownEntryReason = UnknownEntryReason.ENTRY_NOT_ANNOTATED, + ), + ) + } + + @Test + fun `convert() - returns the reported reason if a custom mapper forwards a reporting mapper's null`() { + val converter = newConverter(entryMapper = { entry -> entryNotAnnotatedMapper.map(entry) }) + + assertThat(converter.convert(HomeScreen()).unknownEntryReason) + .isEqualTo(UnknownEntryReason.ENTRY_NOT_ANNOTATED) + } + + @Test + fun `convert() - returns a named entry if a custom mapper names an entry after a reporting mapper's null`() { + val converter = + newConverter( + entryMapper = { entry -> + entryNotAnnotatedMapper.map(entry) ?: SentryBackStackEntry("fallback") + }, + ) + + assertThat(converter.convert(HomeScreen())) + .isEqualTo(NormalizedSentryBackStackEntry(name = "/fallback")) + } + + @Test + fun `convert() - does not carry a reported reason over to the next back stack entry`() { + val converter = + newConverter( + entryMapper = { entry -> + when (entry) { + is HomeScreen -> entryNotAnnotatedMapper.map(entry) + else -> null + } + }, + ) + + val routes = + converter.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + + assertThat(routes.map { it.unknownEntryReason }) + .containsExactly(UnknownEntryReason.ENTRY_NOT_ANNOTATED, UnknownEntryReason.UNMAPPED) + .inOrder() + } + @Test fun `convert() - returns unknown name with the mapping failed reason and no arguments if mapper throws`() { val converter = newConverter(entryMapper = { error("boom") }) @@ -253,6 +315,20 @@ class BackStackConverterTest { ) } + @Test + fun `convert() - returns the mapping failed reason if mapper throws after reporting a reason`() { + val converter = + newConverter( + entryMapper = { entry -> + entryNotAnnotatedMapper.map(entry) + error("boom") + }, + ) + + assertThat(converter.convert(HomeScreen()).unknownEntryReason) + .isEqualTo(UnknownEntryReason.MAPPING_FAILED) + } + @Test fun `convert() - logs the mapper failure warning once per back stack update`() { val converter = newConverter(entryMapper = { error("boom") }) 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 new file mode 100644 index 00000000000..758ce9c864b --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -0,0 +1,321 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.Sentry +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.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 +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.thread +import kotlin.test.assertFailsWith +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import org.junit.Test +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions + +/** + * The built-in mappers are singletons whose caches and warning history persist across tests. Tests + * that assert logs must use `create()` or a fresh class loader to isolate that state. + */ +class BuiltInBackStackEntryMappersTest { + + @Serializable @SerialName("Home") data object Home + + data class NotSerializable(val id: String) + + private val kotlinxMapper = BackStackEntryMapper { SentryBackStackEntry("Kotlinx") } + private val logger = mock() + + // serialName + + @Test + fun `serialName - returns the same mapper on every access`() { + assertThat(BuiltInBackStackEntryMappers.serialName) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialName) + } + + @Test + fun `serialName - doesn't create the kotlinx mapper when read`() { + val classLoader = KotlinxMapperHidingClassLoader() + + classLoader.companionMapper("getSerialName") + + assertThat(classLoader.wasKotlinxMapperRequested).isFalse() + } + + @Test + fun `serialName - maps entries to null when the kotlinx mapper can't be loaded`() { + val classLoader = KotlinxMapperHidingClassLoader() + + val mapper = classLoader.companionMapper("getSerialName") + + assertThat(mapper.map(Home)).isNull() + assertThat(classLoader.wasKotlinxMapperRequested).isTrue() + } + + @Test + fun `serialName - maps entries to null when kotlinx serialization is missing`() { + val classLoader = KotlinxMapperHidingClassLoader(hidesKotlinx = true) + val entry = classLoader.notSerializableEntry("1") + + val mapper = classLoader.companionMapper("getSerialName") + + assertThat(mapper.map("home")).isNull() + assertThat(mapper.map(entry)).isNull() + assertThat(classLoader.wasKotlinxRequested).isTrue() + } + + @Test + fun `serialName - holds no lock while logging a mapper creation failure on the first mapping`() { + val race = raceOnFirstMapping("getSerialName") + + assertThat(race.otherThreadLoggerGotAppLock).isTrue() + } + + @Test + fun `serialName - uses the mapper created first for racing and later mappings`() { + val race = raceOnFirstMapping("getSerialName") + + assertThat(race.unavailableTypeWarnings).isEqualTo(1) + } + + // create() + + @Test + fun `create() - returns the kotlinx mapper without logging when it can be created`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + kotlinxMapper + } + + assertThat(mapper).isSameInstanceAs(kotlinxMapper) + verifyNoInteractions(logger) + } + + @Test + fun `create() - returns a mapper reporting the kotlinx serialization version reason for a NoClassDefFoundError`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw NoClassDefFoundError("kotlinx/serialization/KSerializer") + } + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(Home) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION) + } + + @Test + fun `create() - returns a mapper that maps entries to null for an ExceptionInInitializerError`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw ExceptionInInitializerError("static initializer failed") + } + + assertThat(mapper.map(Home)).isNull() + } + + @Test + fun `create() - logs the LinkageError and compatibility advice when creating the kotlinx mapper fails`() { + val error = NoClassDefFoundError("kotlinx/serialization/KSerializer") + + BuiltInBackStackEntryMappers.create(logger = { logger }) { throw error } + + val message = argumentCaptor() + verify(logger, times(1)).log(eq(SentryLevel.WARNING), message.capture(), eq(error)) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `create() - propagates an exception that isn't a LinkageError from creating the kotlinx mapper`() { + val exception = IllegalStateException("mapper bug") + + val thrown = + assertFailsWith { + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw exception + } + } + + assertThat(thrown).isSameInstanceAs(exception) + } + + /** + * Races the first mappings of [Home] by the mapper of [getterName] to detect lock inversion: this + * thread holds an app lock while mapping, and the other thread's mapper creation logs through a + * logger that needs the same lock. Holding a lazy-initialization lock while logging would + * deadlock. Then maps [Home] once more. + * + * Both threads create an [UnavailableBackStackEntryMapper], which warns once per entry type, so a + * single warning shows that every mapping used the one mapper published first. + * + * Bounded waits prevent a hang. Assertions inside the helper verify the race's preconditions. + */ + private fun raceOnFirstMapping(getterName: String): FirstMappingRace { + val appLock = ReentrantLock() + val logger = LockingLogger(appLock, thisThread = Thread.currentThread()) + initForTest( + { + it.dsn = "https://key@sentry.io/proj" + it.isDebug = true + it.setLogger(logger) + }, + true, + ) + try { + val mapper = KotlinxMapperHidingClassLoader().companionMapper(getterName) + appLock.lock() + val otherThread = thread(name = "other-mapper-user") { mapper.map(Home) } + assertThat(logger.otherThreadLogging.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue() + + try { + mapper.map(Home) + } finally { + appLock.unlock() + } + otherThread.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS * 2)) + assertThat(otherThread.isAlive).isFalse() + mapper.map(Home) + + return FirstMappingRace( + otherThreadLoggerGotAppLock = logger.otherThreadGotLock, + unavailableTypeWarnings = logger.unavailableTypeWarnings.get(), + ) + } finally { + Sentry.close() + } + } + + private class FirstMappingRace( + val otherThreadLoggerGotAppLock: Boolean, + /** How many times the racing and later mappings warned that [Home]'s mapper is unavailable. */ + val unavailableTypeWarnings: Int, + ) + + /** + * An app's logger that takes [appLock] to log that the built-in mappers couldn't be created, as + * an app's logger might, giving up after a timeout. Records whether a thread other than + * [thisThread] got the lock, and counts warnings that an entry type's mapper is unavailable. + */ + private class LockingLogger(private val appLock: ReentrantLock, private val thisThread: Thread) : + ILogger { + val otherThreadLogging = CountDownLatch(1) + + val unavailableTypeWarnings = AtomicInteger() + + @Volatile var otherThreadGotLock = false + + override fun log(level: SentryLevel, message: String, vararg args: Any?) { + if (message.startsWith(MAPPER_UNAVAILABLE)) unavailableTypeWarnings.incrementAndGet() + } + + override fun log(level: SentryLevel, message: String, throwable: Throwable?) { + if (!message.startsWith(CREATION_FAILED)) return + val isOtherThread = Thread.currentThread() != thisThread + if (isOtherThread) otherThreadLogging.countDown() + val gotLock = appLock.tryLock(TIMEOUT_SECONDS, TimeUnit.SECONDS) + if (isOtherThread) otherThreadGotLock = gotLock + if (gotLock) appLock.unlock() + } + + override fun log( + level: SentryLevel, + throwable: Throwable?, + message: String, + vararg args: Any?, + ) = Unit + + override fun isEnabled(level: SentryLevel?): Boolean = true + } + + /** + * Loads its own copy of this module's classes, so their singletons are created anew, but can't + * find [KotlinxBackStackEntryMapper], as when it can't be linked against the app's + * kotlinx.serialization. Other classes come from the test's class loader. + * + * With `hidesKotlinx = true`, it finds [KotlinxBackStackEntryMapper] but not + * kotlinx.serialization itself, as when the app doesn't depend on it. + */ + private class KotlinxMapperHidingClassLoader(private val hidesKotlinx: Boolean = false) : + ClassLoader(BuiltInBackStackEntryMappersTest::class.java.classLoader) { + + @Volatile + var wasKotlinxMapperRequested = false + private set + + @Volatile + var wasKotlinxRequested = false + private set + + /** Returns a [NotSerializable] loaded by this class loader, which doesn't need kotlinx. */ + fun notSerializableEntry(id: String): Any = + loadClass(NotSerializable::class.java.name).getConstructor(String::class.java).newInstance(id) + + /** Returns the mapper of this class loader's `BackStackEntryMapper.Companion.`. */ + fun companionMapper(getterName: String): Mapper { + val companion = + loadClass(BackStackEntryMapper::class.java.name).getField("Companion").get(null) + return Mapper(companion.javaClass.getMethod(getterName).invoke(companion)) + } + + override fun loadClass(name: String, resolve: Boolean): Class<*> = + synchronized(this) { + when { + name == HIDDEN_CLASS && !hidesKotlinx -> { + wasKotlinxMapperRequested = true + throw ClassNotFoundException(name) + } + name.startsWith(KOTLINX_PACKAGE) && hidesKotlinx -> { + wasKotlinxRequested = true + throw ClassNotFoundException(name) + } + !name.startsWith(ISOLATED_PACKAGE) -> super.loadClass(name, resolve) + else -> findLoadedClass(name) ?: define(name) + } + } + + private fun define(name: String): Class<*> { + val bytes = + parent.getResourceAsStream(name.replace('.', '/') + ".class")?.use { it.readBytes() } + ?: throw ClassNotFoundException(name) + return defineClass(name, bytes, 0, bytes.size) + } + + /** A mapper loaded by this class loader, whose types differ from the test's. */ + class Mapper(val delegate: Any) { + val type: Class<*> = delegate.javaClass + + fun map(backStackEntry: Any): Any? = + type.getMethod("map", Any::class.java).invoke(delegate, backStackEntry) + } + + private companion object { + const val ISOLATED_PACKAGE = "io.sentry.compose.navigation3." + const val KOTLINX_PACKAGE = "kotlinx.serialization." + val HIDDEN_CLASS: String = KotlinxBackStackEntryMapper::class.java.name + } + } + + private companion object { + /** Bounds every wait, so that a deadlock fails the test rather than hanging it. */ + const val TIMEOUT_SECONDS = 5L + + const val CREATION_FAILED = "Nav3 built-in mapper creation failed." + + const val MAPPER_UNAVAILABLE = "Nav3 mapper unavailable for type" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/DeferredBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/DeferredBackStackEntryMapperTest.kt new file mode 100644 index 00000000000..4d78dd61d1f --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/DeferredBackStackEntryMapperTest.kt @@ -0,0 +1,88 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import kotlin.test.assertFailsWith +import org.junit.Test + +class DeferredBackStackEntryMapperTest { + + @Test + fun `doesn't create the delegate mapper before it maps an entry`() { + val fixture = Fixture.create() + + assertThat(fixture.creations).isEqualTo(0) + } + + // map() + + @Test + fun `map() - creates the delegate mapper on the first call and returns its result for the entry`() { + val fixture = Fixture.create() + val deferredMapper = fixture.deferredMapper + + val mapped = deferredMapper.map("home") + + assertThat(mapped).isEqualTo(SentryBackStackEntry("mapped home")) + assertThat(fixture.creations).isEqualTo(1) + } + + @Test + fun `map() - reuses the created delegate mapper for later entries`() { + val fixture = Fixture.create() + val deferredMapper = fixture.deferredMapper + deferredMapper.map("home") + + val mapped = listOf("detail", "settings").map(deferredMapper::map) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("mapped detail"), + SentryBackStackEntry("mapped settings"), + ) + .inOrder() + assertThat(fixture.creations).isEqualTo(1) + } + + @Test + fun `map() - propagates the exception thrown while creating the delegate mapper`() { + val exception = IllegalStateException("creation failed") + val fixture = Fixture.create(creationFailure = exception) + val deferredMapper = fixture.deferredMapper + + val thrown = assertFailsWith { deferredMapper.map("home") } + + assertThat(thrown).isSameInstanceAs(exception) + } + + @Test + fun `map() - creates the delegate mapper again after creating it threw`() { + val fixture = Fixture.create(creationFailure = IllegalStateException("creation failed")) + val deferredMapper = fixture.deferredMapper + assertFailsWith { deferredMapper.map("home") } + fixture.creationFailure = null + + val mapped = deferredMapper.map("home") + + assertThat(mapped).isEqualTo(SentryBackStackEntry("mapped home")) + assertThat(fixture.creations).isEqualTo(2) + } + + private class Fixture private constructor(var creationFailure: RuntimeException?) { + var creations = 0 + private set + + private val delegateMapper = BackStackEntryMapper { SentryBackStackEntry("mapped $it") } + + val deferredMapper = DeferredBackStackEntryMapper { + creations++ + creationFailure?.let { throw it } + delegateMapper + } + + companion object { + fun create(creationFailure: RuntimeException? = null) = Fixture(creationFailure) + } + } +} 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 new file mode 100644 index 00000000000..c2be6bf0f59 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt @@ -0,0 +1,59 @@ +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.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions + +class UnavailableBackStackEntryMapperTest { + + private data object Home + + private data class Detail(val id: String) + + private val logger = mock() + private val mapper = UnavailableBackStackEntryMapper(logger = { logger }) + + @Test + fun `map() - maps every back stack entry to null`() { + val mapped = listOf(Home, Detail("1"), "home").map(mapper::map) + + assertThat(mapped).containsExactly(null, null, null) + } + + @Test + fun `map() - reports the kotlinx serialization version as the reason for every back stack entry`() { + val reasons = + listOf(Home, Detail("1"), Home).map { entry -> + UnknownEntryReasonReporter.collect { mapper.map(entry) }.reason + } + + assertThat(reasons) + .containsExactly( + UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION, + UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION, + UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION, + ) + } + + @Test + fun `map() - logs a warning once per back stack entry type`() { + repeat(3) { + mapper.map(Home) + mapper.map(Detail("$it")) + } + + verify(logger, times(1)).log(eq(SentryLevel.WARNING), any(), eq(Home::class.java.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), any(), eq(Detail::class.java.name)) + verifyNoMoreInteractions(logger) + } +} 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 new file mode 100644 index 00000000000..3cad4011b7b --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperTest.kt @@ -0,0 +1,763 @@ +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.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.contract.UnknownEntryReason +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter +import java.lang.annotation.AnnotationFormatError +import java.lang.reflect.InvocationTargetException +import kotlin.test.assertFailsWith +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.MetaSerializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argThat +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions + +@OptIn(ExperimentalSerializationApi::class) +@MetaSerializable +@Target(AnnotationTarget.CLASS) +private annotation class MetaSerializableRoute + +@MetaSerializableRoute private data class MetaSerializableEntry(val id: String) + +class KotlinxBackStackEntryMapperTest { + + @Serializable + @SerialName("TabWithBodies") + enum class TabWithBodies { + FEED { + override val icon = "feed" + }, + SEARCH { + override val icon = "search" + }; + + abstract val icon: String + } + + data class NotSerializable(val id: String) + + enum class UnannotatedTab { + FEED, + } + + @Serializable data class Generic(val value: T) + + // Construction + + @Test + fun `logs nothing when created and the compatibility probe finds kotlinx serialization compatible`() { + val logger = mock() + + KotlinxBackStackEntryMapper(probe = FakeCompatibilityProbe(), logger = { logger }) + + verifyNoInteractions(logger) + } + + @Test + fun `fails creation with the LinkageError the compatibility probe returns`() { + val error = NoSuchMethodError("serializerOrNull") + val probe = FakeCompatibilityProbe(linkageError = error) + + val thrown = + assertFailsWith { + KotlinxBackStackEntryMapper(probe = probe, logger = { mock() }) + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + 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(probe = probe, 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") + val logger = mock() + val probe = FakeCompatibilityProbe(inconclusive = Inconclusive(error)) + + KotlinxBackStackEntryMapper(probe = probe, logger = { logger }) + + verify(logger).log(eq(SentryLevel.DEBUG), eq(error), any(), eq(PROBE_THREW)) + } + + @Test + 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")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + } + + // Naming + + @Test + fun `names entries after their serializer's serial name`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Search("shoes"))) + + assertThat(mapped) + .containsExactly(SentryBackStackEntry("Detail"), SentryBackStackEntry("Search")) + .inOrder() + } + + @Test + fun `names constants of an enum with constant bodies after the enum's serializer`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + val mapped = mapper.map(TabWithBodies.SEARCH) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("TabWithBodies")) + } + + // Annotation check + + @Test + fun `returns null for entries that aren't annotated @Serializable, even if the serializer lookup has a serializer`() { + // kotlinx.serialization has serializers for built-in types and enums that aren't @Serializable. + val fixture = Fixture.create(lookUpSerializer = { String.serializer() }) + val mapper = fixture.mapper + + val mapped = + listOf( + mapper.map("home"), + mapper.map(42), + mapper.map(UnannotatedTab.FEED), + mapper.map(NotSerializable("1")), + ) + + assertThat(mapped).containsExactly(null, null, null, null) + } + + @Test + fun `returns null for entries of a class annotated with a @MetaSerializable annotation`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + val mapped = mapper.map(MetaSerializableEntry("1")) + + assertThat(mapped).isNull() + } + + @Test + fun `doesn't look up serializers for entries that aren't annotated @Serializable`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + mapper.map(NotSerializable("1")) + mapper.map("home") + mapper.map(42) + mapper.map(UnannotatedTab.FEED) + + assertThat(fixture.lookedUpTypes).isEmpty() + } + + @Test + fun `returns null and logs the error when the annotation check throws an exception`() { + val error = AnnotationFormatError("malformed annotation") + val fixture = Fixture.create(isAnnotatedSerializable = { throw error }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, error) + } + + @Test + fun `returns null and logs the error when the annotation check throws a LinkageError`() { + val error = NoClassDefFoundError("com/example/MissingAnnotation") + val fixture = Fixture.create(isAnnotatedSerializable = { throw error }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, error) + } + + @Test + fun `restores the interrupt flag when the annotation check throws InterruptedException`() { + val fixture = Fixture.create(isAnnotatedSerializable = { throw 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 `keeps naming other types after the annotation check throws for one type`() { + val fixture = + Fixture.create( + isAnnotatedSerializable = { + if (it == Detail::class.java) throw AnnotationFormatError("malformed annotation") + true + }, + ) + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home)) + + assertThat(mapped).containsExactly(null, SentryBackStackEntry("Home")).inOrder() + } + + @Test + fun `propagates a fatal error the annotation check throws`() { + val error = OutOfMemoryError() + val fixture = Fixture.create(isAnnotatedSerializable = { throw error }) + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Generic types + + @Test + fun `returns null for entries of a generic @Serializable type`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + val mapped = mapper.map(Generic("1")) + + assertThat(mapped).isNull() + } + + @Test + fun `doesn't look up serializers for generic @Serializable types`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + mapper.map(Generic("1")) + + assertThat(fixture.lookedUpTypes).isEmpty() + } + + // Serializer lookup failures + + @Test + fun `returns null and logs that no serializer was found when the serializer lookup finds none`() { + val fixture = Fixture.create(lookUpSerializer = { null }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifySerializerNotFoundLogged(fixture.logger) + } + + @Test + fun `returns null and logs the error when the serializer lookup throws a LinkageError`() { + val error = NoSuchMethodError("kotlinx.serialization.KSerializer.getDescriptor()") + val fixture = Fixture.create(lookUpSerializer = { throw error }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, error) + } + + @Test + fun `returns null and logs the error when the serializer lookup throws a ReflectiveOperationException`() { + val error = NoSuchMethodException("serializer") + val fixture = Fixture.create(lookUpSerializer = { throw error }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, error) + } + + @Test + fun `returns null and logs the error when the serializer lookup throws an unchecked exception`() { + val error = TypeNotPresentException("com.example.RemovedSerializer", null) + val fixture = Fixture.create(lookUpSerializer = { throw error }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, error) + } + + @Test + fun `returns null and logs the cause when the serializer lookup throws a wrapped exception`() { + val cause = IllegalStateException("serializer() failed") + val fixture = Fixture.create(lookUpSerializer = { throw InvocationTargetException(cause) }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, cause) + } + + @Test + 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 + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, cause) + } + + @Test + fun `returns null and logs the InvocationTargetException when the serializer lookup throws one without a cause`() { + val error = InvocationTargetException(null) + val fixture = Fixture.create(lookUpSerializer = { throw error }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, error) + } + + @Test + fun `returns null and logs the error when the serializer's descriptor throws`() { + val error = IllegalStateException("descriptor failed") + val serializer = + object : NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = throw error + } + val fixture = Fixture.create(lookUpSerializer = { serializer }) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isNull() + verifyLookUpFailureLogged(fixture.logger, error) + } + + @Test + fun `restores the interrupt flag when the serializer lookup throws InterruptedException`() { + val fixture = Fixture.create(lookUpSerializer = { throw 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 `keeps naming other types after the serializer lookup throws for one type`() { + val fixture = + Fixture.create( + lookUpSerializer = { + if (it == Detail::class.java) throw NoSuchMethodError() else SERIALIZERS[it] + }, + ) + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home), mapper.map(Search("shoes"))) + + assertThat(mapped) + .containsExactly(null, SentryBackStackEntry("Home"), SentryBackStackEntry("Search")) + .inOrder() + } + + @Test + fun `propagates a fatal error the serializer lookup throws`() { + val error = OutOfMemoryError() + val fixture = Fixture.create(lookUpSerializer = { throw error }) + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Caching + + @Test + fun `looks up each @Serializable type's serializer once, including failed lookups`() { + val fixture = + Fixture.create(lookUpSerializer = { if (it == Search::class.java) null else SERIALIZERS[it] }) + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Home) + mapper.map(Detail("$it")) + mapper.map(Search("$it")) + } + + assertThat(fixture.lookedUpTypes) + .containsExactly(Home::class.java, Detail::class.java, Search::class.java) + } + + @Test + fun `looks up an enum with constant bodies once for all its constants`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + mapper.map(TabWithBodies.FEED) + mapper.map(TabWithBodies.SEARCH) + + assertThat(fixture.lookedUpTypes).containsExactly(TabWithBodies::class.java) + } + + @Test + fun `doesn't look up a type's serializer again after the serializer lookup throws`() { + val fixture = Fixture.create(lookUpSerializer = { throw NoSuchMethodError() }) + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java) + } + + @Test + fun `doesn't check a type's annotation or look up its serializer again after the annotation check throws`() { + val checkedTypes = mutableListOf>() + val fixture = + Fixture.create( + isAnnotatedSerializable = { + checkedTypes += it + throw NoClassDefFoundError() + }, + ) + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(checkedTypes).containsExactly(Detail::class.java) + assertThat(fixture.lookedUpTypes).isEmpty() + } + + @Test + fun `looks up a type's serializer again after the serializer lookup throws a fatal error`() { + var hasThrown = false + val fixture = + Fixture.create( + lookUpSerializer = { + if (!hasThrown) { + hasThrown = true + throw OutOfMemoryError() + } + Detail.serializer() + }, + ) + val mapper = fixture.mapper + assertFailsWith { mapper.map(Detail("1")) } + + 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() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(NotSerializable("$it")) + mapper.map("home") + mapper.map(Home) + } + + verifyNotSerializableLogged(fixture.logger, NotSerializable::class.java) + verifyNotSerializableLogged(fixture.logger, String::class.java) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `logs each generic @Serializable type once`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Generic("$it")) + mapper.map(Home) + } + + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + argThat { contains("because the type has type parameters") }, + eq(Generic::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `logs each type whose serializer lookup fails once`() { + val error = NoSuchMethodError() + val fixture = + Fixture.create( + lookUpSerializer = { + when (it) { + Detail::class.java -> null + Search::class.java -> throw error + else -> SERIALIZERS[it] + } + }, + ) + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail("$it")) + mapper.map(Search("$it")) + mapper.map(Home) + } + + verifySerializerNotFoundLogged(fixture.logger, Detail::class.java) + verifyLookUpFailureLogged(fixture.logger, error, Search::class.java) + verifyNoMoreInteractions(fixture.logger) + } + + // Unknown entry reasons + + @Test + fun `reports no reason for an entry it names`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(reason).isNull() + } + + @Test + fun `reports entry not annotated for an entry whose type isn't annotated @Serializable`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(NotSerializable("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.ENTRY_NOT_ANNOTATED) + } + + @Test + fun `reports serializer access threw for an entry whose annotation check throws an exception`() { + val fixture = + Fixture.create( + isAnnotatedSerializable = { throw AnnotationFormatError("malformed annotation") }, + ) + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_ACCESS_THREW) + } + + @Test + fun `reports serializer access threw for an entry whose annotation check throws a LinkageError`() { + val fixture = + Fixture.create( + isAnnotatedSerializable = { throw NoClassDefFoundError("com/example/MissingAnnotation") }, + ) + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_ACCESS_THREW) + } + + @Test + fun `reports generic entry type for an entry of a generic @Serializable type`() { + val fixture = Fixture.create() + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(Generic("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.GENERIC_ENTRY_TYPE) + } + + @Test + fun `reports serializer not found for an entry whose serializer lookup finds none`() { + val fixture = Fixture.create(lookUpSerializer = { null }) + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_NOT_FOUND) + } + + @Test + fun `reports serializer access threw for an entry whose serializer lookup throws an exception`() { + val fixture = + Fixture.create(lookUpSerializer = { throw IllegalStateException("lookup failed") }) + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_ACCESS_THREW) + } + + @Test + fun `reports serializer access threw for an entry whose serializer lookup throws a LinkageError`() { + val fixture = Fixture.create(lookUpSerializer = { throw NoSuchMethodError() }) + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReporter.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_ACCESS_THREW) + } + + @Test + fun `reports the reason again for every later entry of a type that can't be named`() { + val fixture = + Fixture.create(lookUpSerializer = { if (it == Detail::class.java) null else SERIALIZERS[it] }) + val mapper = fixture.mapper + val entries = + listOf( + Detail("1"), + NotSerializable("1"), + Generic("1"), + Detail("2"), + NotSerializable("2"), + Generic("2"), + ) + + val reasons = entries.map { entry -> + UnknownEntryReasonReporter.collect { mapper.map(entry) }.reason + } + + assertThat(reasons) + .containsExactly( + UnknownEntryReason.SERIALIZER_NOT_FOUND, + UnknownEntryReason.ENTRY_NOT_ANNOTATED, + UnknownEntryReason.GENERIC_ENTRY_TYPE, + UnknownEntryReason.SERIALIZER_NOT_FOUND, + UnknownEntryReason.ENTRY_NOT_ANNOTATED, + UnknownEntryReason.GENERIC_ENTRY_TYPE, + ) + .inOrder() + } + + private fun verifyNotSerializableLogged(logger: ILogger, type: Class<*>) { + verify(logger) + .log( + eq(SentryLevel.WARNING), + argThat { contains("because the type is not @Serializable") }, + eq(type.name), + ) + } + + private fun verifySerializerNotFoundLogged(logger: ILogger, type: Class<*> = Detail::class.java) { + verify(logger) + .log( + eq(SentryLevel.WARNING), + isNull(), + any(), + eq(type.name), + eq(SERIALIZER_NOT_FOUND), + ) + } + + private fun verifyLookUpFailureLogged( + logger: ILogger, + error: Throwable, + type: Class<*> = Detail::class.java, + ) { + verify(logger) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(type.name), eq(LOOK_UP_FAILED)) + } + + private companion object { + val SERIALIZERS: Map, KSerializer<*>> = + mapOf( + Home::class.java to Home.serializer(), + Detail::class.java to Detail.serializer(), + Search::class.java to Search.serializer(), + TabWithBodies::class.java to TabWithBodies.serializer(), + ) + } + + /** + * A [KotlinxBackStackEntryMapper] whose serializer lookups are recorded in [lookedUpTypes]. + * Without an `isAnnotatedSerializable` check, the mapper reads each type's real `@Serializable` + * annotation. + */ + private class Fixture + private constructor( + lookUpSerializer: (Class<*>) -> KSerializer<*>?, + isAnnotatedSerializable: ((Class<*>) -> Boolean)?, + probe: CompatibilityProbe, + ) { + val logger = mock() + val lookedUpTypes = mutableListOf>() + val mapper: KotlinxBackStackEntryMapper + + init { + val recordingLookUp: (Class<*>) -> KSerializer<*>? = { type -> + lookedUpTypes += type + lookUpSerializer(type) + } + mapper = + if (isAnnotatedSerializable == null) { + KotlinxBackStackEntryMapper(recordingLookUp, probe = probe, logger = { logger }) + } else { + KotlinxBackStackEntryMapper(recordingLookUp, isAnnotatedSerializable, probe, { logger }) + } + } + + companion object { + fun create( + lookUpSerializer: (Class<*>) -> KSerializer<*>? = { SERIALIZERS[it] }, + isAnnotatedSerializable: ((Class<*>) -> Boolean)? = null, + probe: CompatibilityProbe = FakeCompatibilityProbe(), + ) = Fixture(lookUpSerializer, isAnnotatedSerializable, probe) + } + } +} 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 new file mode 100644 index 00000000000..a72868dd03f --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperDiagnosticsTest.kt @@ -0,0 +1,151 @@ +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 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 + +class KotlinxMapperDiagnosticsTest { + + private val logger = mock() + private val diagnostics = KotlinxMapperDiagnostics { logger } + + private val type = Detail::class.java + + // notSerializable() + + @Test + fun `notSerializable() - logs a warning for the type that advises adding @Serializable`() { + diagnostics.notSerializable(type) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains("because the type is not @Serializable") + assertThat(message.firstValue).contains("Add @Serializable") + } + + // genericType() + + @Test + fun `genericType() - logs a warning for the type that advises a custom BackStackEntryMapper`() { + diagnostics.genericType(type) + + val message = argumentCaptor() + verify(logger).log(eq(SentryLevel.WARNING), message.capture(), eq(type.name)) + assertThat(message.firstValue).contains("because the type has type parameters") + assertThat(message.firstValue).contains("Use a custom BackStackEntryMapper") + } + + // inconclusiveProbe() + + @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") + } + + @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), + isNull(), + message.capture(), + eq(PROBE_SERIALIZER_NOT_FOUND), + ) + assertThat(message.firstValue) + .startsWith("Nav3 couldn't verify kotlinx.serialization support for name lookups") + } + + // unresolved() + + @Test + fun `unresolved() - logs the error with advice to see it, without compatibility advice, for an exception`() { + val error = IllegalStateException("lookup failed") + + diagnostics.unresolved(type, error) + + val message = loggedUnresolvedMessage(error, LOOK_UP_FAILED) + assertThat(message).contains("See the attached error") + assertThat(message).doesNotContain(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `unresolved() - logs the error with compatibility advice for a LinkageError`() { + val error = NoSuchMethodError("kotlinx.serialization.KSerializer.getDescriptor()") + + diagnostics.unresolved(type, error) + + val message = loggedUnresolvedMessage(error, LOOK_UP_FAILED) + assertThat(message).contains("See the attached error") + assertThat(message).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `unresolved() - logs the error without compatibility advice for an ExceptionInInitializerError`() { + val error = ExceptionInInitializerError(IllegalStateException("serializer init failed")) + + diagnostics.unresolved(type, error) + + val message = loggedUnresolvedMessage(error, LOOK_UP_FAILED) + assertThat(message).contains("See the attached error") + assertThat(message).doesNotContain(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `unresolved() - logs that no serializer was found with advice to see the docs when there's no error`() { + diagnostics.unresolved(type, null) + + val message = loggedUnresolvedMessage(null, SERIALIZER_NOT_FOUND) + assertThat(message).contains("See BackStackEntryMapper.SerialName's documentation") + assertThat(message).doesNotContain(INCOMPATIBLE_KOTLINX_ADVICE) + } + + // MIN_KOTLINX_SERIALIZATION_VERSION + + @Test + fun `MIN_KOTLINX_SERIALIZATION_VERSION matches kotlinxSerialization-floor in the dependency matrix catalog`() { + val floor = + checkNotNull(System.getProperty(KOTLINX_SERIALIZATION_FLOOR_PROPERTY)) { + "System property $KOTLINX_SERIALIZATION_FLOOR_PROPERTY is missing. Run this test through " + + "Gradle, which sets it from kotlinxSerialization-floor in " + + "gradle/dependency-matrix.versions.toml." + } + + assertThat(MIN_KOTLINX_SERIALIZATION_VERSION).isEqualTo(floor) + } + + /** + * Returns the message of the warning [diagnostics] logged for [type] with [error] and [reason]. + */ + private fun loggedUnresolvedMessage(error: Throwable?, reason: String): String { + val message = argumentCaptor() + verify(logger) + .log(eq(SentryLevel.WARNING), eq(error), message.capture(), eq(type.name), eq(reason)) + return message.firstValue + } + + private companion object { + const val KOTLINX_SERIALIZATION_FLOOR_PROPERTY = "nav3.kotlinxSerializationFloor" + } +} 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 new file mode 100644 index 00000000000..bb3b036ed79 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt @@ -0,0 +1,380 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import java.lang.reflect.InvocationTargetException +import kotlin.test.assertFailsWith +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Test + +class KotlinxSerializerLookupTest { + + @Serializable + @SerialName("Route") + sealed interface Route { + @Serializable @SerialName("route.settings") data object Settings : Route + } + + @Serializable + @SerialName("Tab") + enum class Tab { + FEED, + } + + @Serializable + @SerialName("TabWithBodies") + enum class TabWithBodies { + FEED { + override val icon = "feed" + }; + + abstract val icon: String + } + + @Serializable(with = CustomSerializer::class) internal data class CustomSerialized(val id: String) + + internal object CustomSerializer : NamingOnlySerializer() { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + } + + @Serializable @SerialName("PrivateObject") private data object PrivateObject + + @Serializable @SerialName("PrivateClass") private data class PrivateClass(val id: String) + + data class NotSerializable(val id: String) + + /** + * Looks like a private object to kotlinx.serialization, as it has a private static `INSTANCE` + * field of its own type, but lacks the `serializer()` method the compiler plugin generates. + */ + class InaccessibleInstanceWithoutSerializer private constructor() { + private companion object { + @Suppress("unused") private val INSTANCE = InaccessibleInstanceWithoutSerializer() + } + } + + /** + * Looks like a private object to kotlinx.serialization, as for + * [InaccessibleInstanceWithoutSerializer], but its `serializer()` method returns something other + * than a serializer. + */ + class InaccessibleInstanceWithNonSerializer private constructor() { + @Suppress("unused", "FunctionOnlyReturningConstant") fun serializer(): Any = "not a serializer" + + private companion object { + @Suppress("unused") private val INSTANCE = InaccessibleInstanceWithNonSerializer() + } + } + + enum class UnannotatedTab { + FEED, + } + + @Serializable data class Generic(val value: T) + + // A class whose serializer's initializer threw can't be initialized again for the rest of the + // JVM's life, so each test that triggers one gets its own pair, separate from other suites'. + + @Serializable(with = UninitializableSerializer::class) internal class Uninitializable + + internal object UninitializableSerializer : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable", PrimitiveKind.STRING) + } + + @Serializable(with = IncompatiblyUninitializableSerializer::class) + internal class IncompatiblyUninitializable + + internal object IncompatiblyUninitializableSerializer : + NamingOnlySerializer() { + init { + // As for FatallyUninitializableSerializer, the error isn't wrapped in an + // ExceptionInInitializerError. + if (System.nanoTime() != 0L) throw NoSuchMethodError("serializer init failed to link") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("incompatible", PrimitiveKind.STRING) + } + + @Serializable(with = PrivateUninitializableSerializer::class) + private object PrivateUninitializable + + private object PrivateUninitializableSerializer : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("private serializer init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("private.uninitializable", PrimitiveKind.STRING) + } + + @Serializable(with = FatallyUninitializableSerializer::class) private object PrivateFatal + + private object FatallyUninitializableSerializer : NamingOnlySerializer() { + init { + // Unlike an exception, an error thrown by an initializer isn't wrapped in an + // ExceptionInInitializerError. + if (System.nanoTime() != 0L) throw OutOfMemoryError("serializer init failed fatally") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("fatal", PrimitiveKind.STRING) + } + + @Serializable(with = PublicFatallyUninitializableSerializer::class) + internal class FatallyUninitializable + + internal object PublicFatallyUninitializableSerializer : + NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) throw OutOfMemoryError("class serializer init failed fatally") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("fatal.class", PrimitiveKind.STRING) + } + + // A serializer class, unlike an object, is constructed by the type's serializer() method, so an + // exception its constructor throws reaches reflection without an ExceptionInInitializerError. + + @Serializable(with = FailingConstructionSerializer::class) internal class FailingConstruction + + internal class FailingConstructionSerializer : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer construction failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("failingConstruction", PrimitiveKind.STRING) + } + + @Serializable(with = InterruptedConstructionSerializer::class) + internal class InterruptedConstruction + + internal class InterruptedConstructionSerializer : + NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) throw InterruptedException("serializer construction interrupted") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("interruptedConstruction", PrimitiveKind.STRING) + } + + // @Serializable types + + @Test + fun `returns the serializer of a @Serializable class`() { + val serializer = reflectiveSerializerOrNull(Detail::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Detail") + } + + @Test + fun `returns the serializer of a @Serializable object`() { + val serializer = reflectiveSerializerOrNull(Home::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Home") + } + + @Test + fun `returns the subtype's own serializer for a @Serializable sealed subtype`() { + val serializer = reflectiveSerializerOrNull(Route.Settings::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("route.settings") + } + + @Test + fun `returns the serializer of a @Serializable enum`() { + val serializer = reflectiveSerializerOrNull(Tab::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Tab") + } + + @Test + fun `returns the custom serializer of a class that is @Serializable with a custom serializer`() { + val serializer = reflectiveSerializerOrNull(CustomSerialized::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("custom.Name") + } + + @Test + fun `returns the serializer of a private @Serializable object`() { + val serializer = reflectiveSerializerOrNull(PrivateObject::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateObject") + } + + @Test + fun `returns the serializer of a private @Serializable class`() { + val serializer = reflectiveSerializerOrNull(PrivateClass::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateClass") + } + + // Types that aren't @Serializable but that kotlinx.serialization can serialize + + @Test + fun `returns kotlinx serialization's serializers for built-in types`() { + val types = listOf(String::class.java, Integer::class.java) + + val serialNames = types.map { reflectiveSerializerOrNull(it)?.descriptor?.serialName } + + assertThat(serialNames).containsExactly("kotlin.String", "kotlin.Int").inOrder() + } + + @Test + fun `returns kotlinx serialization's enum serializer for an enum that isn't @Serializable`() { + val serializer = reflectiveSerializerOrNull(UnannotatedTab::class.java) + + assertThat(serializer?.descriptor?.serialName) + .isEqualTo(UnannotatedTab::class.java.canonicalName) + } + + // Types without a serializer to return + + @Test + fun `returns null for a class that isn't @Serializable`() { + val serializer = reflectiveSerializerOrNull(NotSerializable::class.java) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for the class of a @Serializable enum's constant that has a body`() { + val serializer = reflectiveSerializerOrNull(TabWithBodies.FEED.javaClass) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for a generic @Serializable class`() { + val serializer = reflectiveSerializerOrNull(Generic::class.java) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for a generic built-in collection type`() { + val serializer = reflectiveSerializerOrNull(ArrayList::class.java) + + assertThat(serializer).isNull() + } + + // Serializer initializers that throw + + @Test + fun `throws a class's serializer initializer error wrapped in an InvocationTargetException`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(Uninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .isEqualTo("serializer init failed") + } + + @Test + fun `throws a class's serializer initializer NoSuchMethodError wrapped in an InvocationTargetException`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(IncompatiblyUninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(NoSuchMethodError::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed to link") + } + + @Test + fun `throws a private object's serializer initializer error wrapped in an InvocationTargetException`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(PrivateUninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .isEqualTo("private serializer init failed") + } + + @Test + fun `throws an exception from a class's serializer construction wrapped in an InvocationTargetException`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(FailingConstruction::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(IllegalStateException::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer construction failed") + } + + @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() + } + } + + @Test + fun `propagates a class's fatal serializer initializer error unwrapped`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(FatallyUninitializable::class.java) + } + + assertThat(thrown).hasMessageThat().isEqualTo("class serializer init failed fatally") + } + + @Test + fun `propagates a private object's fatal serializer initializer error unwrapped`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(PrivateFatal::class.java) + } + + assertThat(thrown).hasMessageThat().isEqualTo("serializer init failed fatally") + } + + // Private object lookups that find no serializer + + @Test + fun `throws the reflection error when a type with an inaccessible INSTANCE field has no serializer method`() { + val thrown = + assertFailsWith { + reflectiveSerializerOrNull(InaccessibleInstanceWithoutSerializer::class.java) + } + + assertThat(thrown).hasMessageThat().contains("serializer") + } + + @Test + fun `returns null when a type with an inaccessible INSTANCE field has a serializer() that returns no KSerializer`() { + val serializer = reflectiveSerializerOrNull(InaccessibleInstanceWithNonSerializer::class.java) + + assertThat(serializer).isNull() + } +} 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 new file mode 100644 index 00000000000..1a1339a038c --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -0,0 +1,43 @@ +@file:Suppress("MatchingDeclarationName") + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +@Serializable @SerialName("Home") internal data object Home + +@Serializable @SerialName("Detail") internal data class Detail(val id: String) + +@Serializable @SerialName("Search") internal data class Search(val query: String) + +/** A serializer for tests that only read its descriptor, e.g., to name an entry. */ +internal abstract class NamingOnlySerializer : KSerializer { + override fun serialize(encoder: Encoder, value: T) = throw UnsupportedOperationException() + + 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/NavDataContractTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt index 947d710a8b1..8fd55c57caf 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt @@ -63,6 +63,16 @@ class NavDataContractTest { "mapping_failed", UnknownEntryReason.UNMAPPED, "unmapped", + UnknownEntryReason.ENTRY_NOT_ANNOTATED, + "entry_not_annotated", + UnknownEntryReason.GENERIC_ENTRY_TYPE, + "generic_entry_type", + UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION, + "kotlinx_serialization_version", + UnknownEntryReason.SERIALIZER_ACCESS_THREW, + "serializer_access_threw", + UnknownEntryReason.SERIALIZER_NOT_FOUND, + "serializer_not_found", ) } 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/contract/UnknownEntryReasonReporterTest.kt new file mode 100644 index 00000000000..eea71458579 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/UnknownEntryReasonReporterTest.kt @@ -0,0 +1,97 @@ +package io.sentry.compose.navigation3.internal.contract + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.contract.UnknownEntryReasonReporter.Collected +import kotlin.concurrent.thread +import kotlin.test.assertFailsWith +import org.junit.Test + +class UnknownEntryReasonReporterTest { + + @Test + fun `collect() - returns the block's result without a reason when nothing is reported`() { + val collected = UnknownEntryReasonReporter.collect { "result" } + + assertThat(collected).isEqualTo(Collected("result", null)) + } + + @Test + fun `collect() - returns the block's result with the reason reported while it ran`() { + val collected = UnknownEntryReasonReporter.collect { + UnknownEntryReasonReporter.report(UnknownEntryReason.ENTRY_NOT_ANNOTATED) + null + } + + assertThat(collected).isEqualTo(Collected(null, UnknownEntryReason.ENTRY_NOT_ANNOTATED)) + } + + @Test + fun `collect() - returns the last reason reported when the block reports several`() { + val collected = UnknownEntryReasonReporter.collect { + UnknownEntryReasonReporter.report(UnknownEntryReason.ENTRY_NOT_ANNOTATED) + UnknownEntryReasonReporter.report(UnknownEntryReason.GENERIC_ENTRY_TYPE) + null + } + + assertThat(collected.reason).isEqualTo(UnknownEntryReason.GENERIC_ENTRY_TYPE) + } + + @Test + fun `collect() - ignores a reason reported before it was called`() { + UnknownEntryReasonReporter.report(UnknownEntryReason.ENTRY_NOT_ANNOTATED) + + val collected = UnknownEntryReasonReporter.collect { null } + + assertThat(collected.reason).isNull() + } + + @Test + fun `collect() - does not keep the reason reported in its block after it returns`() { + val collected = UnknownEntryReasonReporter.collect { + UnknownEntryReasonReporter.collect { + UnknownEntryReasonReporter.report(UnknownEntryReason.ENTRY_NOT_ANNOTATED) + null + } + null + } + + assertThat(collected.reason).isNull() + } + + @Test + fun `collect() - does not keep the reason reported in its block after the block throws`() { + val collected = UnknownEntryReasonReporter.collect { + runCatching { + UnknownEntryReasonReporter.collect { + UnknownEntryReasonReporter.report(UnknownEntryReason.ENTRY_NOT_ANNOTATED) + error("boom") + } + } + null + } + + assertThat(collected.reason).isNull() + } + + @Test + fun `collect() - rethrows the exception thrown by the block unchanged`() { + val exception = IllegalStateException("boom") + + val thrown = + assertFailsWith { + UnknownEntryReasonReporter.collect { throw exception } + } + + assertThat(thrown).isSameInstanceAs(exception) + } + + @Test + fun `collect() - ignores a reason reported on another thread while the block runs`() { + val collected = UnknownEntryReasonReporter.collect { + thread { UnknownEntryReasonReporter.report(UnknownEntryReason.ENTRY_NOT_ANNOTATED) }.join() + null + } + + assertThat(collected.reason).isNull() + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 18340a6c241..652e86912b9 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -38,6 +38,11 @@ dependencyResolutionManagement { mavenCentral() mavenLocal() } + versionCatalogs { + create("matrixLibs") { + from(files("gradle/dependency-matrix.versions.toml")) + } + } } rootProject.name = "sentry-root"