Skip to content

Commit f69512e

Browse files
authored
fix(android): Part 3 of Nav3 support for multi-Activity and multi-Fragment apps (JAVA-785, JAVA-823) (#6480)
This commit constitutes part 3 of our Nav3 support for multi-Activity and multi-Fragment apps. In part 1 (#6301) we provided the basic mechanism for coordinating multiple SentryNavEffects; and in part 2 (#6398) we adapted our approach to the quirks of ViewPager2 and other oddball Fragment lifecycles. Both of those commits assumed that any Activities or Fragments that had a SentryNavEffect would only launch other Activities or Fragments that also had SentryNavEffects. This commit handles three remaining (and important) corner cases: 1. Ensuring spans don't get lost when the user returns to an Activity or Fragment they already visited. (We now start a new nav transaction when the user returns if the previous transaction finished in the meantime.) 2. Ensuring Activities or Fragments with SentryNavEffects play nicely with Activities or Fragments without them. (We no longer keep stale nav data in the shared IScope.) 3. Ensuring Activities' ui.load transactions interoperate well with Nav3 transactions. (Nav3 transactions now consistently defer to ui.load transactions, like we do for Nav2.) See the PR description of #6480 for more details.
1 parent 2e298a3 commit f69512e

31 files changed

Lines changed: 4162 additions & 1377 deletions

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,14 @@
1515

1616
- Most SDK log calls no longer allocate when `debug` is off ([#6600](https://github.com/getsentry/sentry-java/pull/6600))
1717

18+
### Behavioral Changes
19+
20+
- Nav3: Returning to an Activity or Fragment with its own `SentryNavEffect` within the app (e.g., closing the Activity that covered it, swiping back to its ViewPager2 page, or dismissing a dialog over it) now starts a new navigation transaction for the current destination if the previous one finished, so spans produced upon return can now be consistently captured ([#6482](https://github.com/getsentry/sentry-java/pull/6482))
21+
- Nav3: `ui.load` transactions are bound to `IScope` in preference to Nav3 transactions when transitioning between Activities, matching Nav2 behavior (API 29+) ([#6484](https://github.com/getsentry/sentry-java/pull/6484))
22+
1823
### Fixes
1924

25+
- Nav3: Stop attributing errors and spans from an Activity or ViewPager2 page without a `SentryNavEffect` to the most recently visited Nav3 root ([#6483](https://github.com/getsentry/sentry-java/pull/6483))
2026
- Android: Count deep sleep in breadcrumb, screenshot and view hierarchy debounce windows, so the first low-memory or battery breadcrumb after a long Doze is no longer dropped ([#6590](https://github.com/getsentry/sentry-java/pull/6590))
2127

2228
## 8.64.0

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ android {
4747
warningsAsErrors = true
4848
checkDependencies = true
4949

50+
// Lifecycle 2.8.3's lint checks are incompatible with AGP 9.5. Lifecycle 2.10.0 fixes them,
51+
// but raises minSdk to 23 while this SDK still supports 21.
52+
disable += "ObsoleteLintCustomCheck"
53+
5054
// We run a full lint analysis as build part in CI, so skip vital checks for assemble tasks.
5155
checkReleaseBuilds = false
5256
}
@@ -68,7 +72,10 @@ dependencies {
6872
implementation(libs.androidx.lifecycle.runtime.compose)
6973

7074
compileOnly(libs.androidx.compose.runtime)
75+
compileOnly(libs.androidx.compose.ui)
7176

77+
testImplementation(projects.sentryAndroidCore)
78+
testImplementation(projects.sentryTestSupport)
7279
testImplementation(libs.androidx.compose.ui.test.junit4)
7380
testImplementation(libs.androidx.fragment.ktx)
7481
testImplementation(libs.androidx.test.core)

‎sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt‎

Lines changed: 44 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,18 @@ import io.sentry.Hint
55
import io.sentry.SentryIntegrationPackageStorage
66
import io.sentry.SentryLevel.INFO
77
import io.sentry.SentryOptions
8-
import io.sentry.TransactionContext
9-
import io.sentry.TransactionOptions
108
import io.sentry.compose.navigation3.BackStackConverter.RetentionPolicy
119
import io.sentry.compose.navigation3.PreparedChange.BackStackHasNewTop
1210
import io.sentry.compose.navigation3.PreparedChange.BackStackHasSameTop
1311
import io.sentry.compose.navigation3.PreparedChange.BackStackIsEmpty
1412
import io.sentry.compose.navigation3.lifecycle.INavScope
1513
import io.sentry.compose.navigation3.lifecycle.INavScopes
16-
import io.sentry.compose.navigation3.lifecycle.INavTransaction
1714
import io.sentry.compose.navigation3.lifecycle.NAVIGATION_CONTEXT_KEY
18-
import io.sentry.protocol.App
19-
import io.sentry.protocol.TransactionNameSource
15+
import io.sentry.compose.navigation3.lifecycle.NAVIGATION_OP
16+
import io.sentry.compose.navigation3.lifecycle.NavTransactionRequest
2017
import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion
2118
import java.lang.ref.WeakReference
2219

23-
private const val NAVIGATION_OP: String = "navigation"
24-
2520
/**
2621
* Observes the back stack managed by a single [SentryNavEffect] and records Sentry state as the
2722
* back stack is updated.
@@ -33,8 +28,8 @@ private const val NAVIGATION_OP: String = "navigation"
3328
*
3429
* **Entry identity determines whether the top has changed**
3530
*
36-
* Referential equality (===), not structural equality, is used to determine whether the top of the
37-
* incoming back stack has changed. That approach:
31+
* Referential equality (===) is used to determine whether the top of the incoming back stack has
32+
* changed. That approach:
3833
*
3934
* - matches the typical Nav3 SnapshotStateList, where an entry instance has a stable identity for
4035
* its lifetime in the stack;
@@ -57,10 +52,9 @@ internal class BackStackObserver<T : Any>(
5752

5853
private val backStackConverter = BackStackConverter(entryMapper, scopes.options.logger)
5954

60-
private val navTransactions = NavTransactions(scopes)
6155
private val navBreadcrumbs = NavBreadcrumbs(scopes)
6256
private val navScreen = NavScreen()
63-
private val navContext = NavContext(scopes, options)
57+
private val navContext = NavContext(options)
6458

6559
// Safe because the host back stack retains the current top entry strongly between updates.
6660
private var previousTop: WeakReference<T>? = null
@@ -192,44 +186,57 @@ internal class BackStackObserver<T : Any>(
192186
navBreadcrumbs.emit(fromEntry = previousTop, toEntry = currentBackStack.topEntryNormalized)
193187
}
194188

195-
navTransactions.stop(scope)
189+
scope.finishNavTransaction()
196190

197191
if (areNavigationTransactionsEnabled) {
198-
navTransactions
199-
.start(
200-
scope,
201-
currentTop.name,
202-
currentTop.argumentsWithMetadata(),
203-
)
204-
?.let { transaction -> navContext.updateTransaction(transaction, scope, currentBackStack) }
192+
scope.startNavTransaction(navTransactionRequestFor(currentBackStack))
205193
} else {
206194
scope.rotatePropagationContext()
207195
}
208196

209-
storeAsPreviousTop(currentBackStack.topEntry, currentBackStack.topEntryNormalized)
197+
storePreviousTop(currentBackStack)
210198
}
211199

212200
private fun handleSameTop(scope: INavScope, backStack: BackStackData<T>) {
213201
navContext.update(scope, backStack.capturedEntriesNormalized)
214-
storeAsPreviousTop(backStack.topEntry, backStack.topEntryNormalized)
202+
203+
// Keeps the nav context of transactions started later for the same destination (e.g., when the
204+
// user returns to the nav root) in step with the back stack.
205+
if (areNavigationTransactionsEnabled) {
206+
scope.updateNavTransactionRequest(navTransactionRequestFor(backStack))
207+
}
208+
209+
storePreviousTop(backStack)
215210
}
216211

217212
private fun handleEmptyBackStack(scope: INavScope) {
218213
tearDown(scope)
219214
}
220215

221-
private fun storeAsPreviousTop(topEntry: T, topEntryNormalized: NormalizedSentryBackStackEntry) {
222-
previousTop = WeakReference(topEntry)
223-
previousTopNormalized = topEntryNormalized
216+
private fun storePreviousTop(backStack: BackStackData<T>) {
217+
previousTop = WeakReference(backStack.topEntry)
218+
previousTopNormalized = backStack.topEntryNormalized
224219
}
225220

226221
private fun clearPreviousTop() {
227222
previousTop = null
228223
previousTopNormalized = null
229224
}
230225

226+
private fun navTransactionRequestFor(backStack: BackStackData<T>): NavTransactionRequest {
227+
val top = backStack.topEntryNormalized
228+
229+
return NavTransactionRequest.forDestination(
230+
name = top.name,
231+
arguments = top.argumentsWithMetadata(),
232+
contexts = navContext.forTransaction(backStack.capturedEntriesNormalized),
233+
viewNames = if (scopes.options.isEnableScreenTracking) listOf(top.name) else null,
234+
options = scopes.options,
235+
)
236+
}
237+
231238
private fun tearDown(scope: INavScope) {
232-
navTransactions.stop(scope)
239+
scope.finishNavTransaction()
233240
navContext.clear(scope)
234241
navScreen.clear(scope)
235242
clearPreviousTop()
@@ -274,58 +281,8 @@ private data class BackStackData<T>(
274281
val capturedEntriesNormalized: List<NormalizedSentryBackStackEntry>,
275282
)
276283

277-
/** A helper class for managing nav transactions. */
278-
private class NavTransactions(private val scopes: INavScopes) {
279-
280-
private companion object {
281-
private const val TRANSACTION_ORIGIN = "auto.navigation.nav3"
282-
}
283-
284-
/**
285-
* Starts an idle navigation transaction, or no-ops if another transaction is already active.
286-
*
287-
* [Stop][stop] the current navigation transaction first. See [INavScope.startNavTransaction].
288-
*/
289-
fun start(
290-
scope: INavScope,
291-
name: String,
292-
arguments: Map<String, Any?>,
293-
): INavTransaction? {
294-
val transactionOptions =
295-
TransactionOptions().also {
296-
it.isWaitForChildren = true
297-
it.idleTimeout = scopes.options.idleTimeout
298-
val deadlineTimeoutMillis = scopes.options.deadlineTimeout
299-
it.deadlineTimeout = if (deadlineTimeoutMillis <= 0) null else deadlineTimeoutMillis
300-
it.isTrimEnd = true
301-
it.origin = TRANSACTION_ORIGIN
302-
}
303-
304-
val transaction =
305-
scope.startNavTransaction(
306-
TransactionContext(name, TransactionNameSource.ROUTE, NAVIGATION_OP),
307-
transactionOptions,
308-
) ?: return null
309-
310-
if (arguments.isNotEmpty()) {
311-
transaction.setData("arguments", arguments)
312-
}
313-
314-
return transaction
315-
}
316-
317-
/**
318-
* Finishes and unsets the active navigation transaction, if one exists.
319-
*
320-
* See [INavScope.finishNavTransaction].
321-
*/
322-
fun stop(scope: INavScope) {
323-
scope.finishNavTransaction()
324-
}
325-
}
326-
327284
/** A helper class for updating [nav context][NAVIGATION_CONTEXT_KEY]. */
328-
private class NavContext(private val scopes: INavScopes, private val options: SentryNavOptions) {
285+
private class NavContext(private val options: SentryNavOptions) {
329286

330287
private companion object {
331288
private const val BACKSTACK_KEY = "Back Stack"
@@ -345,33 +302,21 @@ private class NavContext(private val scopes: INavScopes, private val options: Se
345302
}
346303

347304
/**
348-
* Updates the transaction with the provided navigation info.
305+
* The nav context to set on the nav transaction for a destination whose back stack is
306+
* [capturedEntries], if any.
349307
*
350308
* Needed because transactions inherit base scope context on a per-key basis unless transactions
351-
* have their own values for those keys. In our case, we need to keep fresh back stack and route
352-
* values in the base context for purposes of crash reporting. But those values will often advance
353-
* past what's relevant to a given transaction. This method prevents misassociation by binding
354-
* proper values to the transaction context instead.
309+
* have their own values for those keys. In our case, we need to keep fresh back stack values in
310+
* the base context for purposes of crash reporting. But those values will often advance past
311+
* what's relevant to a given transaction. Setting the destination's own back stack on its
312+
* transaction prevents misassociation.
355313
*/
356-
fun <T : Any> updateTransaction(
357-
transaction: INavTransaction,
358-
scope: INavScope,
359-
backStack: BackStackData<T>,
360-
) {
361-
if (scopes.options.isEnableScreenTracking) {
362-
val appContext = scope.app ?: App()
363-
364-
appContext.viewNames = listOf(backStack.topEntryNormalized.name)
365-
transaction.setApp(appContext)
366-
}
367-
368-
if (options.captureBackStack && backStack.capturedEntriesNormalized.isNotEmpty()) {
369-
transaction.setContext(
370-
NAVIGATION_CONTEXT_KEY,
371-
backStack.capturedEntriesNormalized.toBackStackMap(),
372-
)
314+
fun forTransaction(capturedEntries: List<NormalizedSentryBackStackEntry>): Map<String, Any> =
315+
if (options.captureBackStack && capturedEntries.isNotEmpty()) {
316+
mapOf(NAVIGATION_CONTEXT_KEY to capturedEntries.toBackStackMap())
317+
} else {
318+
emptyMap()
373319
}
374-
}
375320

376321
/** Builds the `{"backstack": [...]}` map bound under [NAVIGATION_CONTEXT_KEY]. */
377322
private fun List<NormalizedSentryBackStackEntry>.toBackStackMap(): Map<String, Any?> =

‎sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserver.kt‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
package io.sentry.compose.navigation3
22

3-
import androidx.lifecycle.Lifecycle
43
import androidx.lifecycle.LifecycleEventObserver
54
import io.sentry.IScope
65
import io.sentry.IScopes
76
import io.sentry.compose.navigation3.lifecycle.NavLeaseCoordinator
7+
import io.sentry.compose.navigation3.lifecycle.NavRootInfo
88
import io.sentry.compose.navigation3.lifecycle.NavScopes
99

1010
/**
11-
* A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with other
12-
* `BackStackObserver`s.
11+
* A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with those of
12+
* other `BackStackObserver`s.
1313
*
1414
* Coordination is achieved via [NavScopes].
1515
*
@@ -35,8 +35,8 @@ internal class CoordinatedBackStackObserver<T : Any>(
3535
private val navScopes = NavScopes(scopes, coordinator)
3636
private val observer = BackStackObserver(navScopes, options, entryMapper)
3737

38-
fun attach(lifecycle: Lifecycle) {
39-
navScopes.attach(lifecycle)
38+
fun attach(rootInfo: NavRootInfo) {
39+
navScopes.attach(rootInfo)
4040
}
4141

4242
fun onBackStackChanged(backStack: List<T>) {
@@ -52,5 +52,24 @@ internal class CoordinatedBackStackObserver<T : Any>(
5252
}
5353
}
5454

55-
/** The [NavLeaseCoordinator] shared by default by all [SentryNavEffect]s. */
55+
/**
56+
* The [NavLeaseCoordinator] shared by default by all [CoordinatedBackStackObserver]s.
57+
*
58+
* **Lifetime**
59+
*
60+
* The default coordinator lives as long as the process, since lease state follows nav root
61+
* lifecycles rather than the SDK's. Closing and re-initializing the SDK doesn't require a reset
62+
* because:
63+
*
64+
* - `SentryNavEffect` resolves the current scopes on every call;
65+
*
66+
* - while the SDK is closed, bookkeeping continues without a scope; and
67+
*
68+
* - unpublishing compares by reference, so values published to an earlier scope don't affect the
69+
* current one.
70+
*
71+
* Limitation: A nav transaction that's still running when the SDK is closed and re-initialized can
72+
* be bound to the new scope the next time it's published, although its client has been closed.
73+
* Spans then attach to it, and are lost, until it times out or the next navigation finishes it.
74+
*/
5675
internal val defaultNavLeaseCoordinator: NavLeaseCoordinator = NavLeaseCoordinator()

‎sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,19 @@ import androidx.compose.runtime.Composable
44
import androidx.compose.runtime.DisposableEffect
55
import androidx.compose.runtime.remember
66
import androidx.compose.runtime.rememberUpdatedState
7+
import androidx.compose.ui.platform.LocalContext
78
import androidx.lifecycle.compose.LocalLifecycleOwner
89
import io.sentry.IScopes
910
import io.sentry.ScopesAdapter
1011
import io.sentry.SentryOptions
1112
import io.sentry.compose.navigation3.lifecycle.NavLeaseCoordinator
13+
import io.sentry.compose.navigation3.lifecycle.NavRootInfo
14+
import io.sentry.compose.navigation3.lifecycle.findActivity
1215
import org.jetbrains.annotations.ApiStatus
1316

1417
/**
15-
* An effect for generating Sentry data from your Nav3 backstack. Configure it via [options] and
16-
* call it before you invoke your `NavDisplay`.
17-
*
18+
* A composable effect for generating Sentry data from your Nav3 backstack. Configure it via
19+
* [options] and call it before you invoke your `NavDisplay`:
1820
* ```kotlin
1921
* @Composable
2022
* fun AppNavigation() {
@@ -24,7 +26,7 @@ import org.jetbrains.annotations.ApiStatus
2426
* // Place SentryNavEffect in the same composable as your NavDisplay and call
2527
* // the effect first. Doing so ensures the effect's lifecycle matches your
2628
* // NavDisplay, and that any Sentry data produced by your initial nav
27-
* // destination get attributed to the appropriate nav transaction.
29+
* // destination are attributed to the appropriate nav transaction.
2830
* SentryNavEffect(
2931
* backStack = navBackStack,
3032
* backStackEntryMapper = { entry ->
@@ -105,6 +107,7 @@ internal fun <T : Any> SentryNavEffect(
105107
) {
106108
val currentBackStackEntryMapper = rememberUpdatedState(backStackEntryMapper)
107109
val lifecycle = LocalLifecycleOwner.current.lifecycle
110+
val context = LocalContext.current
108111

109112
val observer =
110113
remember(scopes, options, lifecycle, coordinator) {
@@ -116,9 +119,13 @@ internal fun <T : Any> SentryNavEffect(
116119
)
117120
}
118121

119-
// Register first so the initial prepared back stack update can acquire navigation ownership.
122+
// Intentionally don't key on context. It's only used to find the Activity that displays the nav
123+
// root, which can't change without the lifecycle changing too, and that replaces the observer.
124+
// The context's identity can change more often (e.g., if the host app provides a new
125+
// ContextThemeWrapper on every recomposition), and re-attaching for those changes would
126+
// needlessly finish the nav transaction.
120127
DisposableEffect(observer) {
121-
observer.attach(lifecycle)
128+
observer.attach(NavRootInfo(lifecycle, context.findActivity()))
122129
onDispose { observer.dispose() }
123130
}
124131

0 commit comments

Comments
 (0)