diff --git a/CHANGELOG.md b/CHANGELOG.md index f2815aaef7f..7abe96335b5 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 kotlinx.serialization serial names ([#6703](https://github.com/getsentry/sentry-java/pull/6703)) + ### Behavioral Changes - Nav3: If a back stack entry's arguments contain a map with two keys that are recorded as the same string (e.g., `1` and `"1"`), Sentry now drops that entry's arguments and records `dropped_by_sentry: duplicate_key`, instead of keeping only one of the values ([#6701](https://github.com/getsentry/sentry-java/pull/6701)) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 56c294c6ad9..2e099f1ab00 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -68,6 +68,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/gradle/nav3.versions.toml b/gradle/nav3.versions.toml new file mode 100644 index 00000000000..1513888127a --- /dev/null +++ b/gradle/nav3.versions.toml @@ -0,0 +1,15 @@ +# Versions for sentry-android-navigation3's kotlinx.serialization compatibility checks, registered as +# the `nav3Libs` catalog. +# +# Kept apart from libs.versions.toml so that the Nav3 R8 check workflow can run on PRs that change +# them without also running on every unrelated dependency bump. + +[versions] +# The oldest kotlinx.serialization version sentry-android-navigation3 supports, which it compiles and +# tests against. Nav3 builds apply it explicitly rather than via version.ref to prevent Dependabot +# from modifying it. When updating, also update MIN_KOTLINX_SERIALIZATION_VERSION in +# KotlinxMapperDiagnostics (KotlinxBackStackEntryMapper.kt); a unit test fails if the two don't match. +kotlinxSerializationFloor = "1.7.3" + +[libraries] +kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core" } diff --git a/sentry-android-navigation3/README.md b/sentry-android-navigation3/README.md index 95bbbeb006b..2135233aefd 100644 --- a/sentry-android-navigation3/README.md +++ b/sentry-android-navigation3/README.md @@ -6,7 +6,7 @@ Use `SentryNavEffect` alongside your `NavDisplay` to record navigation transacti users move around your app. Configure the data you want captured via `SentryNavOptions`. 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..65b7f6dbc79 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 = nav3Libs.versions.kotlinxSerializationFloor.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,22 @@ android { kotlin { explicitApi() } +// Unit tests run against the kotlinx.serialization floor by default. CI also runs them against the +// latest version (-Pnav3TestKotlinxVersion=), as apps may ship a newer +// kotlinx.serialization dependency than sentry-android-navigation3 compiles against. +val testKotlinxVersion = + providers.gradleProperty("nav3TestKotlinxVersion").orNull ?: kotlinxSerializationFloor + 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) + // All Nav3 apps depend on kotlinx.serialization via navigation3-runtime. + compileOnly(nav3Libs.kotlinx.serialization.core) { + version { require(kotlinxSerializationFloor) } + } testImplementation(projects.sentryAndroidCore) testImplementation(projects.sentryTestSupport) @@ -88,6 +103,10 @@ dependencies { testImplementation(libs.androidx.viewpager2) testImplementation(libs.google.truth) testImplementation(libs.kotlin.test.junit) + testImplementation(nav3Libs.kotlinx.serialization.core) { + // Avoid using whatever version test deps happen to pull in transitively. + version { strictly(testKotlinxVersion) } + } testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) testImplementation(libs.roboelectric) 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 b4b93fa4743..0ce6a4f534e 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,5 +1,6 @@ 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. */ @@ -53,12 +54,16 @@ public class SentryBackStackEntry( /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * To be implemented by the host app. + * If you use kotlinx.serialization, see [SerialName] for convenient, out-of-the-box mappers. + * Otherwise, provide your own implementation. (Note: Custom implementations can always 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. + * Custom mappers are responsible for filtering their own arguments. + * + * Only return names and arguments that are known to be safe or have been pre-scrubbed. All + * arguments remain subject to size and structural limits. * * **Performance** * @@ -91,7 +96,8 @@ public class SentryBackStackEntry( * - [CharSequence] * - [Char] * - [Boolean] - * - any [Number] (`NaN` and infinite values are sent as strings) + * - any [Number] (`NaN` and infinite values are sent as the strings `"NaN"`, `"Infinity"`, and + * `"-Infinity"`, which JSON can represent) * - enums (via [Enum.name]) * - `null` * @@ -106,46 +112,82 @@ public class SentryBackStackEntry( * * **Arguments fall back to `toString()` or nothing** * - * All non-supported argument types are stringified via `toString()`. + * 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. If the SDK drops an entry's arguments, it - * adds a `dropped_by_sentry` field and corresponding reason 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) - * ) - * ... - * } - * } - * ``` + * 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. */ @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 name of each of their back stack entries (and not each entry's properties). + * + * For instance, given: + * ``` + * @Serializable + * @SerialName("ProductDetail") + * data class ProductDetail( + * val userId: String, + * val productId: String + * ) : NavKey + * ``` + * + * when navigating to `ProductDetail(userId = "123abc", productId = "zyx987")`, this mapper + * would return `"ProductDetail"` as the destination's name, but would ***not*** return the + * destination's properties (`userId` and `productId`). + * + * **Name == SerialDescriptor.serialName** + * + * This mapper names each back stack entry after the entry's + * [`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"). + * + * **Unknown names** + * + * This mapper returns `null` for an entry, which Sentry displays as `"/unknown"`, if: + * + * - the entry class isn't annotated with `@Serializable` itself, even if kotlinx.serialization + * can serialize it without the annotation (e.g., `String`, `List`, an unannotated enum, or a + * class marked with a custom `@MetaSerializable` annotation); + * + * - the entry class is generic (e.g., `SettingsScreen`), as its serializer needs type + * arguments that can't be recovered from the entry at runtime; or + * + * - looking up the entry's serializer fails, e.g., because a custom serializer throws, R8 + * removed what the lookup needs, or the app's kotlinx.serialization version is incompatible + * with this SDK. + * + * The first entry of each class that can't be named logs a warning explaining why, visible when + * the SDK's `debug` option is enabled. For fixes, see + * [Troubleshooting](https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers) + * in the Sentry Android Navigation docs. + * + * **Sharing names** + * + * Entries share a Sentry name whenever their serializers share a serial name. In particular: + * + * - All constants of an enum are named after the enum. A `@SerialName` on a constant does not + * change the destination name. + * + * - Classes that use the same custom serializer (`@Serializable(with = ...)`) are named after + * that serializer's descriptor, which ignores a `@SerialName` on the class. + * + * To tell such entries apart, define a custom [BackStackEntryMapper], e.g., one that names enum + * constants after [Enum.name]. + */ + @get:ApiStatus.Experimental + public val SerialName: BackStackEntryMapper + get() = BuiltInBackStackEntryMappers.serialName + } } 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/BuiltInBackStackEntryMappers.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt new file mode 100644 index 00000000000..703f2d2e9bb --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -0,0 +1,120 @@ +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.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap + +internal object BuiltInBackStackEntryMappers { + + /** + * 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 a mapper can't be created. + * + * See [BackStackEntryMapper.SerialName] for more details. + */ + val serialName: BackStackEntryMapper by + lazy(LazyThreadSafetyMode.PUBLICATION) { + // PUBLICATION avoids holding a lock while mapper creation calls the app's logger. Racing + // threads may each create and probe a mapper and log warnings, and all but the first + // published instance would be discarded. + create(logger) { + KotlinxBackStackEntryMapper(logger = logger) + } + } + + private val logger: () -> ILogger = { ScopesAdapter.getInstance().options.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) { + // An incompatible kotlinx.serialization version can throw a LinkageError while the mapper is + // created, either because a class the mapper uses can't be linked or because the mapper's + // compatibility probe failed to look up names. We catch the error here so that every entry + // falls back to UNKNOWN_ENTRY_NAME instead of crashing the app. + // + // Construction runs no host app code, only kotlinx.serialization's and the SDK's, so this + // also catches an ExceptionInInitializerError from either. We fall back rather than crash, + // and log the error for diagnosis. + logger() + .log( + WARNING, + // The compiler inlines INCOMPATIBLE_KOTLINX_ADVICE, and it's 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 when a built-in [BackStackEntryMapper] isn't supported by the host app. + * + * Maps every back stack entry to `null`, which Sentry records as [UNKNOWN_ENTRY_NAME]. 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, + ) + } + + return null + } +} + +/** + * 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/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..fef70e5bd0d --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -0,0 +1,282 @@ +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.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.util.ExceptionUtils +import java.lang.reflect.InvocationTargetException +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. + */ + private val lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, + logger: () -> ILogger, + probe: KotlinxCompatibilityProbe = KotlinxCompatibilityProbe, +) : BackStackEntryMapper { + + // Resolved here, rather than on the first map() call, so that if kotlinx.serialization is + // missing, creating this mapper fails and BuiltInBackStackEntryMappers falls back to + // UnavailableBackStackEntryMapper. + private val serializableAnnotation: Class = Serializable::class.java + + // 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 { + // Check name-lookup support during construction so an incompatible kotlinx.serialization + // version triggers the use of UnavailableBackStackEntryMapper. Later LinkageErrors likely come + // from the entry's own type and are handled per type. + probe + .nameLookupLinkageError { error -> + diagnostics.inconclusiveProbe(NAME_LOOKUP_CAPABILITY, 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 = cachedType(type) + val name = cached.name ?: return null + + return SentryBackStackEntry(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 name. Logs if it can't be named. + * + * Never throws for a non-fatal error. Instead, a lookup that fails returns [UNRESOLVED], which + * [cachedType] caches, so each type's failure is queried and logged only once. + */ + @OptIn(ExperimentalSerializationApi::class) + private fun lookUp(type: Class<*>): CachedType { + // Checked before the lookup, which would otherwise return serializers for types that aren't + // @Serializable. + if (!isMarkedSerializable(type)) { + return UNRESOLVED + } + + // Serializer lookup and descriptor access may run host app code. Failures affect only this + // type. + val lookup = lookUpSerializerCatching(type) + val serializer = lookup.serializer + var error = lookup.error + + val name = + try { + serializer?.descriptor?.let { descriptor -> + descriptor.serialName + } + } catch (e: LinkageError) { + // Treat descriptor linkage errors as type-specific, including incompatibilities caused by a + // serializer compiled against another kotlinx.serialization version. + error = e + null + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Custom descriptors may throw anything. Catch broadly to log once and cache the type as + // unresolved, avoiding repeated lookups. Entries use UNKNOWN_ENTRY_NAME. + ExceptionUtils.rethrowIfFatal(t) + error = t + null + } + + if (name == null) { + diagnostics.unresolved(type, error) + } + return if (name == null) UNRESOLVED else CachedType(name) + } + + /** + * Whether [type] is annotated with `@Serializable`. Logs why it can't be named if the annotation + * is absent or can't be read. + * + * We only name types the host app marks as `@Serializable`. kotlinx.serialization provides + * serializers for built-in types (e.g. String, Int) and enums, but their serial names would be + * misleading ("kotlin.String") or derived from an obfuscated class name. + */ + private fun isMarkedSerializable(type: Class<*>): Boolean = + try { + type.isAnnotationPresent(serializableAnnotation).also { isMarked -> + if (!isMarked) { + diagnostics.notSerializable(type) + } + } + } catch (e: LinkageError) { + // As for the serializer lookup, a LinkageError from reading this type's annotations only + // fails this type. + diagnostics.unresolved(type, e) + false + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Catch broadly because annotation parsing has undocumented failure modes. Cache failures as + // unresolved so the type records UNKNOWN_ENTRY_NAME and logs once, rather than throwing from + // map() and retrying on every navigation. + ExceptionUtils.rethrowIfFatal(t) + diagnostics.unresolved(type, t) + false + } + + /** + * Looks up [type]'s serializer, returning the error that made it fail, if any, instead of + * throwing it. + */ + private fun lookUpSerializerCatching(type: Class<*>): SerializerLookup = + try { + SerializerLookup(lookUpSerializer(type), error = null) + } catch (e: InvocationTargetException) { + // kotlinx.serialization (or our fallback for private objects) calls the type's + // generated serializer() method reflectively, and it threw. For instance, a custom + // serializer object whose initializer throws arrives here with an + // ExceptionInInitializerError as its cause. Only this type is affected. + val cause = e.cause ?: e + // Reflection wraps everything the method throws, fatal errors included, so we apply the + // SDK's fatal-error check to the cause. A LinkageError cause (e.g., that + // ExceptionInInitializerError) only fails this type, so it's exempt. + if (cause !is LinkageError) { + ExceptionUtils.rethrowIfFatal(cause) + } + SerializerLookup(serializer = null, error = cause) + } catch (e: ReflectiveOperationException) { + // Any other reflective failure is specific to this type's serializer members. + SerializerLookup(serializer = null, error = e) + } catch (e: LinkageError) { + // A LinkageError, which the SDK otherwise rethrows as fatal, only fails this type. If the + // app's kotlinx.serialization version couldn't support name lookups at all, the probe that + // ran when this mapper was created would most likely have failed. So the error most likely + // comes from linking or initializing a class this type's serializer needs (e.g., a + // NoSuchMethodError from a serializer compiled against another version, or a + // NoClassDefFoundError for a class that failed to initialize earlier). + SerializerLookup(serializer = null, error = e) + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because the lookup reflects over the app's classes, and the reflection and + // annotation APIs it uses can throw unchecked exceptions of their own (e.g., a + // TypeNotPresentException when R8 removed the serializer a @Serializable(with = ...) + // names). Without this catch, the exception would escape map() uncached and the lookup + // would be repeated on every navigation. Instead, the type is cached as unresolved and + // recorded as UNKNOWN_ENTRY_NAME, with the error logged once. + ExceptionUtils.rethrowIfFatal(t) + SerializerLookup(serializer = null, error = t) + } + + /** A type's serial name, or `null` if the lookup failed. */ + private class CachedType( + val name: String?, + ) + + /** A type's serializer, or the error that made looking it up fail, if any. */ + private class SerializerLookup(val serializer: KSerializer<*>?, val error: Throwable?) + + private companion object { + private const val NAME_LOOKUP_CAPABILITY = "name lookups" + private val UNRESOLVED = CachedType(name = null) + } +} + +/** + * The warnings [KotlinxBackStackEntryMapper] logs when it can't name a back stack entry. + * + * Only decides what's logged, and how often. Whether a type is looked up or encoded again is up to + * the mapper. + */ +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 the probe couldn't verify support for [capability], due to [error] or a missing probe + * serializer if the error is `null`. The mapper handles subsequent failures per type. + */ + fun inconclusiveProbe(capability: String, 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 %s because %s. Handling " + + "failures per entry type.", + capability, + if (error != null) { + "the compatibility probe threw (see the attached error)" + } else { + "a probe serializer wasn't 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. + */ + fun unresolved(type: Class<*>, error: Throwable?) { + val reason = + if (error != null) { + "reading its annotations, serializer, or descriptor failed" + } else { + "no serializer was found (the type may be generic or require R8 keep rules)" + } + val advice = + if (error is LinkageError) { + // 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 `kotlinxSerializationFloor` in `gradle/nav3.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." + } +} 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..afc4bda12b4 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt @@ -0,0 +1,116 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.util.ExceptionUtils +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.Serializable + +/** + * Checks whether the app's kotlinx.serialization 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 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 version is incompatible. + * + * Note: Only a `LinkageError` is conclusive. Any other failure, or a probe type whose serializer + * can't be found, leaves the check inconclusive: 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 interface KotlinxCompatibilityProbe { + + /** + * Verifies [KotlinxBackStackEntryMapper]'s serializer and name lookups with [ProbeClass] and + * [ProbeObject]. + * + * Returns a [LinkageError] if those lookups can't link against the host app's + * kotlinx.serialization version, or `null` if they succeed or the check is inconclusive. + * + * Calls [onInconclusive] for each inconclusive result, passing the cause or `null` if a probe + * type's serializer is unavailable. + */ + fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? + + /** Probes the app's kotlinx.serialization version using [ProbeClass] and [ProbeObject]. */ + companion object : KotlinxCompatibilityProbe { + + override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? { + var isSerializerMissing = false + + val error = + probe(onInconclusive) { + val descriptors = + listOf(ProbeClass::class.java, ProbeObject::class.java).map { type -> + reflectiveSerializerOrNull(type)?.descriptor + } + for (descriptor in descriptors.filterNotNull()) { + descriptor.serialName + descriptor.elementsCount + descriptor.kind + } + isSerializerMissing = null in descriptors + } + + // 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 (@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 and property encoding. Its scalar, list, and map properties + * exercise common encoding paths 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", + val values: List = listOf(1), + val counts: Map = mapOf("count" to 1), + ) + + /** + * 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 + } +} 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..0c88012a1ee --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -0,0 +1,39 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.serializerOrNull + +/** + * Returns the serializer of [type], or `null` if kotlinx.serialization can't provide one (e.g. for + * a generic class whose serializer needs type arguments). + * + * Unlike kotlinx.serialization's [serializerOrNull], this also finds the serializers of private + * `@Serializable` objects. Like it, this returns serializers for built-in types (e.g. `String`) and + * enums that aren't `@Serializable`. + * + * This method may throw, as looking up a serializer can run the type's serializer code for the + * first time (e.g. an [InvocationTargetException][java.lang.reflect.InvocationTargetException] + * whose cause is the serializer initializer's error). + */ +@Suppress("SwallowedException") +internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = + try { + serializerOrNull(type) + } catch (_: IllegalAccessException) { + // kotlinx.serialization reads a serializable object's INSTANCE field without making it + // accessible, which fails for private objects. + privateObjectSerializerOrNull(type) + } + +/** + * Uses reflection to look up the serializer of a private `@Serializable object` through the members + * the serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules + * keep both members.) + * + * 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/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt new file mode 100644 index 00000000000..2e32c345f3d --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -0,0 +1,152 @@ +package io.sentry.compose.navigation3 + +import com.google.common.truth.Truth.assertThat +import java.io.File +import org.junit.Test + +/** Enforces internal dependency rules for `sentry-android-navigation3`. */ +class PackageBoundariesTest { + + private val sources: List = + File(SOURCE_ROOT) + .walkTopDown() + .filter { it.isFile && it.extension == "kt" } + .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 lifecycle package has no imports from other Sentry navigation3 packages, Compose, or AndroidX Nav3`() { + val lifecycleSources = sources.filter { it.packageName.isIn(LIFECYCLE) } + + val violations = lifecycleSources.importsMatching { + (it.isIn(ROOT) && !it.isIn(LIFECYCLE)) || + it.isIn("androidx.navigation3") || + (it.isIn("androidx") && "compose" in it.split('.')) + } + + assertThat(lifecycleSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + // Check that the import reader finds the declarations the rules inspect. + + @Test + fun `reads the package and the targets of plain, aliased, and wildcard imports`() { + val file = File.createTempFile("Parsed", ".kt").apply { deleteOnExit() } + file.writeText( + """ + |@file:OptIn(ExperimentalSerializationApi::class) + | + |package com.example.feature + | + |import com.example.Plain + |import com.example.wildcard.* + |import com.example.Original as Alias + | + |class Parsed + """ + .trimMargin(), + ) + + val parsed = SourceFile.parse(file) + + assertThat(parsed.packageName).isEqualTo("com.example.feature") + assertThat(parsed.imports) + .containsExactly("com.example.Plain", "com.example.wildcard", "com.example.Original") + .inOrder() + } + + @Test + fun `reads imports from the module's Kotlin sources`() { + val imports = sources.flatMap { it.imports } + + assertThat(imports).contains("kotlinx.serialization.KSerializer") + } + + /** A source file's location, package, and import targets. */ + private class SourceFile( + val path: String, + val name: String, + val packageName: String, + val imports: List, + ) { + companion object { + private val PACKAGE = Regex("""^package\s+([\w.]+)""") + private val IMPORT = Regex("""^import\s+([\w.]+?)(?:\.\*)?(?:\s+as\s+\w+)?\s*;?\s*$""") + + fun parse(file: File): SourceFile { + 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) }, + ) + } + } + } + + private companion object { + const val SOURCE_ROOT = "src/main/kotlin" + const val ROOT = "io.sentry.compose.navigation3" + const val KOTLINX = "$ROOT.internal.backstack.kotlinx" + const val LIFECYCLE = "$ROOT.internal.lifecycle" + 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 = + this == packageName || startsWith("$packageName.") + + /** Each import matching [isForbidden], as `path: name`. */ + fun List.importsMatching(isForbidden: (String) -> Boolean): List = + flatMap { file -> + file.imports.filter(isForbidden).map { "${file.path}: $it" } + } + } +} 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..dfe941ee2f8 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,42 @@ class SentryNavEffectTest { assertThat(observedTransactionNames).containsExactly("/HomeRoute", "/ProfileRoute").inOrder() } + @Test + fun `SerialName records serial names, and unknown names 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.scope.navigationBackStack()) + .isEqualTo( + listOf( + mapOf("entry" to "/unknown"), + mapOf("entry" to profileName), + mapOf("entry" to "/SerializableHome"), + ), + ) + } + @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/BuiltInBackStackEntryMappersTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt new file mode 100644 index 00000000000..7bb5c0594d6 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -0,0 +1,344 @@ +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.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.MIN_KOTLINX_SERIALIZATION_VERSION +import io.sentry.test.initForTest +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +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 + +class BuiltInBackStackEntryMappersTest { + + @Serializable @SerialName("Home") data object Home + + @Serializable @SerialName("Detail") data class Detail(val id: String) + + data class NotSerializable(val id: String) + + private val kotlinxMapper = BackStackEntryMapper { SentryBackStackEntry("Kotlinx") } + private val logger = mock() + + // serialName and serialNameAndProperties + + @Test + fun `serialName names entries without recording their properties`() { + val mapper = BuiltInBackStackEntryMappers.serialName + + val mapped = listOf(Home, Detail("1")).map(mapper::map) + + assertThat(mapped) + .containsExactly(SentryBackStackEntry("Home"), SentryBackStackEntry("Detail")) + .inOrder() + } + + // BackStackEntryMapper's companion mappers + + @Test + fun `BackStackEntryMapper SerialName can serve as the mapper for any entry type`() { + val homeMapper: BackStackEntryMapper = BackStackEntryMapper.SerialName + + assertThat(homeMapper.map(Home)).isEqualTo(SentryBackStackEntry("Home")) + } + + @Test + fun `BackStackEntryMapper 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 `BackStackEntryMapper 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() + } + + // First access from several threads + + @Test + fun `BackStackEntryMapper SerialName holds no lock while creating the mapper logs`() { + val race = raceOnFirstAccess("getSerialName") + + assertThat(race.otherThreadLoggerGotAppLock).isTrue() + } + + @Test + fun `BackStackEntryMapper SerialName returns the mapper published first to racing threads`() { + val race = raceOnFirstAccess("getSerialName") + + assertThat(race.otherThreadMapper).isSameInstanceAs(race.thisThreadMapper) + assertThat(race.laterMapper).isSameInstanceAs(race.thisThreadMapper) + } + + // MIN_KOTLINX_SERIALIZATION_VERSION + + @Test + fun `MIN_KOTLINX_SERIALIZATION_VERSION matches kotlinxSerializationFloor in nav3 versions 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 kotlinxSerializationFloor in gradle/nav3.versions.toml." + } + + assertThat(MIN_KOTLINX_SERIALIZATION_VERSION).isEqualTo(floor) + } + + // create() + + @Test + fun `create() - returns the kotlinx mapper when it can be created`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + kotlinxMapper + } + + assertThat(mapper).isSameInstanceAs(kotlinxMapper) + } + + @Test + fun `create() - doesn't log when the kotlinx mapper can be created`() { + BuiltInBackStackEntryMappers.create(logger = { logger }) { kotlinxMapper } + + verifyNoInteractions(logger) + } + + @Test + fun `create() - maps entries to null when creating the kotlinx mapper throws NoClassDefFoundError`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw NoClassDefFoundError("kotlinx/serialization/KSerializer") + } + + assertThat(mapper.map(Home)).isNull() + } + + @Test + fun `create() - maps entries to null when creating the kotlinx mapper throws 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 mapper creation 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 is not a linkage error from creating the kotlinx mapper`() { + val exception = IllegalStateException("mapper bug") + + val thrown = + assertFailsWith { + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw exception + } + } + + assertThat(thrown).isSameInstanceAs(exception) + } + + /** + * Races two threads on the first access of a fresh copy of the companion mapper [getterName], in + * the shape of a deadlock: this thread holds a lock of the app's while it accesses the mapper, + * and the other thread's creation of the mapper, which is already logging that the kotlinx mapper + * can't be loaded, waits for that lock in the app's logger. + * + * Every wait is bounded, so a deadlock makes the logger give up on the lock rather than hang. The + * assertions inside are precondition guards that the race ran as intended, not the contracts + * under test. + */ + private fun raceOnFirstAccess(getterName: String): FirstAccessRace { + 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 classLoader = KotlinxMapperHidingClassLoader() + appLock.lock() + var otherThreadMapper: Any? = null + val otherThread = + thread(name = "other-mapper-user") { + otherThreadMapper = classLoader.companionMapper(getterName).delegate + } + assertThat(logger.otherThreadLogging.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue() + + val thisThreadMapper = + try { + classLoader.companionMapper(getterName).delegate + } finally { + appLock.unlock() + } + otherThread.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS * 2)) + assertThat(otherThread.isAlive).isFalse() + + return FirstAccessRace( + otherThreadLoggerGotAppLock = logger.otherThreadGotLock, + otherThreadMapper = otherThreadMapper, + thisThreadMapper = thisThreadMapper, + laterMapper = classLoader.companionMapper(getterName).delegate, + ) + } finally { + Sentry.close() + } + } + + private class FirstAccessRace( + val otherThreadLoggerGotAppLock: Boolean, + val otherThreadMapper: Any?, + val thisThreadMapper: Any, + val laterMapper: Any, + ) + + /** + * 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. + */ + private class LockingLogger(private val appLock: ReentrantLock, private val thisThread: Thread) : + ILogger { + val otherThreadLogging = CountDownLatch(1) + + @Volatile var otherThreadGotLock = false + + override fun log(level: SentryLevel, message: String, vararg args: Any?) = Unit + + 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." + + /** Set by the module's Gradle build from `kotlinxSerializationFloor`. */ + const val KOTLINX_SERIALIZATION_FLOOR_PROPERTY = "nav3.kotlinxSerializationFloor" + } +} 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..b42874d8393 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt @@ -0,0 +1,43 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel +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 + +class UnavailableBackStackEntryMapperTest { + + private data object Home + + private data class Detail(val id: String) + + private val logger = mock() + + @Test + fun `maps every back stack entry to null`() { + val mapper = UnavailableBackStackEntryMapper(logger = { logger }) + + val mapped = listOf(Home, Detail("1"), "home").map(mapper::map) + + assertThat(mapped).containsExactly(null, null, null) + } + + @Test + fun `logs a warning once per back stack entry type`() { + val mapper = UnavailableBackStackEntryMapper(logger = { logger }) + + 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)) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt new file mode 100644 index 00000000000..63edcc3a2e4 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt @@ -0,0 +1,796 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import java.lang.reflect.InvocationTargetException +import kotlin.test.assertFailsWith +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.MetaSerializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argThat +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify + +@OptIn(ExperimentalSerializationApi::class) +@MetaSerializable +@Target(AnnotationTarget.CLASS) +private annotation class MetaSerializableRoute + +@MetaSerializableRoute private data class MetaSerializableEntry(val id: String) + +class KotlinxBackStackEntryMapperNamingTest { + + @Serializable data class WithoutSerialName(val id: String) + + @Serializable + enum class Tab { + FEED, + @SerialName("tab.search") SEARCH, + } + + @Serializable(with = CustomNameSerializer::class) + @SerialName("IgnoredSerialName") + internal class CustomSerialized + + internal object CustomNameSerializer : NamingOnlySerializer() { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + } + + @Serializable + 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) + + // 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 it gets its own pair. + + @Serializable(with = UninitializableSerializerA::class) internal class UninitializableSerializedA + + internal object UninitializableSerializerA : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer A init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.A", PrimitiveKind.STRING) + } + + @Serializable(with = UninitializableSerializerB::class) internal class UninitializableSerializedB + + internal object UninitializableSerializerB : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer B init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.B", PrimitiveKind.STRING) + } + + @Serializable(with = UninitializableSerializerC::class) private object PrivateUninitializable + + private object UninitializableSerializerC : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer C init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.C", PrimitiveKind.STRING) + } + + @Serializable(with = DescriptorThrowsIllegalStateSerializer::class) + internal class DescriptorThrowsIllegalState + + internal object DescriptorThrowsIllegalStateSerializer : + NamingOnlySerializer() { + val error = IllegalStateException("descriptor failed") + + override val descriptor: SerialDescriptor + get() = throw error + } + + @Serializable(with = DescriptorThrowsAbstractMethodErrorSerializer::class) + internal class DescriptorThrowsAbstractMethodError + + internal object DescriptorThrowsAbstractMethodErrorSerializer : + NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = throw AbstractMethodError("descriptor not implemented") + } + + @Serializable(with = DescriptorThrowsNoClassDefFoundErrorSerializer::class) + internal class DescriptorThrowsNoClassDefFoundError + + internal object DescriptorThrowsNoClassDefFoundErrorSerializer : + NamingOnlySerializer() { + val error = NoClassDefFoundError("com/example/MissingDescriptorClass") + + override val descriptor: SerialDescriptor + get() = throw error + } + + // Naming + + @Test + fun `names entries after their SerialName`() { + val fixture = KotlinxMapperFixture.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 entries without @SerialName after their fully qualified class name`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(WithoutSerialName("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.WithoutSerialName")) + } + + @Test + fun `names constants of @Serializable enums after their enum`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(Tab.FEED) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.Tab")) + } + + @Test + fun `names enum constants that have a @SerialName after their enum`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(Tab.SEARCH) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.Tab")) + } + + @Test + fun `names constants of @Serializable enums that have bodies after their enum`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { if (it == TabWithBodies::class.java) TabWithBodies.serializer() else null } + val mapper = fixture.mapper + + val mapped = mapper.map(TabWithBodies.SEARCH) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.TabWithBodies")) + } + + @Test + fun `names entries of a class with a custom serializer after its descriptor, ignoring the class's @SerialName`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(CustomSerialized()) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("custom.Name")) + } + + @Test + fun `returns null for entries that aren't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + val mapped = mapper.map(NotSerializable("1")) + + assertThat(mapped).isNull() + } + + @Test + fun `returns null for entries that aren't @Serializable even if the lookup has a serializer`() { + // kotlinx serialization has serializers for built-in types and enums that aren't @Serializable. + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { 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 marked with a @MetaSerializable annotation`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(MetaSerializableEntry("1")) + + assertThat(mapped).isNull() + } + + // Name lookup caching and logging + + @Test + fun `looks up each @Serializable type once, including failed lookups`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Home) + mapper.map(Detail("$it")) + mapper.map(Generic("$it")) + } + + assertThat(fixture.lookedUpTypes) + .containsExactly(Home::class.java, Detail::class.java, Generic::class.java) + } + + @Test + fun `never looks up types that aren't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(NotSerializable("$it")) + mapper.map("home") + mapper.map(42) + mapper.map(UnannotatedTab.FEED) + } + + assertThat(fixture.lookedUpTypes).isEmpty() + } + + @Test + fun `looks up an enum that has bodies once for all its constants`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + mapper.map(TabWithBodies.FEED) + mapper.map(TabWithBodies.SEARCH) + + assertThat(fixture.lookedUpTypes).containsExactly(TabWithBodies::class.java) + } + + @Test + fun `logs a warning once per type that isn't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(NotSerializable("$it")) + mapper.map("home") + mapper.map(UnannotatedTab.FEED) + mapper.map(Home) + } + + verifyNotSerializableLoggedOnce(fixture, NotSerializable::class.java) + verifyNotSerializableLoggedOnce(fixture, String::class.java) + verifyNotSerializableLoggedOnce(fixture, UnannotatedTab::class.java) + verify(fixture.logger, never()).log(any(), any(), eq(Home::class.java.name)) + } + + @Test + fun `logs a warning once per @Serializable type whose serializer can't be found`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { if (it == Detail::class.java) null else fixture.serializers[it] } + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail("$it")) + mapper.map(Home) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + isNull(), + any(), + eq(Detail::class.java.name), + eq(SERIALIZER_NOT_FOUND), + ) + verify(fixture.logger, never()) + .log(any(), anyOrNull(), any(), eq(Home::class.java.name), any()) + } + + @Test + fun `advises making the type @Serializable when a type that isn't @Serializable can't be named`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + mapper.map(NotSerializable("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log(eq(SentryLevel.WARNING), message.capture(), eq(NotSerializable::class.java.name)) + assertThat(message.firstValue).contains("Add @Serializable") + } + + @Test + fun `advises seeing the docs when a @Serializable type's serializer can't be found`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { null } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + isNull(), + message.capture(), + eq(Detail::class.java.name), + eq(SERIALIZER_NOT_FOUND), + ) + assertThat(message.firstValue).contains("See BackStackEntryMapper.SerialName's documentation") + assertThat(message.firstValue).doesNotContain("Add @Serializable") + } + + @Test + fun `advises seeing the attached error without compatibility advice when a type's name lookup throws an exception`() { + val error = IllegalStateException("lookup failed") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + eq(error), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_ERROR), + ) + assertThat(message.firstValue).contains("See the attached error") + assertThat(message.firstValue).doesNotContain(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `advises checking kotlinx compatibility when a type's name lookup throws a LinkageError`() { + val error = NoSuchMethodError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + eq(error), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_ERROR), + ) + assertThat(message.firstValue).contains("See the attached error") + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + // Serializer lookup errors that only affect one type + + @Test + fun `returns null and logs the error once for a type whose name lookup throws a LinkageError`() { + val error = NoSuchMethodError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `doesn't look up a type again after its name lookup throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw NoSuchMethodError() } + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java) + } + + @Test + fun `keeps naming other types after a type's name lookup throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == Detail::class.java) throw NoSuchMethodError() else fixture.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 `returns null and logs the error once for a type whose name lookup throws ReflectiveOperationException`() { + val error = NoSuchMethodException("serializer") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `returns null and logs the error once for a type whose name lookup throws an unchecked exception`() { + val error = TypeNotPresentException("com.example.RemovedSerializer", null) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `doesn't look up a type again after its name lookup throws an unchecked exception`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { error("lookup failed") } + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java) + } + + @Test + fun `keeps naming other types after a type's name lookup throws an unchecked exception`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == Detail::class.java) error("lookup failed") else fixture.serializers[it] + } + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home)) + + assertThat(mapped).containsExactly(null, SentryBackStackEntry("Home")).inOrder() + } + + @Test + fun `restores the interrupt status when a type's name lookup throws InterruptedException`() { + val error = InterruptedException() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + try { + assertThat(mapper.map(Detail("1"))).isNull() + assertThat(Thread.currentThread().isInterrupted).isTrue() + verifyLookUpErrorLoggedOnce(fixture, error) + } finally { + Thread.interrupted() + } + } + + @Test + fun `propagates fatal errors a name lookup throws`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer lookup errors wrapped in an InvocationTargetException + + @Test + fun `returns null and logs the cause once for a type whose name lookup throws a wrapped exception`() { + val cause = IllegalStateException("serializer() failed") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(cause) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, cause) + } + + @Test + fun `returns null and logs the cause once when a name lookup throws a wrapped ExceptionInInitializerError`() { + val cause = ExceptionInInitializerError(IllegalStateException("serializer init failed")) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(cause) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, cause) + } + + @Test + fun `keeps naming other types after a type's name lookup throws a wrapped LinkageError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == Detail::class.java) throw InvocationTargetException(NoSuchMethodError()) + else fixture.serializers[it] + } + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home)) + + assertThat(mapped).containsExactly(null, SentryBackStackEntry("Home")).inOrder() + } + + @Test + fun `returns null and logs the InvocationTargetException once when a name lookup throws one without a cause`() { + val error = InvocationTargetException(null) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `restores the interrupt status when a type's name lookup throws a wrapped InterruptedException`() { + val error = InterruptedException() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(error) } + val mapper = fixture.mapper + + try { + assertThat(mapper.map(Detail("1"))).isNull() + assertThat(Thread.currentThread().isInterrupted).isTrue() + verifyLookUpErrorLoggedOnce(fixture, error) + } finally { + Thread.interrupted() + } + } + + @Test + fun `propagates fatal errors a name lookup throws wrapped in an InvocationTargetException`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(error) } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer descriptors that throw + + @Test + fun `returns null without looking up again for a type whose serializer's descriptor throws`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { DescriptorThrowsIllegalStateSerializer } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(DescriptorThrowsIllegalState()) } + + assertThat(mapped).containsExactly(null, null, null) + assertThat(fixture.lookedUpTypes).containsExactly(DescriptorThrowsIllegalState::class.java) + } + + @Test + fun `logs the error once for a type whose serializer's descriptor throws`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { DescriptorThrowsIllegalStateSerializer } + val mapper = fixture.mapper + + repeat(3) { mapper.map(DescriptorThrowsIllegalState()) } + + verifyLookUpErrorLoggedOnce( + fixture, + DescriptorThrowsIllegalStateSerializer.error, + DescriptorThrowsIllegalState::class.java, + ) + } + + @Test + fun `keeps naming other types after a type's serializer's descriptor throws AbstractMethodError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == DescriptorThrowsAbstractMethodError::class.java) { + DescriptorThrowsAbstractMethodErrorSerializer + } else { + fixture.serializers[it] + } + } + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(DescriptorThrowsAbstractMethodError()), mapper.map(Home)) + + assertThat(mapped).containsExactly(null, SentryBackStackEntry("Home")).inOrder() + } + + @Test + fun `returns null and logs the error once for a type whose serializer's descriptor throws NoClassDefFoundError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { DescriptorThrowsNoClassDefFoundErrorSerializer } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(DescriptorThrowsNoClassDefFoundError()) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce( + fixture, + DescriptorThrowsNoClassDefFoundErrorSerializer.error, + DescriptorThrowsNoClassDefFoundError::class.java, + ) + } + + @Test + fun `propagates fatal errors thrown by a serializer's descriptor`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + object : NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = throw error + } + } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer descriptors whose shape throws + + @Test + fun `names an entry after its SerialName without reading its descriptor's shape`() { + val serializer = ShapeThrowingDetailSerializer() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { serializer } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(serializer.shapeReads).isEqualTo(0) + } + + // Integration: serializer initializers that throw through real reflection + // + // Unlike the tests above, these use the mapper's default serializer lookup and its real + // reflection, to check that the mapper handles the errors it actually throws. + + @Test + fun `returns null without looking up again for a type whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create() + // Wraps the default lookup, rather than using it directly, so that lookedUpTypes records each + // lookup. + fixture.lookUp = { reflectiveSerializerOrNull(it) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(UninitializableSerializedA()) } + + assertThat(mapped).containsExactly(null, null, null) + assertThat(fixture.lookedUpTypes).containsExactly(UninitializableSerializedA::class.java) + } + + @Test + fun `logs the initializer error once for a type whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + repeat(3) { mapper.map(UninitializableSerializedB()) } + + val logged = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + logged.capture(), + any(), + eq(UninitializableSerializedB::class.java.name), + eq(LOOK_UP_ERROR), + ) + assertThat(logged.firstValue).isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(logged.firstValue) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("serializer B init failed") + } + + @Test + fun `logs the initializer error once for a private object whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(PrivateUninitializable) } + + assertThat(mapped).containsExactly(null, null, null) + val logged = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + logged.capture(), + any(), + eq(PrivateUninitializable::class.java.name), + eq(LOOK_UP_ERROR), + ) + assertThat(logged.firstValue).isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(logged.firstValue) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("serializer C init failed") + } + + private fun verifyLookUpErrorLoggedOnce( + fixture: KotlinxMapperFixture, + error: Throwable, + type: Class<*> = Detail::class.java, + ) { + verify(fixture.logger, times(1)) + .log(eq(SentryLevel.WARNING), eq(error), any(), eq(type.name), eq(LOOK_UP_ERROR)) + } + + private fun verifyNotSerializableLoggedOnce(fixture: KotlinxMapperFixture, type: Class<*>) { + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + argThat { contains(NOT_SERIALIZABLE) }, + eq(type.name), + ) + } + + private companion object { + val TEST_CLASS: String = KotlinxBackStackEntryMapperNamingTest::class.java.name + + const val NOT_SERIALIZABLE = "because the type is not @Serializable" + + const val SERIALIZER_NOT_FOUND = + "no serializer was found (the type may be generic or require R8 keep rules)" + + const val LOOK_UP_ERROR = "reading its annotations, serializer, or descriptor failed" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt new file mode 100644 index 00000000000..8703282b6fc --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt @@ -0,0 +1,115 @@ +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 kotlin.test.assertFailsWith +import org.junit.Test +import org.mockito.kotlin.argThat +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions + +/** How [KotlinxBackStackEntryMapper] acts on what its [KotlinxCompatibilityProbe] finds. */ +class KotlinxBackStackEntryMapperProbeTest { + + // Name lookup check + + @Test + fun `logs nothing when created for a kotlinx version the name lookup check finds compatible`() { + val fixture = KotlinxMapperFixture.create(probe = FakeCompatibilityProbe()) + + fixture.mapper + + verifyNoInteractions(fixture.logger) + } + + @Test + fun `throws the probe's LinkageError when created for a kotlinx version that can't support name lookups`() { + val error = NoSuchMethodError("serializerOrNull") + val probe = FakeCompatibilityProbe(nameLookupError = error) + + val thrown = + assertFailsWith { + KotlinxBackStackEntryMapper(logger = { mock() }, probe = probe) + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `doesn't log when created for a kotlinx version that can't support name lookups`() { + // BuiltInBackStackEntryMappers logs the error it catches, so the mapper doesn't log it too. + val logger = mock() + val probe = FakeCompatibilityProbe(nameLookupError = NoSuchMethodError()) + + assertFailsWith { + KotlinxBackStackEntryMapper(logger = { logger }, probe = probe) + } + + verifyNoInteractions(logger) + } + + @Test + fun `names entries when the name lookup check is inconclusive`() { + val probe = + FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(IllegalStateException())) + val fixture = KotlinxMapperFixture.create(probe = probe) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + } + + @Test + fun `logs at debug level with the error when the name lookup check throws inconclusively`() { + val error = IllegalStateException("check failed") + val probe = FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(error)) + + val fixture = KotlinxMapperFixture.create(probe = probe) + + val message = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.DEBUG), + eq(error), + message.capture(), + eq(NAME_LOOKUP_CAPABILITY), + eq(PROBE_THREW), + ) + assertThat(message.firstValue).startsWith(INCONCLUSIVE_PROBE) + } + + @Test + fun `logs at debug level when the name lookup check can't find a probe type's serializer`() { + val probe = FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(error = null)) + + val fixture = KotlinxMapperFixture.create(probe = probe) + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.DEBUG), + isNull(), + argThat { startsWith(INCONCLUSIVE_PROBE) }, + eq(NAME_LOOKUP_CAPABILITY), + eq(PROBE_SERIALIZER_NOT_FOUND), + ) + } + + private companion object { + const val NAME_LOOKUP_CAPABILITY = "name lookups" + + const val INCONCLUSIVE_PROBE = "Nav3 couldn't verify kotlinx.serialization support for %s" + + const val PROBE_THREW = "the compatibility probe threw (see the attached error)" + + const val PROBE_SERIALIZER_NOT_FOUND = "a probe serializer wasn't found" + } +} 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..b7fe764f3c1 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt @@ -0,0 +1,40 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.Companion.ProbeClass +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.Companion.ProbeObject +import org.junit.Test + +/** + * Runs the default probe against the kotlinx.serialization version on the test classpath, which CI + * also sets to the latest version with `-Pnav3TestKotlinxVersion`. + */ +class KotlinxCompatibilityProbeTest { + + // nameLookupLinkageError() + + @Test + fun `nameLookupLinkageError() - returns null for a compatible kotlinx serialization version conclusively`() { + val inconclusive = mutableListOf() + + val error = KotlinxCompatibilityProbe.nameLookupLinkageError { inconclusive += it } + + assertThat(error).isNull() + assertThat(inconclusive).isEmpty() + } + + // 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/KotlinxMapperFixture.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt new file mode 100644 index 00000000000..1d0f853c8d8 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt @@ -0,0 +1,169 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.ILogger +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.ArgumentBudget +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason +import io.sentry.compose.navigation3.internal.backstack.ArgumentSource +import io.sentry.compose.navigation3.internal.backstack.DropArguments +import io.sentry.compose.navigation3.internal.backstack.TreeArgumentWriter +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.mockito.AdditionalAnswers.delegatesTo +import org.mockito.Mockito +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +/** + * Delegates to [delegate], recording each serialized value and throwing [error], if set, for the + * values [failsFor] accepts. + */ +internal class RecordingSerializer(private val delegate: KSerializer) : + KSerializer by delegate { + val serialized = mutableListOf() + var error: Throwable? = null + var failsFor: (T) -> Boolean = { true } + + override fun serialize(encoder: Encoder, value: T) { + serialized += value + error?.takeIf { failsFor(value) }?.let { throw it } + delegate.serialize(encoder, value) + } +} + +/** + * Serializes [Detail] with a descriptor whose shape, its `elementsCount` and `kind`, throws + * [elementsCountError] and [kindError] when set. Counts every read of the shape in [shapeReads]. + * Encoding reads the descriptor's `kind`, so it throws [kindError] too. + */ +@OptIn(ExperimentalSerializationApi::class) +internal class ShapeThrowingDetailSerializer( + private val elementsCountError: Throwable? = null, + private val kindError: Throwable? = null, +) : KSerializer { + var shapeReads = 0 + + private val delegate = Detail.serializer().descriptor + + override val descriptor: SerialDescriptor = + Mockito.mock(SerialDescriptor::class.java, delegatesTo(delegate)).apply { + doAnswer { + shapeReads++ + elementsCountError?.let { error -> throw error } + delegate.elementsCount + } + .whenever(this) + .elementsCount + doAnswer { + shapeReads++ + kindError?.let { error -> throw error } + delegate.kind + } + .whenever(this) + .kind + } + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { encodeStringElement(descriptor, 0, value.id) } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() +} + +/** + * A [KotlinxCompatibilityProbe] that finds the app's kotlinx.serialization version compatible + * unless [nameLookupError] or [encodingError] is set, so that mapper tests don't depend on the real + * probe. Reports the name check inconclusive with [nameLookupInconclusive], if set, and the + * encoding check inconclusive with [encodingInconclusiveError], if set. Counts the checks of the + * properties encoder in [encodingChecks]. + */ +internal class FakeCompatibilityProbe( + private val nameLookupError: LinkageError? = null, + private val nameLookupInconclusive: Inconclusive? = null, +) : KotlinxCompatibilityProbe { + + override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? { + nameLookupError?.let { + return it + } + nameLookupInconclusive?.let { onInconclusive(it.error) } + return null + } + + /** Why the name check is inconclusive: [error], or `null` if a probe serializer wasn't found. */ + class Inconclusive(val error: Throwable?) +} + +/** + * A [KotlinxBackStackEntryMapper] whose serializer lookup returns [serializers] by default. The + * mapper only looks up `@Serializable` types, so [lookUp] never sees any others. Its compatibility + * [probe] finds the app's kotlinx.serialization version compatible by default. + * + * With `useDefaultLookUp = true`, the mapper uses its real serializer lookup, so [lookUp] and + * [lookedUpTypes] are unused. + */ +internal class KotlinxMapperFixture +private constructor( + useDefaultLookUp: Boolean, + val probe: KotlinxCompatibilityProbe, +) { + val logger = mock() + + val detailSerializer = RecordingSerializer(Detail.serializer()) + val searchSerializer = RecordingSerializer(Search.serializer()) + val serializers: Map, KSerializer<*>> = + mapOf( + Home::class.java to Home.serializer(), + Detail::class.java to detailSerializer, + Search::class.java to searchSerializer, + WithContextual::class.java to WithContextual.serializer(), + ) + + val lookedUpTypes = mutableListOf>() + var lookUp: (Class<*>) -> KSerializer<*>? = { serializers[it] } + + val mapper = + if (useDefaultLookUp) { + KotlinxBackStackEntryMapper(logger = { logger }, probe = probe) + } else { + KotlinxBackStackEntryMapper( + lookUpSerializer = { + lookedUpTypes += it + lookUp(it) + }, + logger = { logger }, + probe = probe, + ) + } + + companion object { + fun create( + useDefaultLookUp: Boolean = false, + probe: KotlinxCompatibilityProbe = FakeCompatibilityProbe(), + ) = KotlinxMapperFixture(useDefaultLookUp, probe) + } +} + +/** The arguments read from an entry whose arguments were dropped for [reason]. */ +internal fun droppedBy(reason: ArgumentDropReason): Map = + mapOf(ArgumentDropReason.ARGUMENT_DROP_REASON_KEY to reason.serializedValue) + +/** Maps [entry] and reads its arguments, which encodes its properties. */ +internal fun KotlinxBackStackEntryMapper.mapAndReadArguments(entry: Any): SentryBackStackEntry? = + map(entry)?.also { it.arguments?.size } + +/** + * Maps [entry] and writes its arguments to a sink with a budget of its own, as the argument + * sanitizer does, which encodes its properties. Ignores the [DropArguments] a failure throws. + */ +internal fun KotlinxBackStackEntryMapper.mapAndWriteArguments(entry: Any) { + val arguments = map(entry)?.arguments as ArgumentSource + try { + arguments.writeTo(TreeArgumentWriter(ArgumentBudget())) + } catch (_: DropArguments) {} +} 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..0c0f61ba8c3 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt @@ -0,0 +1,289 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import java.lang.reflect.InvocationTargetException +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.Assert.assertThrows +import org.junit.Test + +class KotlinxSerializerLookupTest { + + @Serializable @SerialName("Detail") data class Detail(val id: String) + + @Serializable @SerialName("Home") data object Home + + @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() + } + } + + 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 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 = + assertThrows(InvocationTargetException::class.java) { + 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 = + assertThrows(InvocationTargetException::class.java) { + 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 = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(PrivateUninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .isEqualTo("private serializer init failed") + } + + @Test + fun `throws a private object's fatal serializer initializer error wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(PrivateFatal::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(OutOfMemoryError::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed fatally") + } + + // Private object lookups that fail + + @Test + fun `throws the reflection error when a type with an inaccessible INSTANCE field has no serializer method`() { + val thrown = + assertThrows(NoSuchMethodException::class.java) { + reflectiveSerializerOrNull(InaccessibleInstanceWithoutSerializer::class.java) + } + + assertThat(thrown).hasMessageThat().contains("serializer") + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt new file mode 100644 index 00000000000..c912d881bb2 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -0,0 +1,87 @@ +@file:Suppress("MatchingDeclarationName") + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +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) + +internal class Unregistered(val id: String) + +@Serializable +@SerialName("WithContextual") +internal data class WithContextual(val id: String, @Contextual val other: Unregistered) + +/** 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() +} + +@Serializable internal data class Box(val value: T) + +/** Wraps [value] in [depth] nested [Box]es, so that [value] sits at [depth]. */ +internal fun boxed( + depth: Int, + value: T, + serializer: KSerializer, +): Pair, Any> { + var boxedSerializer: KSerializer<*> = serializer + var boxedValue: Any? = value + repeat(depth) { + @Suppress("UNCHECKED_CAST") + boxedSerializer = Box.serializer(boxedSerializer as KSerializer) + boxedValue = Box(boxedValue) + } + @Suppress("UNCHECKED_CAST") + return boxedSerializer as KSerializer to boxedValue!! +} + +/** The arguments the encoder produces for [boxed] when within its limits. */ +internal fun boxedArguments(depth: Int, value: Any?): Map { + var arguments: Any? = value + repeat(depth) { arguments = mapOf("value" to arguments) } + @Suppress("UNCHECKED_CAST") + return arguments as Map +} + +internal class Link(val id: String) { + var next: Link? = null +} + +/** + * Encodes a link as the id of the last link in its chain, encoding each next link in place of its + * own, so the recursion never begins a structure. + */ +internal object LinkSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.Link", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + val next = value.next + if (next != null) encoder.encodeSerializableValue(this, next) + else encoder.encodeString(value.id) + } + + override fun deserialize(decoder: Decoder): Link = Link(decoder.decodeString()) +} + +/** Chains [length] [Link]s, the last of which has the id `leaf`. */ +internal fun linked(length: Int): Link { + var link = Link("leaf") + repeat(length - 1) { index -> link = Link("link-$index").apply { next = link } } + return link +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 18340a6c241..897227ad444 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -38,6 +38,11 @@ dependencyResolutionManagement { mavenCentral() mavenLocal() } + versionCatalogs { + create("nav3Libs") { + from(files("gradle/nav3.versions.toml")) + } + } } rootProject.name = "sentry-root"