diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index 4bd7f27ab2..1ca3d68804 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt @@ -6,6 +6,7 @@ import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentSource import io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.common.HostArgumentSource import io.sentry.compose.navigation3.internal.common.TreeArgumentSink @@ -153,8 +154,10 @@ internal class BackStackConverter( * Sanitizes the arguments the [entryMapper] returns for back stack entries and returns them in a * [serializable form][SanitizedArguments.values]. * - * Each entry's arguments are written by a [HostArgumentSource] into a [TreeArgumentSink], which - * bounds depth and total value count, and rejects cyclic structures. + * Each entry's arguments are written into a [TreeArgumentSink], which bounds depth and total + * value count, and rejects cyclic structures. Arguments that are an [ArgumentSource] write + * themselves (e.g., those of `SerialNameAndProperties`); any other map is written by a + * [HostArgumentSource]. * * One instance is shared across every entry in a single [convert] call, so the value and * character budgets span the whole update. @@ -185,7 +188,9 @@ internal class BackStackConverter( return SanitizedArguments(emptyMap(), reason) } - val source = HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } + val source = + raw as? ArgumentSource + ?: HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } val sink = TreeArgumentSink(budget) // A constraint violation the sink recorded takes precedence over whatever the source threw, @@ -193,6 +198,8 @@ internal class BackStackConverter( // entries keep their arguments. return try { source.writeTo(sink) + // Record only the copy the sink built. A mapper's arguments may keep their back stack entry + // in memory (e.g., KotlinxArgumentSource, which encodes lazily). SanitizedArguments(sink.argumentsOrThrow()) } catch (drop: DropArgumentsException) { drop(sink.failure ?: drop) @@ -211,7 +218,7 @@ internal class BackStackConverter( if (drop.reason.exhaustsUpdateBudget) { dropReason = drop.reason } - logger.log(WARNING, drop.warning) + drop.warning?.let { logger.log(WARNING, it) } return SanitizedArguments(emptyMap(), drop.reason) } } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSource.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSource.kt new file mode 100644 index 0000000000..65515c1d2c --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSource.kt @@ -0,0 +1,174 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.ArgumentSource +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.HostArgumentSource +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 io.sentry.util.ExceptionUtils +import kotlinx.serialization.KSerializer + +/** + * The [ArgumentSource] for `BackStackEntryMapper.SerialNameAndProperties`. It's also the map of + * arguments it returns. + * + * Failures are reported to [onFailure]. The only exclusion is if an argument constraint is violated + * while writing to the `ArgumentSanitizer`'s sink; the sanitizer reports that instead, as those + * limits can depend on what fraction of the [ArgumentBudget] the update's other entries spent. + * + * **Lazy encoding** + * + * Encoding is lazy, so that arguments that are dropped or never read never run the entry's + * serializers. + * + * Once the arguments are read, [writeTo] writes the copy that read encoded, or drops the arguments + * for the reason its encoding failed, rather than encoding the entry again. Sentry then records + * what the host app read, even if its serializers would have encoded the entry differently on + * another call. + * + * To encode lazily, each instance holds references to [backStackEntry] and its [serializer] for as + * long as the instance is reachable. + */ +internal class KotlinxArgumentSource( + private val backStackEntry: Any, + private val serializer: KSerializer, + private val onFailure: (Throwable) -> Unit, +) : AbstractMap(), ArgumentSource { + + private val copy: Lazy = + // PUBLICATION so that no lock is held while encoding runs the host app's serializers, which + // could otherwise deadlock on a lock held by the app. Readers that race on the first read may + // each encode, but all of them see the copy published first. + lazy(LazyThreadSafetyMode.PUBLICATION) { encodeCopy() } + + override val entries: Set> + get() = copy.value.arguments.entries + + /** + * Writes the entry's arguments to [sink]: the cached copy if the arguments were read, or else + * encoding the entry's properties. + * + * Throws [DropArgumentsException] if the arguments can't be written, either with the reason for + * the constraint they violated, or with [ArgumentDropReason.ENCODING_FAILED] if encoding failed. + */ + override fun writeTo(sink: ArgumentSink) { + if (copy.isInitialized()) { + copy.value.writeTo(sink) + } else { + encode(sink) + } + } + + @Suppress("ThrowsCount") + private fun encode(sink: ArgumentSink) { + try { + KotlinxPropertiesEncoder.encode(serializer, backStackEntry, sink) + } catch (e: DropArgumentsException) { + // Prefer the sink's first failure because it determines whether older entries keep their + // arguments. + throw sink.failure ?: e + } catch (e: LinkageError) { + // Preserve the entry's name and drop its properties. A compatibility check can't exercise + // every encoder path, and this LinkageError may be specific to the entry's serializers, so + // we keep the failure local to this type. + sink.failure?.let { throw it } + onFailure(e) + throw DropArgumentsException(ArgumentDropReason.ENCODING_FAILED, warning = null) + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // App serializers may throw anything. Catch broadly to log once per type. + ExceptionUtils.rethrowIfFatal(t) + + // A serializer may replace a constraint violation with its own exception. Prefer the sink's + // recorded failure because it determines whether older entries keep their arguments. + sink.failure?.let { throw it } + onFailure(t) + throw DropArgumentsException(ArgumentDropReason.ENCODING_FAILED, warning = null) + } + } + + private fun encodeCopy(): EncodedCopy { + val sink = TreeArgumentSink(ArgumentBudget()) + + return try { + encode(sink) + EncodedCopy(sink.argumentsOrThrow(), failure = null) + } catch (e: DropArgumentsException) { + // encode already reported an encoding failure. + if (e.reason != ArgumentDropReason.ENCODING_FAILED) { + onFailure(e) + } + EncodedCopy(emptyMap(), failure = e) + } + } + + /** + * Arguments encoded from a single back stack entry's properties: [written] if encoding succeeded, + * or else the [failure] that stopped it. + */ + private class EncodedCopy( + private val written: Map, + private val failure: DropArgumentsException?, + ) : ArgumentSource { + + /** + * The arguments a read returns: [written], or, if encoding failed, only the drop reason under + * [ARGUMENT_DROP_REASON_KEY]. + * + * A host app mapper that copies or filters a dropped entry's arguments passes the reason on as + * an ordinary argument. Sentry then records it as it would for this mapper's own output, rather + * than recording no arguments and no reason. + */ + val arguments: Map = + if (failure == null) { + written + } else { + mapOf(ARGUMENT_DROP_REASON_KEY to failure.reason.serializedValue) + } + + /** + * Writes [written] to [sink], or, if encoding failed, throws [failure]'s reason without writing + * anything. + * + * A failed copy spends none of the sink's budget. Encoding the entry into the sink might have + * broken the sink's limits first, which would have dropped older entries' arguments too. A + * failed read keeps them instead, as replaying the copy can't account for everything encoding + * spent. + */ + override fun writeTo(sink: ArgumentSink) { + val failure = failure + if (failure == null) { + // The copy holds only plain maps, lists, and values the sink supports. + HostArgumentSource(written, onUnsupportedValue = {}).writeTo(sink) + return + } + // A broken limit has a warning and is recorded on the sink, as it would have been while + // encoding. An encoding failure was reported when it was read. + failure.warning?.let { sink.reject(failure.reason, it) } + throw DropArgumentsException(failure.reason, warning = null) + } + } +} + +/** + * The arguments of a back stack entry whose properties can't be encoded because the app's + * kotlinx.serialization version doesn't support the properties encoder. + * + * Handles encoding failures like [KotlinxArgumentSource]: map reads return `{"dropped_by_sentry": + * "encoding_failed"}`, and writes drop the entry's arguments with + * [ArgumentDropReason.ENCODING_FAILED]. + */ +internal object KotlinxUnencodableArguments : AbstractMap(), ArgumentSource { + + private val dropReason = + mapOf(ARGUMENT_DROP_REASON_KEY to ArgumentDropReason.ENCODING_FAILED.serializedValue) + + override val entries: Set> + get() = dropReason.entries + + override fun writeTo(sink: ArgumentSink) { + throw DropArgumentsException(ArgumentDropReason.ENCODING_FAILED, warning = null) + } +} 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 6cc5bba59a..d5f309aea5 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 @@ -200,11 +200,16 @@ internal class ArgumentBudget { internal class ArgumentProtocolException(message: String) : IllegalStateException(message) /** - * Control-flow signal to drop a back stack entry's arguments, logging [warning]. Overrides - * [fillInStackTrace] to skip stack-trace capture. + * Control-flow signal to drop a back stack entry's arguments. Overrides [fillInStackTrace] to skip + * stack-trace capture. + * + * [warning] is logged when the arguments are dropped, or not at all if `null` (e.g., because the + * [ArgumentSource] reported the failure itself). */ -internal class DropArgumentsException(val reason: ArgumentDropReason, val warning: String) : - RuntimeException() { +internal class DropArgumentsException( + val reason: ArgumentDropReason, + val warning: String?, +) : RuntimeException() { override fun fillInStackTrace(): Throwable = this 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/internal/backstack/ArgumentSanitizerTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt index 170796764f..965b9c329f 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt @@ -18,6 +18,7 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions class ArgumentSanitizerTest { @@ -237,4 +238,193 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) } + + // Arguments that write themselves + + @Test + fun `sanitizeEntry() - lets an ArgumentSource write its arguments instead of reading them as a map`() { + val arguments = SelfWritingArguments { sink -> + sink.key("written") + sink.scalar("by the source") + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized).isEqualTo(SanitizedArguments(mapOf("written" to "by the source"))) + } + + @Test + fun `sanitizeEntry() - records the drop reason of an ArgumentSource that drops its arguments`() { + val arguments = SelfWritingArguments { + throw DropArgumentsException(ArgumentDropReason.INVALID_STRUCTURE, "source warning") + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + } + + @Test + fun `sanitizeEntry() - logs the warning of an ArgumentSource that drops its arguments`() { + val arguments = SelfWritingArguments { + throw DropArgumentsException(ArgumentDropReason.INVALID_STRUCTURE, "source warning") + } + + sanitizer.sanitizeEntry(arguments) + + verify(logger).log(eq(WARNING), eq("source warning")) + } + + @Test + fun `sanitizeEntry() - logs nothing when an ArgumentSource drops its arguments without a warning`() { + val arguments = SelfWritingArguments { + throw DropArgumentsException(ArgumentDropReason.INVALID_STRUCTURE, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + verifyNoInteractions(logger) + } + + @Test + fun `sanitizeEntry() - records the broken limit when an ArgumentSource replaces it with another exception`() { + val arguments = overCharacterLimitReplacedWith { IllegalStateException("replaced") } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `sanitizeEntry() - logs the broken limit's warning when an ArgumentSource replaces it with another exception`() { + val arguments = overCharacterLimitReplacedWith { IllegalStateException("replaced") } + + sanitizer.sanitizeEntry(arguments) + + verify(logger).log(eq(WARNING), eq(DropArgumentsException.MAX_CHARACTER_WARNING)) + verify(logger, never()) + .log(eq(WARNING), eq(DropArgumentsException.STRUCTURE_WARNING), any()) + } + + @Test + fun `sanitizeEntry() - records the broken limit when an ArgumentSource replaces it with a drop of its own`() { + val arguments = overCharacterLimitReplacedWith { + DropArgumentsException(ArgumentDropReason.INVALID_STRUCTURE, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `entries share the value budget with arguments that write themselves`() { + // The source writes half of the value budget, so one value more than the other half doesn't + // fit. + val half = MAX_ARGUMENT_VALUES / 2 + val first = + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(half - 1) { sink.scalar(it) } + sink.end() + }, + ) + val second = sanitizer.sanitizeEntry(mapOf("values" to List(half) { it })) + + assertThat(first.dropReason).isNull() + assertThat(second).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `arguments that write themselves share the value budget with other entries`() { + // The first entry uses half of the value budget, so the source's one value more than the other + // half doesn't fit. + val half = MAX_ARGUMENT_VALUES / 2 + sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + + val sanitized = + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(half) { sink.scalar(it) } + sink.end() + }, + ) + + assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `entries after an ArgumentSource exhausts the value budget are dropped`() { + sanitizer.sanitizeEntry( + SelfWritingArguments { sink -> + sink.key("values") + sink.beginList() + repeat(MAX_ARGUMENT_VALUES) { sink.scalar(it) } + sink.end() + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `entries after an ArgumentSource replaces a broken character limit with another exception are dropped`() { + sanitizer.sanitizeEntry(overCharacterLimitReplacedWith { IllegalStateException("replaced") }) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `entries after an ArgumentSource replaces a broken character limit with its own exception are dropped`() { + sanitizer.sanitizeEntry( + overCharacterLimitReplacedWith { + DropArgumentsException(ArgumentDropReason.INVALID_STRUCTURE, warning = null) + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `an ArgumentSource that drops its arguments for invalid structure doesn't drop later entries`() { + sanitizer.sanitizeEntry( + SelfWritingArguments { + throw DropArgumentsException(ArgumentDropReason.INVALID_STRUCTURE, null) + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + + /** + * Arguments that write one character more than the character budget, then catch the sink's + * [DropArgumentsException] and throw [replacement] instead, without it as the cause. + */ + private fun overCharacterLimitReplacedWith(replacement: () -> Throwable) = + SelfWritingArguments { sink -> + try { + // The key and the value are one character more than the budget. + sink.key("v") + sink.scalar("x".repeat(MAX_ARGUMENT_CHARACTERS)) + } catch (@Suppress("SwallowedException") e: DropArgumentsException) { + throw replacement() + } + } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt index 6e2e5f7854..cc3aca060e 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverterTest.kt @@ -1,6 +1,7 @@ package io.sentry.compose.navigation3.internal.backstack import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat import io.sentry.ILogger @@ -553,6 +554,28 @@ class BackStackConverterTest { assertThat(observedReads).isEmpty() } + @Test + fun `convert() - hides state reads by arguments that write themselves from snapshot observation`() { + val state = mutableStateOf("value") + val arguments = SelfWritingArguments { sink -> + sink.key("state") + sink.scalar(state.value) + } + val converter = newConverter(entryMapper = { entry -> entryInfo(entry, arguments) }) + val observedReads = mutableListOf() + val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) + + val converted = + try { + snapshot.enter { converter.convert(HomeScreen()) } + } finally { + snapshot.dispose() + } + + assertThat(converted.arguments).isEqualTo(mapOf("state" to "value")) + assertThat(observedReads).isEmpty() + } + @Test fun `convert() - logs the unsupported value warning again in a later back stack update`() { class OpaqueValue { diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt new file mode 100644 index 0000000000..c1fdfd6ff5 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt @@ -0,0 +1,18 @@ +package io.sentry.compose.navigation3.internal.backstack + +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.ArgumentSource + +/** + * Arguments that write themselves with [write], like `SerialNameAndProperties`'s. Read as a map, + * they hold only [entries], which differ from what they write unless a test sets them. + */ +internal class SelfWritingArguments( + override val entries: Set> = mapOf("read" to "as a map").entries, + private val write: (ArgumentSink) -> Unit, +) : AbstractMap(), ArgumentSource { + + override fun writeTo(sink: ArgumentSink) { + write(sink) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSourceTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSourceTest.kt new file mode 100644 index 0000000000..0bb354ca7c --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSourceTest.kt @@ -0,0 +1,701 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.ArgumentBudget +import io.sentry.compose.navigation3.internal.common.ArgumentProtocolException +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.common.TreeArgumentSink +import io.sentry.compose.navigation3.internal.common.budgetWithCharactersRemaining +import io.sentry.compose.navigation3.internal.common.budgetWithValuesRemaining +import io.sentry.compose.navigation3.internal.contract.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.thread +import kotlin.test.assertFailsWith +import kotlinx.serialization.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 KotlinxArgumentSourceTest { + + @Serializable data class Values(val values: List) + + @Serializable data class MutableDetail(var id: String) + + /** + * 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() + } + } + } + + /** + * Encodes a [Detail] whose id is the number of this serializer's call, so that each encoding of + * an entry differs. Runs [beforeEncoding] with that number first. + */ + private class NumberingDetailSerializer(private val beforeEncoding: (call: Int) -> Unit) : + KSerializer { + private val calls = AtomicInteger() + + override val descriptor: SerialDescriptor = Detail.serializer().descriptor + + override fun serialize(encoder: Encoder, value: Detail) { + val call = calls.incrementAndGet() + beforeEncoding(call) + Detail.serializer().serialize(encoder, Detail("encoding-$call")) + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + /** Delegates to [delegate], then throws [error], as a serializer that fails late might. */ + private class ThrowsAfterEncodingSerializer(private val delegate: KSerializer) : + KSerializer by delegate { + val error = IllegalStateException("thrown after encoding") + + override fun serialize(encoder: Encoder, value: T) { + delegate.serialize(encoder, value) + throw error + } + } + + /** 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 first property has no value, followed by a second property + * if [writesSecond] is `true`. + */ + private class ValuelessKeySerializer(private val writesSecond: Boolean) : KSerializer { + override val descriptor: SerialDescriptor = + buildClassSerialDescriptor("test.ValuelessKey") { + element("first") + element("second") + } + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { + encodeSerializableElement(descriptor, 0, WritesNothingSerializer, value.id) + if (writesSecond) { + encodeStringElement(descriptor, 1, value.id) + } + } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() + } + + private val failures = mutableListOf() + + private val detailSerializer = RecordingSerializer(Detail.serializer()) + private val mutableDetailSerializer = RecordingSerializer(MutableDetail.serializer()) + + /** A value over the argument character limit. */ + private val overLimitId = "x".repeat(MAX_ARGUMENT_CHARACTERS + 1) + + private val encodingFailed = droppedBy(ArgumentDropReason.ENCODING_FAILED) + + // Reading as a map + + @Test + fun `reads as the entry's encoded properties`() { + val source = argumentSourceOf(detailSerializer, Detail("1")) + + assertThat(source.entries.associate { it.key to it.value }).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `doesn't encode the entry until its arguments are read`() { + argumentSourceOf(detailSerializer, Detail("1")) + + assertThat(detailSerializer.serialized).isEmpty() + } + + @Test + fun `encodes the entry when its arguments are first read through hashCode()`() { + val source = argumentSourceOf(detailSerializer, Detail("1")) + + val hashCode = source.hashCode() + + assertThat(hashCode).isEqualTo(mapOf("id" to "1").hashCode()) + assertThat(detailSerializer.serialized).containsExactly(Detail("1")) + } + + @Test + fun `encodes the entry once across repeated reads`() { + val source = argumentSourceOf(detailSerializer, Detail("1")) + + source.entries + source.size + source["id"] + source.containsKey("id") + source.equals(mapOf("id" to "1")) + + assertThat(detailSerializer.serialized).containsExactly(Detail("1")) + } + + @Test + fun `equals a plain map with the same entries`() { + val source = argumentSourceOf(detailSerializer, Detail("1")) + + assertThat(source).isEqualTo(mapOf("id" to "1")) + assertThat(mapOf("id" to "1")).isEqualTo(source) + assertThat(source.hashCode()).isEqualTo(mapOf("id" to "1").hashCode()) + } + + @Test + fun `doesn't equal a plain map with other entries`() { + val source = argumentSourceOf(detailSerializer, Detail("1")) + + assertThat(source).isNotEqualTo(mapOf("id" to "2")) + assertThat(mapOf("id" to "2")).isNotEqualTo(source) + } + + @Test + fun `reads each instance's arguments with a budget of its own`() { + // Each entry has 151 values, so two entries wouldn't fit in one budget. + val first = argumentSourceOf(Values.serializer(), Values(List(150) { it })) + val second = argumentSourceOf(Values.serializer(), Values(List(150) { it })) + + assertThat(first).isEqualTo(mapOf("values" to List(150) { it })) + assertThat(second).isEqualTo(mapOf("values" to List(150) { it })) + } + + // Reading from several threads + + @Test + fun `doesn't block a read on another thread's encoding that waits for a lock the reader holds`() { + // Models a deadlock: the reader holds a lock of the app's, and the serializer encoding on + // another thread needs it. + val appLock = ReentrantLock() + val encodingStarted = CountDownLatch(1) + var otherThreadGotLock = false + val serializer = NumberingDetailSerializer { call -> + if (call == 1) { + encodingStarted.countDown() + otherThreadGotLock = appLock.tryLock(TIMEOUT_SECONDS, TimeUnit.SECONDS) + if (otherThreadGotLock) appLock.unlock() + } + } + val source = argumentSourceOf(serializer, Detail("1")) + appLock.lock() + val otherRead = readOnAnotherThread(source) + assertThat(encodingStarted.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue() + + val read = + try { + source.toMap() + } finally { + appLock.unlock() + } + + assertThat(otherRead.await()).isEqualTo(read) + assertThat(otherThreadGotLock).isTrue() + } + + @Test + fun `reads the copy published first on every thread when reads race on the first read`() { + val encodingStarted = CountDownLatch(1) + val firstReadDone = CountDownLatch(1) + var otherThreadSawFirstRead = false + val serializer = NumberingDetailSerializer { call -> + // The other thread's encoding, the first call, waits until this thread's read returns. + if (call == 1) { + encodingStarted.countDown() + otherThreadSawFirstRead = firstReadDone.await(TIMEOUT_SECONDS, TimeUnit.SECONDS) + } + } + val source = argumentSourceOf(serializer, Detail("1")) + val otherRead = readOnAnotherThread(source) + assertThat(encodingStarted.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue() + + val read = source.toMap() + firstReadDone.countDown() + + assertThat(read).isEqualTo(mapOf("id" to "encoding-2")) + assertThat(otherRead.await()).isEqualTo(read) + assertThat(source.toMap()).isEqualTo(read) + assertThat(otherThreadSawFirstRead).isTrue() + } + + // Reading failures + + @Test + fun `reads as only the broken limit when the entry breaks an argument limit`() { + val source = argumentSourceOf(detailSerializer, Detail(overLimitId)) + + assertThat(source).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + } + + @Test + fun `reports the broken limit to onFailure when read`() { + val source = argumentSourceOf(detailSerializer, Detail(overLimitId)) + + source.size + + assertThat(failures).hasSize(1) + assertThat((failures.single() as DropArgumentsException).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `reads as only the encoding failure and reports a serializer's exception once across reads`() { + val error = IllegalStateException("boom") + detailSerializer.error = error + val source = argumentSourceOf(detailSerializer, Detail("1")) + + val reads = List(3) { source.toMap() } + + assertThat(reads).containsExactly(encodingFailed, encodingFailed, encodingFailed) + assertThat(failures).containsExactly(error) + } + + @Test + fun `reads as only the encoding failure and reports a serializer's LinkageError once across reads`() { + val error = NoClassDefFoundError("missing") + detailSerializer.error = error + val source = argumentSourceOf(detailSerializer, Detail("1")) + + val reads = List(3) { source.toMap() } + + assertThat(reads).containsExactly(encodingFailed, encodingFailed, encodingFailed) + assertThat(failures).containsExactly(error) + } + + @Test + fun `reads as only the broken limit and reports it when a serializer replaced it with its own exception`() { + val serializer = ReplacingSerializer(Detail.serializer()) { SerializationException("replaced") } + val source = argumentSourceOf(serializer, Detail(overLimitId)) + + val read = source.toMap() + + assertThat(read).isEqualTo(droppedBy(ArgumentDropReason.CHARACTER_LIMIT)) + assertThat(failures).hasSize(1) + assertThat((failures.single() as DropArgumentsException).reason) + .isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `propagates fatal errors when read, without reporting them`() { + val error = OutOfMemoryError() + detailSerializer.error = error + val source = argumentSourceOf(detailSerializer, Detail("1")) + + val thrown = assertFailsWith { source.size } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(failures).isEmpty() + } + + // writeTo() + + @Test + fun `writeTo() - writes the entry's properties to the sink`() { + val sink = TreeArgumentSink(ArgumentBudget()) + + argumentSourceOf(detailSerializer, Detail("1")).writeTo(sink) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `writeTo() - encodes the entry each time it's written`() { + val source = argumentSourceOf(detailSerializer, Detail("1")) + + source.writeTo(TreeArgumentSink(ArgumentBudget())) + source.writeTo(TreeArgumentSink(ArgumentBudget())) + + assertThat(detailSerializer.serialized).containsExactly(Detail("1"), Detail("1")) + } + + @Test + fun `writeTo() - spends the sink's budget`() { + // Each entry has 151 values, so two entries don't fit in one budget. + val budget = ArgumentBudget() + argumentSourceOf(Values.serializer(), Values(List(150) { it })) + .writeTo(TreeArgumentSink(budget)) + val second = argumentSourceOf(Values.serializer(), Values(List(150) { it })) + + val thrown = + assertFailsWith { second.writeTo(TreeArgumentSink(budget)) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + } + + @Test + fun `writeTo() - propagates a broken limit unchanged, without reporting it`() { + val sink = TreeArgumentSink(budgetWithValuesRemaining(0)) + + val thrown = + assertFailsWith { + argumentSourceOf(detailSerializer, Detail("1")).writeTo(sink) + } + + assertThat(thrown) + .isSameInstanceAs(assertFailsWith { sink.argumentsOrThrow() }) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - reports a serializer's exception and drops the arguments as an unlogged encoding failure`() { + val error = IllegalStateException("boom") + detailSerializer.error = error + + val thrown = + assertFailsWith { + argumentSourceOf(detailSerializer, Detail("1")).writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(thrown.warning).isNull() + assertThat(failures).containsExactly(error) + } + + @Test + fun `writeTo() - reports a serializer's LinkageError and drops the arguments as an unlogged encoding failure`() { + val error = AbstractMethodError() + detailSerializer.error = error + + val thrown = + assertFailsWith { + argumentSourceOf(detailSerializer, Detail("1")).writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(thrown.warning).isNull() + assertThat(failures).containsExactly(error) + } + + @Test + fun `writeTo() - propagates fatal errors without reporting them`() { + val error = OutOfMemoryError() + detailSerializer.error = error + + val thrown = + assertFailsWith { + argumentSourceOf(detailSerializer, Detail("1")).writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - rethrows the sink's limit that a serializer replaced with its own exception, unreported`() { + val serializer = ReplacingSerializer(Detail.serializer()) { SerializationException("replaced") } + val sink = TreeArgumentSink(ArgumentBudget()) + + val thrown = + assertFailsWith { + argumentSourceOf(serializer, Detail(overLimitId)).writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - rethrows the sink's limit that a serializer replaced with a LinkageError, unreported`() { + val serializer = ReplacingSerializer(Detail.serializer()) { NoClassDefFoundError("replaced") } + val sink = TreeArgumentSink(ArgumentBudget()) + + val thrown = + assertFailsWith { + argumentSourceOf(serializer, Detail(overLimitId)).writeTo(sink) + } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(failures).isEmpty() + } + + // writeTo() after the arguments are read + + @Test + fun `writeTo() - writes the copy read as a map rather than the entry's current properties`() { + val entry = MutableDetail("1") + val source = argumentSourceOf(mutableDetailSerializer, entry) + source.size + entry.id = "2" + val sink = TreeArgumentSink(ArgumentBudget()) + + source.writeTo(sink) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to "1")) + } + + @Test + fun `writeTo() - doesn't encode the entry again after its arguments are read`() { + val source = argumentSourceOf(mutableDetailSerializer, MutableDetail("1")) + source.size + + source.writeTo(TreeArgumentSink(ArgumentBudget())) + source.writeTo(TreeArgumentSink(ArgumentBudget())) + + assertThat(mutableDetailSerializer.serialized).hasSize(1) + } + + @Test + fun `writeTo() - encodes the entry's current properties when its arguments weren't read`() { + val entry = MutableDetail("1") + val source = argumentSourceOf(mutableDetailSerializer, entry) + entry.id = "2" + val sink = TreeArgumentSink(ArgumentBudget()) + + source.writeTo(sink) + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("id" to "2")) + } + + @Test + fun `reads a copy encoded separately from what writeTo() wrote`() { + val entry = MutableDetail("1") + val source = argumentSourceOf(mutableDetailSerializer, entry) + source.writeTo(TreeArgumentSink(ArgumentBudget())) + entry.id = "2" + + val read = source.toMap() + + assertThat(read).isEqualTo(mapOf("id" to "2")) + assertThat(mutableDetailSerializer.serialized).hasSize(2) + } + + @Test + fun `writeTo() - spends the sink's value budget when writing the copy read`() { + // The entry has 151 values, which fit in its own budget but not in the 100 the sink has left. + val source = argumentSourceOf(Values.serializer(), Values(List(150) { it })) + source.size + val sink = TreeArgumentSink(budgetWithValuesRemaining(100)) + + val thrown = assertFailsWith { source.writeTo(sink) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.MAX_COUNT) + assertThat(thrown.warning).isEqualTo(DropArgumentsException.MAX_COUNT_WARNING) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - spends the sink's character budget when writing the copy read`() { + val source = argumentSourceOf(detailSerializer, Detail("123")) + source.size + val sink = TreeArgumentSink(budgetWithCharactersRemaining(4)) + + val thrown = assertFailsWith { source.writeTo(sink) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(thrown.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) + assertThat(failures).isEmpty() + } + + @Test + fun `writeTo() - drops the arguments for the limit the copy read broke without encoding again`() { + val source = argumentSourceOf(detailSerializer, Detail(overLimitId)) + source.size + val sink = TreeArgumentSink(ArgumentBudget()) + + val thrown = assertFailsWith { source.writeTo(sink) } + + assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(thrown.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) + assertThat(detailSerializer.serialized).hasSize(1) + // Only the read reports the limit; the sink's owner reports it again for writeTo(). + assertThat(failures).hasSize(1) + } + + @Test + fun `writeTo() - drops the arguments without encoding or reporting again when the copy read failed`() { + val error = IllegalStateException("boom") + detailSerializer.error = error + val source = argumentSourceOf(detailSerializer, Detail("1")) + source.size + val sink = TreeArgumentSink(ArgumentBudget()) + + val thrown = assertFailsWith { source.writeTo(sink) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(thrown.warning).isNull() + assertThat(sink.failure).isNull() + assertThat(detailSerializer.serialized).hasSize(1) + assertThat(failures).containsExactly(error) + } + + @Test + fun `writeTo() - drops the arguments as the encoding failure the copy read even if encoding again would succeed`() { + detailSerializer.error = IllegalStateException("boom") + detailSerializer.failsFor = { detailSerializer.serialized.size == 1 } + val source = argumentSourceOf(detailSerializer, Detail("1")) + source.size + + val thrown = + assertFailsWith { + source.writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(source.toMap()).isEqualTo(encodingFailed) + } + + @Test + fun `writeTo() - spends none of the sink's budget when the copy read failed to encode`() { + // The copy's 11 values (the list and its elements) were written before its serializer threw. + val source = + argumentSourceOf(ThrowsAfterEncodingSerializer(Values.serializer()), Values(List(10) { it })) + source.size + val budget = budgetWithValuesRemaining(12) + assertFailsWith { source.writeTo(TreeArgumentSink(budget)) } + val nextSink = TreeArgumentSink(budget) + + repeat(12) { + nextSink.key("value$it") + nextSink.scalar(it) + } + + assertThat(nextSink.argumentsOrThrow()).hasSize(12) + } + + @Test + fun `writeTo() - drops a failed copy's arguments as an encoding failure, not a sink limit`() { + // The entry's 151 values fit in the copy's own budget, so the copy failed only once its + // serializer threw. Encoding the entry into the sink would have overflowed its 100 values. + val serializer = ThrowsAfterEncodingSerializer(Values.serializer()) + val source = argumentSourceOf(serializer, Values(List(150) { it })) + source.size + val sink = TreeArgumentSink(budgetWithValuesRemaining(100)) + + val thrown = assertFailsWith { source.writeTo(sink) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(sink.failure).isNull() + assertThat(failures).containsExactly(serializer.error) + } + + /** + * Reads [source] as a map on a new thread. The returned read's [OtherThreadRead.await] fails + * rather than hangs if the thread doesn't finish in time. + */ + private fun readOnAnotherThread(source: Map): OtherThreadRead { + val read = OtherThreadRead() + read.thread = + thread(name = "other-reader") { + try { + read.result = source.toMap() + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + read.error = t + } + } + return read + } + + /** A read of the arguments on another thread, whose result [await] returns. */ + private class OtherThreadRead { + lateinit var thread: Thread + @Volatile var result: Map? = null + @Volatile var error: Throwable? = null + + fun await(): Map? { + thread.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS * 2)) + assertThat(thread.isAlive).isFalse() + error?.let { throw it } + return result + } + } + + // Serializers that stop part-way + + @Test + fun `reads as only the encoding failure when a serializer leaves a list open`() { + val source = argumentSourceOf(UnclosedListSerializer, Detail("1")) + + assertThat(source.toMap()).isEqualTo(encodingFailed) + assertThat(failures.single()).isInstanceOf(ArgumentProtocolException::class.java) + } + + @Test + fun `writeTo() - drops the arguments as an encoding failure when a list is left open`() { + val thrown = + assertFailsWith { + argumentSourceOf(UnclosedListSerializer, Detail("1")) + .writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(failures.single()).isInstanceOf(ArgumentProtocolException::class.java) + } + + @Test + fun `reads as only the encoding failure when a serializer's last key has no value`() { + val source = argumentSourceOf(ValuelessKeySerializer(writesSecond = false), Detail("1")) + + assertThat(source.toMap()).isEqualTo(encodingFailed) + assertThat(failures.single()).isInstanceOf(ArgumentProtocolException::class.java) + } + + @Test + fun `writeTo() - drops the arguments as an encoding failure when a key has no value`() { + val thrown = + assertFailsWith { + argumentSourceOf(ValuelessKeySerializer(writesSecond = true), Detail("1")) + .writeTo(TreeArgumentSink(ArgumentBudget())) + } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(failures.single()).isInstanceOf(ArgumentProtocolException::class.java) + } + + @Suppress("UNCHECKED_CAST") + private fun argumentSourceOf( + serializer: KSerializer, + entry: T, + ): KotlinxArgumentSource = + KotlinxArgumentSource(entry, serializer as KSerializer) { failures += it } + + private companion object { + /** Bounds every wait, so that a deadlock fails the test rather than hanging it. */ + const val TIMEOUT_SECONDS = 5L + } +} 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/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt new file mode 100644 index 0000000000..61fd44fc28 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt @@ -0,0 +1,36 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.common.ArgumentSink +import io.sentry.compose.navigation3.internal.common.DropArgumentsException +import io.sentry.compose.navigation3.internal.contract.ArgumentDropReason +import kotlin.test.assertFailsWith +import org.junit.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.verifyNoInteractions + +class KotlinxUnencodableArgumentsTest { + + @Test + fun `reads as only the encoding failure`() { + val arguments: Map = KotlinxUnencodableArguments + + assertThat(arguments) + .containsExactly( + ArgumentDropReason.ARGUMENT_DROP_REASON_KEY, + ArgumentDropReason.ENCODING_FAILED.serializedValue, + ) + } + + @Test + fun `writeTo() - drops the arguments as an unlogged encoding failure without writing to the sink`() { + val sink = mock() + + val thrown = + assertFailsWith { KotlinxUnencodableArguments.writeTo(sink) } + + assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) + assertThat(thrown.warning).isNull() + verifyNoInteractions(sink) + } +} 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,