diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt index c91b3b6f54..5506119474 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavOptions.kt @@ -7,6 +7,10 @@ import org.jetbrains.annotations.ApiStatus // sanitization when navigation changes are observed. internal const val DEFAULT_MAX_CAPTURED_BACK_STACK_ENTRIES = 5 +// Bounds the work done per back stack change to help ensure performance while still providing (more +// than) enough entries for host app's needs. +internal const val MAX_CAPTURED_BACK_STACK_ENTRIES = 25 + /** * Configuration info for a [SentryNavEffect]. * @@ -64,7 +68,7 @@ private constructor( /** * Maximum number of entries Sentry should record per captured back stack (starting with the - * most recent). Set to `0` to capture no back stack entries. + * most recent). Capped at 25. Set it to 0 to capture no back stack entries. * * Note: Sentry resolves and sanitizes up to [maxCapturedBackStackEntries] names + argument maps * whenever your back stack changes. Keep the back stack mapper lightweight, and reduce the max @@ -77,7 +81,8 @@ private constructor( enableNavigationBreadcrumbs = enableNavigationBreadcrumbs, enableNavigationTransactions = enableNavigationTransactions, captureBackStack = captureBackStack, - maxCapturedBackStackEntries = maxCapturedBackStackEntries, + maxCapturedBackStackEntries = + maxCapturedBackStackEntries.coerceAtMost(MAX_CAPTURED_BACK_STACK_ENTRIES), ) } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt new file mode 100644 index 0000000000..3e9df09495 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt @@ -0,0 +1,59 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentWriteResult +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY +import kotlinx.serialization.KSerializer + +/** Builds arguments from back stack entries using kotlinx.serialization. */ +internal object KotlinxArguments { + + /** + * The arguments of an entry whose properties can't be encoded, e.g., because the app's + * kotlinx.serialization version doesn't support the properties encoder. + */ + val UNENCODABLE: Map = droppedFor(ArgumentDropReason.ENCODING_FAILED) + + /** + * Returns [backStackEntry]'s properties, encoded with [serializer] and an [ArgumentBudget] of + * their own. + * + * If the entry breaks an argument limit or can't be encoded, reports why to [onFailure] and + * returns only the reason under [ARGUMENT_DROP_REASON_KEY], e.g., `{"dropped_by_sentry": + * "encoding_failed"}`. A host app mapper that copies or filters the arguments then passes the + * reason on as an ordinary argument. + */ + fun encode( + backStackEntry: Any, + serializer: KSerializer, + onFailure: (Throwable) -> Unit, + ): Map { + val result = + try { + TreeArgumentSink(ArgumentBudget()).write { + KotlinxPropertiesEncoder.encode(serializer, backStackEntry, it) + } + } catch (e: LinkageError) { + // write() rethrows LinkageErrors as fatal. This one may be specific to the entry's + // serializers, which a compatibility check can't exercise, so we drop only its properties. + ArgumentWriteResult.Failed(e) + } + + return when (result) { + is ArgumentWriteResult.Written -> result.arguments + is ArgumentWriteResult.Dropped -> { + onFailure(result.drop) + droppedFor(result.drop.reason) + } + is ArgumentWriteResult.Failed -> { + onFailure(result.cause) + UNENCODABLE + } + } + } + + private fun droppedFor(reason: ArgumentDropReason): Map = + mapOf(ARGUMENT_DROP_REASON_KEY to reason.serializedValue) +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt index 63635f5f20..b98fe151fd 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/common/ArgumentProtocol.kt @@ -142,7 +142,7 @@ internal interface ArgumentSink { * `SerialNameAndProperties` filters sensitive values to comply with Sentry's * [sensitive denylist policy](https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist). */ -internal interface ArgumentSource { +internal fun interface ArgumentSource { fun writeTo(sink: ArgumentSink) } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt index e9dbf05389..66e67d0f05 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContract.kt @@ -96,7 +96,7 @@ internal enum class UnknownEntryReason(val serializedValue: String) { } /** - * Why host-provided arguments were unavailable in emitted nav state. + * Why a back stack entry's arguments were unavailable in emitted nav state. * * Recorded under [ARGUMENT_DROP_REASON_KEY]. */ @@ -107,6 +107,7 @@ internal enum class ArgumentDropReason( CHARACTER_LIMIT("max_character_limit_exceeded", exhaustsUpdateBudget = true), DUPLICATE_KEY("duplicate_key"), + ENCODING_FAILED("encoding_failed"), INVALID_STRUCTURE("invalid_structure"), MAX_COUNT("max_argument_count_exceeded", exhaustsUpdateBudget = true), SANITIZATION_FAILED("sanitization_failed"); diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt index 15e30b16f4..e956f090b6 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavOptionsTest.kt @@ -28,6 +28,20 @@ class SentryNavOptionsTest { assertThat(options.maxCapturedBackStackEntries).isEqualTo(0) } + @Test + fun `accepts 25 max captured backstack entries`() { + val options = SentryNavOptions { maxCapturedBackStackEntries = 25 } + + assertThat(options.maxCapturedBackStackEntries).isEqualTo(25) + } + + @Test + fun `captures at most 25 back stack entries when more are requested`() { + val options = SentryNavOptions { maxCapturedBackStackEntries = 26 } + + assertThat(options.maxCapturedBackStackEntries).isEqualTo(25) + } + @Test fun `rejects negative max captured backstack entries`() { val exception = diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt new file mode 100644 index 0000000000..59289ca5c2 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt @@ -0,0 +1,200 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlin.test.assertFailsWith +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.descriptors.element +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.junit.Test + +class KotlinxArgumentsTest { + + @Serializable data class Values(val values: List) + + /** + * Delegates to [delegate], but replaces a [DropArgumentsException] it throws with an exception of + * its own, as a serializer that catches and rethrows everything might. + */ + private class ReplacingSerializer( + private val delegate: KSerializer, + private val replace: () -> Throwable, + ) : KSerializer by delegate { + override fun serialize(encoder: Encoder, value: T) { + try { + delegate.serialize(encoder, value) + } catch (_: DropArgumentsException) { + throw replace() + } + } + } + + /** Writes a [Detail]'s id into a list it begins but never ends. */ + private object UnclosedListSerializer : KSerializer { + override val descriptor: SerialDescriptor = ListSerializer(String.serializer()).descriptor + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.beginStructure(descriptor).encodeStringElement(descriptor, 0, value.id) + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + /** Writes nothing, leaving the key written for its value without one. */ + private object WritesNothingSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.WritesNothing", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: String) = Unit + + override fun deserialize(decoder: Decoder): String = throw UnsupportedOperationException() + } + + /** Writes a [Detail] as a class whose only property has no value. */ + private object ValuelessKeySerializer : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("test.ValuelessKey") { element("first") } + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { + encodeSerializableElement(descriptor, 0, WritesNothingSerializer, value.id) + } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + private val failures = mutableListOf() + + private val detailSerializer = RecordingSerializer(Detail.serializer()) + + /** A value over the argument character limit. */ + private val overLimitId = "x".repeat(MAX_ARGUMENT_CHARACTERS + 1) + + private val encodingFailed = droppedBy(ArgumentDropReason.ENCODING_FAILED) + + // Encoding + + @Test + fun `encode() - returns the entry's encoded properties`() { + val arguments = encode(detailSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `encode() - encodes each entry with a budget of its own`() { + // Each entry has 151 values, so two entries wouldn't fit in one budget. + val first = encode(Values.serializer(), Values(List(150) { it })) + val second = encode(Values.serializer(), Values(List(150) { it })) + + assertThat(first).isEqualTo(mapOf("values" to List(150) { it })) + assertThat(second).isEqualTo(mapOf("values" to List(150) { it })) + } + + @Test + fun `encode() - runs the entry's serializer once, and no more when the arguments are read or compared`() { + val arguments = encode(detailSerializer, Detail("1")) + + arguments.hashCode() + arguments == mapOf("id" to "1") + arguments.entries.toList() + + assertThat(detailSerializer.serialized).containsExactly(Detail("1")) + } + + // Failures + + @Test + fun `encode() - returns only the broken limit and reports it when the entry breaks an argument limit`() { + val arguments = encode(detailSerializer, Detail(overLimitId)) + + assertThat(arguments).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + assertThat((failures.single() as DropArgumentsException).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `encode() - returns only the broken limit and reports it when a serializer replaced it with its own exception`() { + val serializer = ReplacingSerializer(Detail.serializer()) { SerializationException("replaced") } + + val arguments = encode(serializer, Detail(overLimitId)) + + assertThat(arguments).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + assertThat((failures.single() as DropArgumentsException).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `encode() - returns only the encoding failure and reports a serializer's exception`() { + val error = IllegalStateException("boom") + detailSerializer.error = error + + val arguments = encode(detailSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(encodingFailed) + assertThat(failures).containsExactly(error) + } + + @Test + fun `encode() - returns only the encoding failure and reports a serializer's LinkageError`() { + val error = NoClassDefFoundError("missing") + detailSerializer.error = error + + val arguments = encode(detailSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(encodingFailed) + assertThat(failures).containsExactly(error) + } + + @Test + fun `encode() - propagates fatal errors without reporting them`() { + val error = OutOfMemoryError() + detailSerializer.error = error + + val thrown = assertFailsWith { encode(detailSerializer, Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(failures).isEmpty() + } + + @Test + fun `encode() - returns only the encoding failure when a serializer leaves a list open`() { + val arguments = encode(UnclosedListSerializer, Detail("1")) + + assertThat(arguments).isEqualTo(encodingFailed) + assertThat(failures.single()).isInstanceOf(ArgumentProtocolException::class.java) + } + + @Test + fun `encode() - returns only the encoding failure when a serializer's last key has no value`() { + val arguments = encode(ValuelessKeySerializer, Detail("1")) + + assertThat(arguments).isEqualTo(encodingFailed) + assertThat(failures.single()).isInstanceOf(ArgumentProtocolException::class.java) + } + + // Unencodable entries + + @Test + fun `UNENCODABLE - is only the encoding failure`() { + assertThat(KotlinxArguments.UNENCODABLE).isEqualTo(encodingFailed) + } + + @Suppress("UNCHECKED_CAST") + private fun encode(serializer: KSerializer, entry: T): Map = + KotlinxArguments.encode(entry, serializer as KSerializer) { failures += it } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt index 342f57f53b..42c8bbb394 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -2,6 +2,7 @@ package io.sentry.compose.navigation3.internal.backstack.kotlinx +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason import kotlinx.serialization.Contextual import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName @@ -102,3 +103,7 @@ internal class RecordingSerializer(private val delegate: KSerializer) : delegate.serialize(encoder, value) } } + +/** 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) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt index 8fd55c57ca..acbf841bb6 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/contract/NavDataContractTest.kt @@ -91,6 +91,8 @@ class NavDataContractTest { "max_character_limit_exceeded", ArgumentDropReason.DUPLICATE_KEY, "duplicate_key", + ArgumentDropReason.ENCODING_FAILED, + "encoding_failed", ArgumentDropReason.INVALID_STRUCTURE, "invalid_structure", ArgumentDropReason.MAX_COUNT,