From 0f933af8f3019eab552c17118db5ee967deb15a3 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Mon, 30 Nov 2026 11:47:48 +0100 Subject: [PATCH 1/3] feat(nav3): Add a lazily encoding argument source for kotlinx properties Add KotlinxArgumentSource, the arguments the SerialNameAndProperties mapper will return. It encodes an entry's properties only when they're read or written, so an entry whose arguments the update's budget has already ruled out isn't encoded at all. Read as a map, it encodes once and caches the result; written to the sanitizer's sink, it encodes against the update's shared budget. ArgumentSanitizer now lets arguments that are an ArgumentSource write themselves, and a source can drop its arguments without a warning when it has reported the failure itself. Add the encoding_failed drop reason for entries whose properties can't be encoded. Co-Authored-By: Claude Opus 5.5 --- .../internal/backstack/BackStackConverter.kt | 15 +- .../kotlinx/KotlinxArgumentSource.kt | 174 +++++ .../internal/common/ArgumentProtocol.kt | 13 +- .../internal/contract/NavDataContract.kt | 3 +- .../backstack/ArgumentSanitizerTest.kt | 190 +++++ .../backstack/BackStackConverterTest.kt | 23 + .../backstack/SelfWritingArguments.kt | 18 + .../kotlinx/KotlinxArgumentSourceTest.kt | 701 ++++++++++++++++++ .../backstack/kotlinx/KotlinxTestEntries.kt | 5 + .../KotlinxUnencodableArgumentsTest.kt | 36 + .../internal/contract/NavDataContractTest.kt | 2 + 11 files changed, 1171 insertions(+), 9 deletions(-) create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSource.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSourceTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt 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 6e2aa982c0..50d4d88c61 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.ArgumentWriteResult import io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.common.HostArgumentSource @@ -154,8 +155,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,9 +188,13 @@ 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) } return when (val result = TreeArgumentSink(budget).write(source)) { + // 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). is ArgumentWriteResult.Written -> SanitizedArguments(result.arguments) is ArgumentWriteResult.Dropped -> drop(result.drop) is ArgumentWriteResult.Failed -> { @@ -201,7 +208,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 63635f5f20..63de82dcfd 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 @@ -216,11 +216,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, From e2c4e4b7859215fc688e7946623336616b763f5b Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 4 Dec 2026 11:16:07 +0100 Subject: [PATCH 2/3] ref(nav3): Read KotlinxArgumentSource's encoded copy from the write result KotlinxArgumentSource checked the sink's recorded failure in each catch to decide which failure dropped the arguments. Its cached copy now comes from TreeArgumentSink.write, which makes that decision, and encode calls checkNotDropped() where a serializer may have replaced a broken limit with its own exception. ArgumentSource becomes a fun interface so encode can be passed to write directly. Refs JAVA-787 Co-Authored-By: Claude Opus 5.5 --- .../kotlinx/KotlinxArgumentSource.kt | 48 +++++++++++-------- .../internal/common/ArgumentProtocol.kt | 2 +- .../kotlinx/KotlinxArgumentSourceTest.kt | 13 +++-- 3 files changed, 38 insertions(+), 25 deletions(-) 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 index 65515c1d2c..5f12b85bc7 100644 --- 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 @@ -3,6 +3,7 @@ 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.ArgumentWriteResult import io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.common.HostArgumentSource import io.sentry.compose.navigation3.internal.common.TreeArgumentSink @@ -62,47 +63,56 @@ internal class KotlinxArgumentSource( } } + /** + * Encodes the entry's properties into [sink], turning any failure of the entry's serializers into + * an [ArgumentDropReason.ENCODING_FAILED] drop. A broken limit propagates unchanged, as does the + * limit a serializer broke before throwing its own exception. + */ @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 + // Keep the broken limit's reason rather than replacing it with ENCODING_FAILED below. + throw 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 } + sink.checkNotDropped() 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 } + // A serializer may replace a broken limit with its own exception. The limit decides whether + // older entries keep their arguments, so it's dropped for that instead, without reporting. + sink.checkNotDropped() 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) + private fun encodeCopy(): EncodedCopy = + when (val result = TreeArgumentSink(ArgumentBudget()).write(ArgumentSource(::encode))) { + is ArgumentWriteResult.Written -> EncodedCopy(result.arguments, failure = null) + is ArgumentWriteResult.Dropped -> { + // encode already reported an encoding failure. + if (result.drop.reason != ArgumentDropReason.ENCODING_FAILED) { + onFailure(result.drop) + } + EncodedCopy(emptyMap(), failure = result.drop) + } + // Not expected, as encode turns every non-fatal failure into a drop. + is ArgumentWriteResult.Failed -> { + onFailure(result.cause) + EncodedCopy( + emptyMap(), + failure = DropArgumentsException(ArgumentDropReason.ENCODING_FAILED, warning = null), + ) } - EncodedCopy(emptyMap(), failure = e) } - } /** * Arguments encoded from a single back stack entry's properties: [written] if encoding succeeded, 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 63de82dcfd..ec26c641ed 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/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 index 0bb354ca7c..87f289f959 100644 --- 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 @@ -433,7 +433,8 @@ class KotlinxArgumentSourceTest { argumentSourceOf(serializer, Detail(overLimitId)).writeTo(sink) } - assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown) + .isSameInstanceAs(assertFailsWith { sink.checkNotDropped() }) assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) assertThat(failures).isEmpty() } @@ -448,7 +449,8 @@ class KotlinxArgumentSourceTest { argumentSourceOf(serializer, Detail(overLimitId)).writeTo(sink) } - assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown) + .isSameInstanceAs(assertFailsWith { sink.checkNotDropped() }) assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) assertThat(failures).isEmpty() } @@ -539,7 +541,8 @@ class KotlinxArgumentSourceTest { val thrown = assertFailsWith { source.writeTo(sink) } - assertThat(thrown).isSameInstanceAs(sink.failure) + assertThat(thrown) + .isSameInstanceAs(assertFailsWith { sink.checkNotDropped() }) assertThat(thrown.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) assertThat(thrown.warning).isEqualTo(DropArgumentsException.MAX_CHARACTER_WARNING) assertThat(detailSerializer.serialized).hasSize(1) @@ -559,7 +562,7 @@ class KotlinxArgumentSourceTest { assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) assertThat(thrown.warning).isNull() - assertThat(sink.failure).isNull() + sink.checkNotDropped() assertThat(detailSerializer.serialized).hasSize(1) assertThat(failures).containsExactly(error) } @@ -610,7 +613,7 @@ class KotlinxArgumentSourceTest { val thrown = assertFailsWith { source.writeTo(sink) } assertThat(thrown.reason).isEqualTo(ArgumentDropReason.ENCODING_FAILED) - assertThat(sink.failure).isNull() + sink.checkNotDropped() assertThat(failures).containsExactly(serializer.error) } From 03c5a89bc8eeb27474eebd32d78194deb144fdd7 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Fri, 4 Dec 2026 11:44:25 +0100 Subject: [PATCH 3/3] ref(nav3): Encode kotlinx back stack entry properties eagerly KotlinxArgumentSource encoded an entry's properties only when its arguments were read or written. As a map, its equals and hashCode read its entries, so comparing two SentryBackStackEntry values ran the app's serializers on the comparing thread, and could change what Sentry later recorded. Replace it with KotlinxArguments.encode, which encodes an entry once, into a budget of its own, and returns a plain map. The sanitizer treats that map like any other mapper's, so it no longer needs arguments that write themselves, and a dropped entry's reason is an ordinary argument. Eager encoding runs every captured entry's serializers, including those of entries whose arguments the update's budget will drop. Measured on a Pixel 4, that costs 30-60 us more per navigation at the default of 5 captured entries, and grows with the number captured. Treat maxCapturedBackStackEntries values above 25 as 25 to bound it. Refs JAVA-787 Co-Authored-By: Claude Opus 5.5 --- .../compose/navigation3/SentryNavOptions.kt | 9 +- .../internal/backstack/BackStackConverter.kt | 15 +- .../kotlinx/KotlinxArgumentSource.kt | 184 ----- .../backstack/kotlinx/KotlinxArguments.kt | 59 ++ .../internal/common/ArgumentProtocol.kt | 13 +- .../navigation3/SentryNavOptionsTest.kt | 14 + .../backstack/ArgumentSanitizerTest.kt | 190 ----- .../backstack/BackStackConverterTest.kt | 23 - .../backstack/SelfWritingArguments.kt | 18 - .../kotlinx/KotlinxArgumentSourceTest.kt | 704 ------------------ .../backstack/kotlinx/KotlinxArgumentsTest.kt | 200 +++++ .../KotlinxUnencodableArgumentsTest.kt | 36 - 12 files changed, 288 insertions(+), 1177 deletions(-) delete mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSource.kt create mode 100644 sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArguments.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSourceTest.kt create mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentsTest.kt delete mode 100644 sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt 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/BackStackConverter.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackConverter.kt index 50d4d88c61..6e2aa982c0 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,7 +6,6 @@ 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.ArgumentWriteResult import io.sentry.compose.navigation3.internal.common.DropArgumentsException import io.sentry.compose.navigation3.internal.common.HostArgumentSource @@ -155,10 +154,8 @@ 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 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]. + * Each entry's arguments are written by a [HostArgumentSource] into a [TreeArgumentSink], which + * bounds depth and total value count, and rejects cyclic structures. * * One instance is shared across every entry in a single [convert] call, so the value and * character budgets span the whole update. @@ -188,13 +185,9 @@ internal class BackStackConverter( return SanitizedArguments(emptyMap(), reason) } - val source = - raw as? ArgumentSource - ?: HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } + val source = HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } return when (val result = TreeArgumentSink(budget).write(source)) { - // 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). is ArgumentWriteResult.Written -> SanitizedArguments(result.arguments) is ArgumentWriteResult.Dropped -> drop(result.drop) is ArgumentWriteResult.Failed -> { @@ -208,7 +201,7 @@ internal class BackStackConverter( if (drop.reason.exhaustsUpdateBudget) { dropReason = drop.reason } - drop.warning?.let { logger.log(WARNING, it) } + logger.log(WARNING, drop.warning) 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 deleted file mode 100644 index 5f12b85bc7..0000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSource.kt +++ /dev/null @@ -1,184 +0,0 @@ -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.ArgumentWriteResult -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) - } - } - - /** - * Encodes the entry's properties into [sink], turning any failure of the entry's serializers into - * an [ArgumentDropReason.ENCODING_FAILED] drop. A broken limit propagates unchanged, as does the - * limit a serializer broke before throwing its own exception. - */ - @Suppress("ThrowsCount") - private fun encode(sink: ArgumentSink) { - try { - KotlinxPropertiesEncoder.encode(serializer, backStackEntry, sink) - } catch (e: DropArgumentsException) { - // Keep the broken limit's reason rather than replacing it with ENCODING_FAILED below. - throw 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.checkNotDropped() - 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 broken limit with its own exception. The limit decides whether - // older entries keep their arguments, so it's dropped for that instead, without reporting. - sink.checkNotDropped() - onFailure(t) - throw DropArgumentsException(ArgumentDropReason.ENCODING_FAILED, warning = null) - } - } - - private fun encodeCopy(): EncodedCopy = - when (val result = TreeArgumentSink(ArgumentBudget()).write(ArgumentSource(::encode))) { - is ArgumentWriteResult.Written -> EncodedCopy(result.arguments, failure = null) - is ArgumentWriteResult.Dropped -> { - // encode already reported an encoding failure. - if (result.drop.reason != ArgumentDropReason.ENCODING_FAILED) { - onFailure(result.drop) - } - EncodedCopy(emptyMap(), failure = result.drop) - } - // Not expected, as encode turns every non-fatal failure into a drop. - is ArgumentWriteResult.Failed -> { - onFailure(result.cause) - EncodedCopy( - emptyMap(), - failure = DropArgumentsException(ArgumentDropReason.ENCODING_FAILED, warning = null), - ) - } - } - - /** - * 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/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 ec26c641ed..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 @@ -216,16 +216,11 @@ internal class ArgumentBudget { internal class ArgumentProtocolException(message: String) : IllegalStateException(message) /** - * 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). + * Control-flow signal to drop a back stack entry's arguments, logging [warning]. Overrides + * [fillInStackTrace] to skip stack-trace capture. */ -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/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/ArgumentSanitizerTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt index 965b9c329f..170796764f 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,7 +18,6 @@ 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 { @@ -238,193 +237,4 @@ 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 cc3aca060e..6e2e5f7854 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,7 +1,6 @@ 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 @@ -554,28 +553,6 @@ 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 deleted file mode 100644 index c1fdfd6ff5..0000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 87f289f959..0000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxArgumentSourceTest.kt +++ /dev/null @@ -1,704 +0,0 @@ -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(assertFailsWith { sink.checkNotDropped() }) - 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(assertFailsWith { sink.checkNotDropped() }) - 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(assertFailsWith { sink.checkNotDropped() }) - 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() - sink.checkNotDropped() - 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) - sink.checkNotDropped() - 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/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/KotlinxUnencodableArgumentsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt deleted file mode 100644 index 61fd44fc28..0000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxUnencodableArgumentsTest.kt +++ /dev/null @@ -1,36 +0,0 @@ -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) - } -}