Skip to content

Commit c9f806c

Browse files
committed
feat(android-nav3): Model navigation routes
Introduce the route translation layer for Navigation 3 so later stages can reason about route names and sanitized arguments in one place. At this stage the module still exposes no meaningful public API surface.
1 parent 6c2b8f9 commit c9f806c

7 files changed

Lines changed: 741 additions & 0 deletions

File tree

‎gradle/libs.versions.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ androidx-activity-compose = { module = "androidx.activity:activity-compose", ver
9090
androidx-compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "androidxCompose" }
9191
androidx-compose-foundation-layout = { module = "androidx.compose.foundation:foundation-layout", version.ref = "androidxCompose" }
9292
androidx-compose-material3 = { module = "androidx.compose.material3:material3", version = "1.4.0" }
93+
androidx-compose-runtime = { module = "androidx.compose.runtime:runtime", version.ref = "androidxCompose" }
9394
androidx-compose-material-icons-core = { module = "androidx.compose.material:material-icons-core", version="1.7.8" }
9495
androidx-compose-material-icons-extended = { module = "androidx.compose.material:material-icons-extended", version="1.7.8" }
9596
androidx-compose-ui = { module = "androidx.compose.ui:ui", version.ref = "androidxCompose" }

‎sentry-android-navigation3/api/sentry-android-navigation3.api‎

Whitespace-only changes.

‎sentry-android-navigation3/build.gradle.kts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ android {
2222
getByName("release") { consumerProguardFiles("proguard-rules.pro") }
2323
}
2424

25+
// AGP 9 only generates unit tests for the testBuildType. The debug variant is
26+
// disabled, so unit tests must target release to run at all.
27+
testBuildType = "release"
28+
2529
kotlin {
2630
compilerOptions.jvmTarget = JVM_1_8
2731
compilerOptions.languageVersion = KotlinVersion.KOTLIN_1_9
@@ -43,6 +47,18 @@ android {
4347

4448
kotlin { explicitApi() }
4549

50+
dependencies {
51+
implementation(projects.sentry)
52+
53+
compileOnly(libs.androidx.compose.runtime)
54+
55+
testImplementation(libs.androidx.compose.runtime)
56+
testImplementation(libs.google.truth)
57+
testImplementation(libs.kotlin.test.junit)
58+
testImplementation(libs.mockito.inline)
59+
testImplementation(libs.mockito.kotlin)
60+
}
61+
4662
tasks.withType<Detekt>().configureEach {
4763
// Target version of the generated JVM bytecode. It is used for type resolution.
4864
jvmTarget = JavaVersion.VERSION_1_8.toString()
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package io.sentry.compose.navigation3
2+
3+
import androidx.compose.runtime.snapshots.Snapshot
4+
5+
/**
6+
* Holds host app-defined extractors, which convert a back stack entry of type [T] into a route name
7+
* and a map of zero or more route arguments. Extracted values are eventually grouped into
8+
* [RouteEntry]s for display.
9+
*
10+
* Extractor invocations are hidden from Compose snapshot observation so they don't impact
11+
* invalidation of the recompose scope that reads them.
12+
*/
13+
internal class RouteResolvers<T : Any>(
14+
val nameExtractor: ((T) -> String)?,
15+
val argumentsExtractor: ((T) -> Map<String, Any?>)?,
16+
) {
17+
18+
fun getName(backStackEntry: T): String? = Snapshot.withoutReadObservation {
19+
nameExtractor?.invoke(backStackEntry)
20+
}
21+
22+
fun getArguments(backStackEntry: T): Map<String, Any?>? = Snapshot.withoutReadObservation {
23+
argumentsExtractor?.invoke(backStackEntry)
24+
}
25+
}
Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
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

Comments
 (0)