Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import io.sentry.SentryLevel.WARNING
import io.sentry.compose.navigation3.BackStackEntryMapper
import io.sentry.compose.navigation3.SentryBackStackEntry
import io.sentry.compose.navigation3.internal.common.ArgumentBudget
import io.sentry.compose.navigation3.internal.common.ArgumentSource
import io.sentry.compose.navigation3.internal.common.DropArgumentsException
import io.sentry.compose.navigation3.internal.common.HostArgumentSource
import io.sentry.compose.navigation3.internal.common.TreeArgumentSink
Expand Down Expand Up @@ -153,8 +154,10 @@ internal class BackStackConverter<T : Any>(
* 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.
Expand Down Expand Up @@ -185,14 +188,18 @@ internal class BackStackConverter<T : Any>(
return SanitizedArguments(emptyMap(), reason)
}

val source = HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) }
val source =
raw as? ArgumentSource
?: HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) }
val sink = TreeArgumentSink(budget)

// A constraint violation the sink recorded takes precedence over whatever the source threw,
// as the source may have caught it and thrown something else, and it decides whether older
// entries keep their arguments.
return try {
source.writeTo(sink)
// Record only the copy the sink built. A mapper's arguments may keep their back stack entry
// in memory (e.g., KotlinxArgumentSource, which encodes lazily).
SanitizedArguments(sink.argumentsOrThrow())
} catch (drop: DropArgumentsException) {
drop(sink.failure ?: drop)
Expand All @@ -211,7 +218,7 @@ internal class BackStackConverter<T : Any>(
if (drop.reason.exhaustsUpdateBudget) {
dropReason = drop.reason
}
logger.log(WARNING, drop.warning)
drop.warning?.let { logger.log(WARNING, it) }
return SanitizedArguments(emptyMap(), drop.reason)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Any>,
private val onFailure: (Throwable) -> Unit,
) : AbstractMap<String, Any?>(), ArgumentSource {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So my clanker tells me that SentryBackStackEntry.equals and hashCode delegate to arguments. This means that comparing two entries or putting one in a HashSet now runs the app's serializers on whatever thread we're currently on.
The issue is that the java spec says that equals shouldn't have side effects!

My clanker thinks the code could be vastly simplified if we removed the laziness here.


private val copy: Lazy<EncodedCopy> =
// 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<Map.Entry<String, Any?>>
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<String, Any?>,
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<String, Any?> =
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<String, Any?>(), ArgumentSource {

private val dropReason =
mapOf(ARGUMENT_DROP_REASON_KEY to ArgumentDropReason.ENCODING_FAILED.serializedValue)

override val entries: Set<Map.Entry<String, Any?>>
get() = dropReason.entries

override fun writeTo(sink: ArgumentSink) {
throw DropArgumentsException(ArgumentDropReason.ENCODING_FAILED, warning = null)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -200,11 +200,16 @@ internal class ArgumentBudget {
internal class ArgumentProtocolException(message: String) : IllegalStateException(message)

/**
* Control-flow signal to drop a back stack entry's arguments, logging [warning]. Overrides
* [fillInStackTrace] to skip stack-trace capture.
* Control-flow signal to drop a back stack entry's arguments. Overrides [fillInStackTrace] to skip
* stack-trace capture.
*
* [warning] is logged when the arguments are dropped, or not at all if `null` (e.g., because the
* [ArgumentSource] reported the failure itself).
*/
internal class DropArgumentsException(val reason: ArgumentDropReason, val warning: String) :
RuntimeException() {
internal class DropArgumentsException(
val reason: ArgumentDropReason,
val warning: String?,
) : RuntimeException() {

override fun fillInStackTrace(): Throwable = this

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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].
*/
Expand All @@ -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");
Expand Down
Loading
Loading