|
| 1 | +package io.sentry.compose.navigation3 |
| 2 | + |
| 3 | +import io.sentry.ILogger |
| 4 | +import io.sentry.SentryLevel.WARNING |
| 5 | +import io.sentry.util.ExceptionUtils |
| 6 | +import java.util.IdentityHashMap |
| 7 | + |
| 8 | +/** Translates app-defined back stack entries into displayable [RouteEntry]s. */ |
| 9 | +internal class RouteTranslator<T : Any>( |
| 10 | + private val resolvers: () -> RouteResolvers<T>, |
| 11 | + private val maxCapturedBackStackEntries: Int, |
| 12 | + private val logger: ILogger, |
| 13 | +) { |
| 14 | + |
| 15 | + internal class UpdateWarningState { |
| 16 | + private var hasLoggedUnsupportedValueWarning = false |
| 17 | + |
| 18 | + fun logUnsupportedValueWarning(typeName: String?, logger: ILogger) { |
| 19 | + if (hasLoggedUnsupportedValueWarning) { |
| 20 | + return |
| 21 | + } |
| 22 | + |
| 23 | + logger.log( |
| 24 | + WARNING, |
| 25 | + "Nav3 argumentsExtractor returned unsupported value of type %s while processing this back " + |
| 26 | + "stack update. Falling back to toString(). Use String, CharSequence, Char, Number, " + |
| 27 | + "Boolean, Enum, Map, Collection, object Array, and primitive array values for reliable " + |
| 28 | + "results.", |
| 29 | + typeName, |
| 30 | + ) |
| 31 | + hasLoggedUnsupportedValueWarning = true |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + companion object { |
| 36 | + |
| 37 | + /** |
| 38 | + * Max nesting depth allowed while sanitizing a single argument value for a given back stack |
| 39 | + * entry. |
| 40 | + * |
| 41 | + * If exceeded, all arguments for that back stack entry are dropped. |
| 42 | + */ |
| 43 | + private const val MAX_ARGUMENT_DEPTH = 20 |
| 44 | + |
| 45 | + /** |
| 46 | + * Max number of argument values visited while sanitizing all entries in a given back stack |
| 47 | + * update. |
| 48 | + * |
| 49 | + * If exceeded, the entry that overflows loses its arguments, as do older entries; newer entries |
| 50 | + * are preserved. E.g., suppose we have the following back stack: |
| 51 | + * |
| 52 | + * - /Checkout -> Top of the stack and processed first |
| 53 | + * - /ProductDetail -> Processed second and overflows the `MAX_ARGUMENT_VALUES` budget |
| 54 | + * - /Home |
| 55 | + * |
| 56 | + * Then /ProductDetail and /Home will have no arguments, but /Checkout will. |
| 57 | + */ |
| 58 | + private const val MAX_ARGUMENT_VALUES = 1_000 |
| 59 | + } |
| 60 | + |
| 61 | + /** Converts the provided [backStack] into a serializable list of [RouteEntry]s. */ |
| 62 | + fun toRouteEntries( |
| 63 | + backStack: List<T>, |
| 64 | + updateWarningState: UpdateWarningState = UpdateWarningState(), |
| 65 | + ): List<RouteEntry> { |
| 66 | + val state = ArgumentSanitizationState() |
| 67 | + |
| 68 | + return backStack.takeLast(maxCapturedBackStackEntries).asReversed().map { entry -> |
| 69 | + buildMap { |
| 70 | + put("route", resolveRouteName(entry)) |
| 71 | + |
| 72 | + val args = |
| 73 | + if (state.isValueBudgetExceeded()) { |
| 74 | + emptyMap() |
| 75 | + } else { |
| 76 | + resolveArguments(entry, state, updateWarningState) |
| 77 | + } |
| 78 | + if (args.isNotEmpty()) { |
| 79 | + put("args", args) |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Returns a route name for the provided [backStackEntry], based on this translator's |
| 87 | + * [name extractor][RouteResolvers.nameExtractor]. |
| 88 | + * |
| 89 | + * The returned name is normalized to always include a leading slash. E.g., both `PromoDialog` and |
| 90 | + * `/PromoDialog` are resolved to `/PromoDialog`. (Doing so maintains parity with our Nav2 |
| 91 | + * convention.) |
| 92 | + */ |
| 93 | + @Suppress("TooGenericExceptionCaught") |
| 94 | + fun resolveRouteName(backStackEntry: T): String { |
| 95 | + val name = |
| 96 | + try { |
| 97 | + resolvers.invoke().getName(backStackEntry) |
| 98 | + } catch (t: Throwable) { |
| 99 | + ExceptionUtils.rethrowIfFatal(t) |
| 100 | + logger.log( |
| 101 | + WARNING, |
| 102 | + "Nav3 nameExtractor threw while resolving a route name. Falling back to class simpleName.", |
| 103 | + t, |
| 104 | + ) |
| 105 | + null |
| 106 | + } ?: backStackEntry::class.simpleName ?: "unknown" |
| 107 | + |
| 108 | + return "/${name.removePrefix("/")}" |
| 109 | + } |
| 110 | + |
| 111 | + /** |
| 112 | + * Returns the arguments for the provided [backStackEntry], based on this translator's |
| 113 | + * [arguments extractor][RouteResolvers.argumentsExtractor]. |
| 114 | + * |
| 115 | + * The arguments are sanitized before being returned, i.e., bounded in size and depth, and |
| 116 | + * converted into a serializable form. |
| 117 | + */ |
| 118 | + @Suppress("TooGenericExceptionCaught") |
| 119 | + fun resolveArguments( |
| 120 | + backStackEntry: T, |
| 121 | + updateWarningState: UpdateWarningState = UpdateWarningState(), |
| 122 | + ): Map<String, Any?> = |
| 123 | + resolveArguments(backStackEntry, ArgumentSanitizationState(), updateWarningState) |
| 124 | + |
| 125 | + @Suppress("TooGenericExceptionCaught") |
| 126 | + private fun resolveArguments( |
| 127 | + backStackEntry: T, |
| 128 | + state: ArgumentSanitizationState, |
| 129 | + updateWarningState: UpdateWarningState, |
| 130 | + ): Map<String, Any?> { |
| 131 | + val raw = |
| 132 | + try { |
| 133 | + resolvers.invoke().getArguments(backStackEntry) ?: return emptyMap() |
| 134 | + } catch (t: Throwable) { |
| 135 | + ExceptionUtils.rethrowIfFatal(t) |
| 136 | + logger.log( |
| 137 | + WARNING, |
| 138 | + "Nav3 argumentsExtractor threw while resolving arguments. Skipping arguments.", |
| 139 | + t, |
| 140 | + ) |
| 141 | + return emptyMap() |
| 142 | + } |
| 143 | + |
| 144 | + return try { |
| 145 | + sanitizeArguments(raw, state, updateWarningState) |
| 146 | + } catch (_: ArgumentValueBudgetExceededException) { |
| 147 | + logger.log( |
| 148 | + WARNING, |
| 149 | + "Nav3 arguments exceeded the maximum total value count for one backstack update. " + |
| 150 | + "Skipping arguments for this and older captured entries.", |
| 151 | + ) |
| 152 | + emptyMap() |
| 153 | + } catch (_: ArgumentStructureException) { |
| 154 | + logger.log( |
| 155 | + WARNING, |
| 156 | + "Nav3 argument sanitization failed (possibly a cyclic or deeply nested structure). " + |
| 157 | + "Skipping arguments.", |
| 158 | + ) |
| 159 | + emptyMap() |
| 160 | + } catch (t: Throwable) { |
| 161 | + ExceptionUtils.rethrowIfFatal(t) |
| 162 | + logger.log( |
| 163 | + WARNING, |
| 164 | + "Nav3 argument sanitization failed (possibly a cyclic or deeply nested structure). " + |
| 165 | + "Skipping arguments.", |
| 166 | + t, |
| 167 | + ) |
| 168 | + emptyMap() |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + private fun sanitizeArguments( |
| 173 | + args: Map<String, Any?>, |
| 174 | + state: ArgumentSanitizationState, |
| 175 | + updateWarningState: UpdateWarningState, |
| 176 | + ): Map<String, Any?> = sanitizeMap(args, state, depth = 0, updateWarningState) |
| 177 | + |
| 178 | + private fun sanitizeMap( |
| 179 | + value: Map<*, *>, |
| 180 | + state: ArgumentSanitizationState, |
| 181 | + depth: Int, |
| 182 | + updateWarningState: UpdateWarningState, |
| 183 | + ): Map<String, Any?> { |
| 184 | + state.enter(value) |
| 185 | + try { |
| 186 | + val sanitized = LinkedHashMap<String, Any?>() |
| 187 | + for ((key, childValue) in value) { |
| 188 | + sanitized[key.toString()] = sanitizeValue(childValue, state, depth + 1, updateWarningState) |
| 189 | + } |
| 190 | + return sanitized |
| 191 | + } finally { |
| 192 | + state.exit(value) |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + private fun sanitizeCollection( |
| 197 | + value: Collection<*>, |
| 198 | + state: ArgumentSanitizationState, |
| 199 | + depth: Int, |
| 200 | + updateWarningState: UpdateWarningState, |
| 201 | + ): List<Any?> { |
| 202 | + state.enter(value) |
| 203 | + try { |
| 204 | + val sanitized = ArrayList<Any?>() |
| 205 | + for (childValue in value) { |
| 206 | + sanitized += sanitizeValue(childValue, state, depth + 1, updateWarningState) |
| 207 | + } |
| 208 | + return sanitized |
| 209 | + } finally { |
| 210 | + state.exit(value) |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + private fun sanitizeValue( |
| 215 | + value: Any?, |
| 216 | + state: ArgumentSanitizationState, |
| 217 | + depth: Int, |
| 218 | + updateWarningState: UpdateWarningState, |
| 219 | + ): Any? { |
| 220 | + state.visit(depth) |
| 221 | + val collection = value?.asSanitizableCollectionOrNull() |
| 222 | + |
| 223 | + return when { |
| 224 | + value == null || value is String || value is Number || value is Boolean -> value |
| 225 | + value is CharSequence || value is Char -> value.toString() |
| 226 | + value is Enum<*> -> value.name |
| 227 | + value is Map<*, *> -> sanitizeMap(value, state, depth, updateWarningState) |
| 228 | + collection != null -> sanitizeCollection(collection, state, depth, updateWarningState) |
| 229 | + else -> { |
| 230 | + updateWarningState.logUnsupportedValueWarning(value::class.simpleName, logger) |
| 231 | + value.toString() |
| 232 | + } |
| 233 | + } |
| 234 | + } |
| 235 | + |
| 236 | + private fun Any.asSanitizableCollectionOrNull(): Collection<*>? = |
| 237 | + when (this) { |
| 238 | + is Collection<*> -> this |
| 239 | + is Array<*> -> asList() |
| 240 | + is BooleanArray -> asList() |
| 241 | + is ByteArray -> asList() |
| 242 | + is ShortArray -> asList() |
| 243 | + is IntArray -> asList() |
| 244 | + is LongArray -> asList() |
| 245 | + is FloatArray -> asList() |
| 246 | + is DoubleArray -> asList() |
| 247 | + is CharArray -> asList() |
| 248 | + else -> null |
| 249 | + } |
| 250 | + |
| 251 | + private class ArgumentSanitizationState { |
| 252 | + |
| 253 | + private val activeContainers = IdentityHashMap<Any, Unit>() |
| 254 | + private var valueCount = 0 |
| 255 | + private var valueBudgetExceeded = false |
| 256 | + |
| 257 | + fun visit(depth: Int) { |
| 258 | + if (depth > MAX_ARGUMENT_DEPTH) { |
| 259 | + throw ArgumentStructureException("Nav3 arguments exceed the maximum depth") |
| 260 | + } |
| 261 | + if (++valueCount > MAX_ARGUMENT_VALUES) { |
| 262 | + valueBudgetExceeded = true |
| 263 | + throw ArgumentValueBudgetExceededException( |
| 264 | + "Nav3 arguments exceed the maximum total value count for one backstack update" |
| 265 | + ) |
| 266 | + } |
| 267 | + } |
| 268 | + |
| 269 | + fun enter(container: Any) { |
| 270 | + if (activeContainers.put(container, Unit) != null) { |
| 271 | + throw ArgumentStructureException("Nav3 arguments contain a cyclic reference") |
| 272 | + } |
| 273 | + } |
| 274 | + |
| 275 | + fun exit(container: Any) { |
| 276 | + activeContainers.remove(container) |
| 277 | + } |
| 278 | + |
| 279 | + fun isValueBudgetExceeded(): Boolean = valueBudgetExceeded |
| 280 | + } |
| 281 | + |
| 282 | + private open class ArgumentSanitizationException(message: String) : |
| 283 | + IllegalArgumentException(message) |
| 284 | + |
| 285 | + private class ArgumentStructureException(message: String) : ArgumentSanitizationException(message) |
| 286 | + |
| 287 | + private class ArgumentValueBudgetExceededException(message: String) : |
| 288 | + ArgumentSanitizationException(message) |
| 289 | +} |
| 290 | + |
| 291 | +/** |
| 292 | + * A map consisting of a single route <> route name pair, and zero or more argument pairs. |
| 293 | + * |
| 294 | + * E.g., in serialized form: |
| 295 | + * ``` |
| 296 | + * { |
| 297 | + * "route": "/ProductScreen" |
| 298 | + * "args": { |
| 299 | + * "product_id": 12345 |
| 300 | + * "promo_id:": "spring-marketing-drive-2026" |
| 301 | + * } |
| 302 | + * } |
| 303 | + * ``` |
| 304 | + * |
| 305 | + * By convention, all route names are normalized to include a leading slash, and all arguments are |
| 306 | + * sanitized (i.e., bounded in size and depth, and converted into a serializable form). |
| 307 | + */ |
| 308 | +internal typealias RouteEntry = Map<String, Any?> |
0 commit comments