diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 2d57e1b73dc..cd221d98d6b 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -9,6 +9,9 @@ updates: - package-ecosystem: "gradle" # The separate sample and test builds read this build's version catalog, so one directory # covers them. Listing them too opens one PR per directory for the same bump. + # + # Also bumps the -stable versions in gradle/dependency-matrix.versions.toml. Don't add + # ignore rules for those modules (see the rules at the top of that file). directory: "/" registries: - gradle-plugin-portal diff --git a/.github/workflows/integration-tests-nav3-r8.yml b/.github/workflows/integration-tests-nav3-r8.yml new file mode 100644 index 00000000000..92bb74a188c --- /dev/null +++ b/.github/workflows/integration-tests-nav3-r8.yml @@ -0,0 +1,200 @@ +name: Nav3 BackStackEntryMapper R8 Check + +# Verifies behavior of BackStackEntryMapper.SerialName from sentry-android-navigation3 in +# R8-minified builds on an emulator (R8 full mode with the +# compile floor, the latest stable release, and any newer release candidate of +# kotlinx.serialization, from gradle/dependency-matrix.versions.toml, and R8 compat mode with the +# floor). Also runs all of the module's unit tests against the newer versions. See sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/README.md. +# +# Release candidate failures are warnings, except on PRs that change kotlinxSerialization-preview, +# such as the weekly updater's. + +# Runs on every PR and every push to main, without paths filters: the relevance job decides +# whether the check runs, using scripts/nav3-r8-check-relevant.sh as the only list of relevant +# changes. +on: + push: + branches: + - main + pull_request: + +permissions: + contents: read + +# A new push only cancels a superseded PR run. On main, a run that started finishes, as the API 23 +# job only runs there and would otherwise rarely complete; a newer push waits for it instead. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + APK_DIR: "nav3-r8-check-apks" + APK_ARTIFACT_NAME: "nav3-r8-check-apks" + +jobs: + # Decides whether the changes affect the check, with scripts/nav3-r8-check-relevant.sh. The + # other jobs are skipped (and report as skipped) if they don't, e.g., for PRs that don't touch + # Nav3 or that only bump unrelated versions in gradle/libs.versions.toml. + # + # Also decides whether release candidate failures fail the check (but only on PRs that change + # kotlinxSerialization-preview). + relevance: + name: Check relevance + runs-on: ubuntu-latest + outputs: + relevant: ${{ steps.check.outputs.relevant }} + preview-required: ${{ steps.check.outputs.preview-required }} + + steps: + # A PR's checkout is a merge commit, whose first parent is the base branch, and a push to + # main is usually one squashed commit, so two commits are usually enough to diff the changes. + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + + - name: Check whether the changes affect the check + id: check + env: + PUSH_BEFORE: ${{ github.event.before }} + run: | + previewRequired=false + if [[ "$GITHUB_EVENT_NAME" == "pull_request" ]]; then + relevant="$(./scripts/nav3-r8-check-relevant.sh HEAD^1 HEAD)" + if ./scripts/dependency-matrix.sh changed-roles HEAD^1 HEAD kotlinxSerialization | grep -qx preview; then + previewRequired=true + fi + else + # A push may contain several commits, so diff against the commit main pointed to before + # it. If that commit can't be fetched (e.g., after a force push), run the check. + if [[ -n "$PUSH_BEFORE" && ! "$PUSH_BEFORE" =~ ^0+$ ]] \ + && { git cat-file -e "${PUSH_BEFORE}^{commit}" 2> /dev/null \ + || git fetch --depth=1 origin "$PUSH_BEFORE"; }; then + relevant="$(./scripts/nav3-r8-check-relevant.sh --any-catalog-change "$PUSH_BEFORE" HEAD)" + else + relevant=true + fi + fi + if [[ "$previewRequired" == "true" ]] \ + && ! ./scripts/dependency-matrix.sh extra-versions kotlinxSerialization | grep -q '^preview '; then + echo "::notice::kotlinxSerialization-preview changed, but isn't newer than kotlinxSerialization-stable, so no release candidate is tested." + fi + echo "relevant=$relevant" >> "$GITHUB_OUTPUT" + echo "preview-required=$previewRequired" >> "$GITHUB_OUTPUT" + echo "Nav3 R8 check relevant: $relevant" + echo "kotlinx.serialization release candidate required: $previewRequired" + + # Runs separately from the APK builds, so a unit test failure doesn't hide the R8 check's results. + unit-tests: + name: Unit tests + needs: relevance + if: needs.relevance.outputs.relevant == 'true' + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '21' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + + # Apps may ship a newer kotlinx.serialization than sentry-android-navigation3 compiles + # against. The Build workflow runs the unit tests against the floor. + - name: Run unit tests against newer kotlinx.serialization versions + env: + NAV3_PREVIEW_REQUIRED: ${{ needs.relevance.outputs.preview-required }} + run: ./scripts/test-nav3-kotlinx-versions.sh + + build: + name: Build + needs: relevance + if: needs.relevance.outputs.relevant == 'true' + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '21' + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + + - name: Build APKs + env: + NAV3_PREVIEW_REQUIRED: ${{ needs.relevance.outputs.preview-required }} + run: ./scripts/test-nav3-backstack-entry-mapper-r8.sh build "${{ env.APK_DIR }}" + + - name: Upload APK artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: ${{ env.APK_ARTIFACT_NAME }} + path: ${{ env.APK_DIR }} + retention-days: 1 + + run: + name: Run on API Level ${{ matrix.api-level }} + needs: [relevance, build] + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # Tests against API 37.0 on every run. Also tests against API 23 (Nav3's minSdkVersion) when changes reach main. + # The latter lets us catch issues present on the oldest Nav3 app runtime without slowing down PRs. + api-level: ${{ fromJSON(github.event_name == 'push' && '[23, "37.0"]' || '["37.0"]') }} + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Enable KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - name: Download APK artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: ${{ env.APK_ARTIFACT_NAME }} + path: ${{ env.APK_DIR }} + + # The runner ships an outdated avdmanager that writes target=android-0 into the + # AVD config for minor-versioned packages (android-37.x), so the emulator clamps + # to API 3 and boots misconfigured. Update cmdline-tools so avdmanager parses it. + # See https://github.com/ReactiveCircus/android-emulator-runner/issues/482 + - name: Update SDK cmdline-tools + if: matrix.api-level == '37.0' + run: | + SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-/usr/local/lib/android/sdk}}" + yes | "$SDK/cmdline-tools/latest/bin/sdkmanager" --install "cmdline-tools;latest" > /dev/null + # sdkmanager won't overwrite the preinstalled dir, so it installs to latest-2. + if [ -d "$SDK/cmdline-tools/latest-2" ]; then + rm -rf "$SDK/cmdline-tools/latest" + mv "$SDK/cmdline-tools/latest-2" "$SDK/cmdline-tools/latest" + fi + + - name: Run check + uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # pin@v2.38.0 + env: + NAV3_PREVIEW_REQUIRED: ${{ needs.relevance.outputs.preview-required }} + with: + api-level: ${{ matrix.api-level }} + # API 37 has no plain google_apis image. + target: ${{ matrix.api-level == 23 && 'google_apis' || 'google_apis_ps16k' }} + # Use canary for API 37, matching the critical UI tests. + channel: ${{ matrix.api-level == 23 && 'stable' || 'canary' }} + arch: x86_64 + disable-animations: true + disable-spellchecker: true + emulator-options: -memory 4096 -no-window -gpu auto -noaudio -no-boot-anim -camera-back none -no-snapshot-save + script: ./scripts/test-nav3-backstack-entry-mapper-r8.sh run "${{ env.APK_DIR }}" diff --git a/.github/workflows/update-deps.yml b/.github/workflows/update-deps.yml index f4a5a5d7d5c..0fc80751564 100644 --- a/.github/workflows/update-deps.yml +++ b/.github/workflows/update-deps.yml @@ -1,10 +1,13 @@ name: Update Dependencies on: - # Run every day. schedule: + # Run every day. - cron: '0 3 * * *' - # And on on every PR merge so we get the updated dependencies ASAP, and to make sure the changelog doesn't conflict. + # Run weekly (select btw daily or weekly via `if:`). + - cron: '0 4 * * 1' + # Also trigger on pushes to main (individual jobs decide whether to run). E.g., lets us get updated + # dependencies ASAP and make sure the changelog doesn't conflict. push: branches: - main @@ -15,7 +18,9 @@ permissions: actions: write jobs: + # Update the Sentry Native SDK dependency daily and on pushes to main. native: + if: github.event.schedule != '0 4 * * 1' runs-on: ubuntu-latest steps: - uses: getsentry/github-workflows/updater@36529d71129a14967bea1fb81bcaf2a5943cf877 # v3 @@ -23,3 +28,19 @@ jobs: path: scripts/update-sentry-native-ndk.sh name: Native SDK ssh-key: ${{ secrets.CI_DEPLOY_KEY }} + + # Update weekly the kotlinx-serialization-core release candidate used by the Nav3 R8 check and + # unit tests. (Dependabot separately bumps the latest stable / non-preview release.) + nav3-kotlinx-serialization-preview: + if: github.event.schedule == '0 4 * * 1' + runs-on: ubuntu-latest + steps: + - uses: getsentry/github-workflows/updater@36529d71129a14967bea1fb81bcaf2a5943cf877 # v3 + with: + path: scripts/update-kotlinx-serialization-preview.sh + name: Nav3 kotlinx.serialization RC check + # Release candidates only. kotlinx.serialization publishes no alpha or beta releases. + pattern: '^v?(?[0-9.]+-RC[0-9]*)$' + # Only the Nav3 tests use this version; the SDK's dependency doesn't change. + changelog-entry: false + ssh-key: ${{ secrets.CI_DEPLOY_KEY }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 482f613041b..f3ee88ea787 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ ## Unreleased +### Features + +- Nav3: Add `BackStackEntryMapper.SerialName`, a convenience mapper that names back stack entries after their kotlinx.serialization serial names ([#6703](https://github.com/getsentry/sentry-java/pull/6703)) +- Nav3: Record why a back stack entry is `/unknown`, as `unknown_entry_reason` next to it in the back stack record and navigation transactions, and as `to_unknown_entry_reason` and `from_unknown_entry_reason` on breadcrumbs (e.g., `not_serializable` or `serializer_not_found` for the built-in mappers, `unmapped` if a custom mapper returns `null`) ([#6781](https://github.com/getsentry/sentry-java/pull/6781)) + - A mapper that throws now records `"unknown_entry_reason": "mapping_failed"` instead of `"dropped_by_sentry": "mapping_failed"` in the entry's arguments + ### Fixes - Session Replay: Mask Compose images loaded with Coil 3.1+ `AsyncImage` when `maskAllImages` is enabled ([#6759](https://github.com/getsentry/sentry-java/pull/6759)) @@ -17,6 +23,7 @@ ### Dependencies +- Nav3: `sentry-android-navigation3` now depends on `kotlinx-serialization-core` 1.7.3 or later, the version every Nav3 release already depends on, so it never raises a Nav3 app's version ([#6703](https://github.com/getsentry/sentry-java/pull/6703)) - Nav3: `sentry-android-navigation3` no longer declares a dependency on `androidx.lifecycle:lifecycle-runtime-compose`. Nav3 apps already depend on it via `navigation3-ui`, so no app changes are necessary ([#6699](https://github.com/getsentry/sentry-java/pull/6699)) ## 8.65.1 diff --git a/Makefile b/Makefile index 7a0016c261b..fdd4b42f3a3 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all clean compile javadocs dryRelease update format checkFormat api assembleUiTestRelease assembleUiTestCriticalRelease runUiTestCritical check preMerge publish +.PHONY: all clean compile javadocs dryRelease update format checkFormat api assembleUiTestRelease assembleUiTestCriticalRelease runUiTestCritical runNav3BackStackEntryMapperR8Test check preMerge publish all: stop clean javadocs compile assembleUiTests: assembleUiTestRelease @@ -52,6 +52,10 @@ assembleUiTestCriticalRelease: runUiTestCritical: ./scripts/test-ui-critical.sh +# Build and run the R8 check for BackStackEntryMapper.SerialName on a booted emulator +runNav3BackStackEntryMapperR8Test: + ./scripts/test-nav3-backstack-entry-mapper-r8.sh + # Run tests and lint check: ./gradlew check diff --git a/gradle/dependency-matrix.versions.toml b/gradle/dependency-matrix.versions.toml new file mode 100644 index 00000000000..f02ae1c864c --- /dev/null +++ b/gradle/dependency-matrix.versions.toml @@ -0,0 +1,42 @@ +# Dependency test matrices, registered as the `matrixLibs` catalog: compile against the oldest +# supported version and test against newer releases too. +# +# Kept apart from libs.versions.toml so that each matrix's tests can run on PRs that change its +# versions, without also running on every unrelated dependency bump. +# +# Each matrix has up to three version keys, named by role: +# +# - -floor: the oldest version we support, which we compile and test against. Only changed +# by hand, in a reviewed change. No library entry references it, so Dependabot never bumps it. +# Builds apply it explicitly (e.g., `version { strictly(...) }`) instead. +# - -stable: the latest stable release. Bumped by Dependabot through the -stableTracker +# library entry, which references it and is used by no build. +# - -preview: the latest pre-release, which is tested only while it's newer than +# -stable. Bumped by a weekly updater job in .github/workflows/update-deps.yml. No library +# entry references it, so Dependabot never bumps it. +# +# Rules for adding a matrix: +# +# - Never give the floor or preview keys a library entry with `version.ref`, and never protect them +# with a Dependabot `ignore` rule: ignore rules match a dependency's group and name, so they would +# also stop Dependabot from bumping -stable. +# - A stableTracker entry mustn't share its module with any entry or build file declaration that +# Dependabot also updates (e.g., in libs.versions.toml). Dependabot merges declarations of one +# module and bumps them all to one version. If they would collide, track a sibling artifact +# instead (e.g., `-jvm`). +# +# scripts/dependency-matrix.sh reads and writes these keys for CI and the updater jobs. + +[versions] +# The oldest kotlinx.serialization version sentry-android-navigation3 supports, which it compiles and +# tests against. Before changing it, read the rules under "Version floor" in +# sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md. +kotlinxSerialization-floor = "1.7.3" +kotlinxSerialization-stable = "1.13.0" +# kotlinx.serialization publishes release candidates (-RC), but no alpha or beta releases. +kotlinxSerialization-preview = "1.12.0-RC" + +[libraries] +# Applied with the floor version by the builds that use it. +kotlinxSerialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core" } +kotlinxSerialization-stableTracker = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinxSerialization-stable" } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e7ab038d9d6..40a24fab5c7 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -70,6 +70,7 @@ kotlin-spring = { id = "org.jetbrains.kotlin.plugin.spring", version.ref = "kotl kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } buildconfig = { id = "com.github.gmazzo.buildconfig", version = "5.6.5" } dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } diff --git a/scripts/dependency-matrix.sh b/scripts/dependency-matrix.sh new file mode 100755 index 00000000000..6ff4f1ce1fa --- /dev/null +++ b/scripts/dependency-matrix.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Reads and writes the role keys in gradle/dependency-matrix.versions.toml (-floor, +# -stable, and -preview; see that file's header) for CI jobs and updater scripts. +# +# Usage: +# dependency-matrix.sh get MATRIX ROLE +# Prints the version of MATRIX's ROLE. +# dependency-matrix.sh set MATRIX ROLE VERSION +# Sets the version of MATRIX's ROLE. +# dependency-matrix.sh extra-versions MATRIX +# Prints the versions to test besides the floor, one "ROLE VERSION" line each: the stable +# version, then the preview version if it's newer than the stable one. +# dependency-matrix.sh changed-roles BASE HEAD MATRIX +# Prints the roles of MATRIX whose versions changed between commits BASE and HEAD. +set -euo pipefail + +cd "$(dirname "$0")/../" +catalog="gradle/dependency-matrix.versions.toml" + +usage() { + sed -n '5,14p' "$0" | sed 's/^# \{0,1\}//' + exit 1 +} + +key() { + echo "${1:?Missing MATRIX}-${2:?Missing ROLE}" +} + +get() { + local key version + key="$(key "$@")" + version="$(KEY="$key" perl -ne 'print "$1\n" if m/^\Q$ENV{KEY}\E\s*=\s*"([^"]+)"/' "$catalog")" + if [[ -z "$version" ]]; then + echo "No version for $key in $catalog" >&2 + exit 1 + fi + echo "$version" +} + +set_version() { + local key + key="$(key "$1" "$2")" + local version="${3:?Missing VERSION}" + get "$1" "$2" > /dev/null + KEY="$key" VERSION="$version" perl -pi -e 's/^(\Q$ENV{KEY}\E\s*=\s*")[^"]+(")/${1}$ENV{VERSION}${2}/' "$catalog" +} + +# Whether pre-release version $1 is newer than stable version $2. A pre-release precedes the release +# of its base version (1.12.0-RC < 1.12.0), so only its base version is compared. Comparing the full +# versions with `sort -V` would rank 1.12.0-RC above 1.12.0. +is_newer_preview() { + local base="${1%%-*}" + [[ "$base" != "$2" && "$(printf '%s\n%s\n' "$base" "$2" | sort -V | tail -n 1)" == "$base" ]] +} + +extra_versions() { + local stable preview + stable="$(get "${1:?Missing MATRIX}" stable)" + preview="$(get "$1" preview)" + echo "stable $stable" + if is_newer_preview "$preview" "$stable"; then + echo "preview $preview" + fi +} + +changed_roles() { + local base="${1:?Missing BASE}" head="${2:?Missing HEAD}" matrix="${3:?Missing MATRIX}" + git diff --unified=0 "$base" "$head" -- "$catalog" \ + | MATRIX="$matrix" perl -ne 'print "$1\n" if m/^[-+]\Q$ENV{MATRIX}\E-(\w+)\s*=\s*"/' \ + | sort -u +} + +case "${1:-}" in + get) get "${2:-}" "${3:-}" ;; + set) set_version "${2:-}" "${3:-}" "${4:-}" ;; + extra-versions) extra_versions "${2:-}" ;; + changed-roles) changed_roles "${2:-}" "${3:-}" "${4:-}" ;; + *) usage ;; +esac diff --git a/scripts/nav3-r8-check-relevant.sh b/scripts/nav3-r8-check-relevant.sh new file mode 100755 index 00000000000..a6ae18c49e6 --- /dev/null +++ b/scripts/nav3-r8-check-relevant.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Prints "true" if the changes between two commits can affect the Nav3 R8 check +# (.github/workflows/integration-tests-nav3-r8.yml), and "false" otherwise. +# +# The workflow runs on every pull request and every push to main, and this script is the only +# place that decides which changes the check needs to run for. (The workflow deliberately has no +# paths filters, so there's no second list to keep in sync with RELEVANT_PATHS below.) +# +# A change is relevant if it touches any of RELEVANT_PATHS, or changes a relevant version in one of +# the two version catalogs: +# +# - gradle/libs.versions.toml: bumps of the toolchain and libraries the check depends on (Kotlin and +# its serialization plugin, AGP and its R8, Compose, lifecycle, savedstate, Nav3) can change how +# our mappers behave under R8. Most of that file's changes bump unrelated dependencies, though, +# so for those the check is skipped. +# - gradle/dependency-matrix.versions.toml: holds the kotlinx.serialization versions the check runs +# against, and may hold other matrices' versions. Only changes to lines that name the +# kotlinxSerialization matrix are relevant. +# +# With --any-catalog-change, any change to either catalog is relevant. Pushes to main use it, so a +# relevant version that matches none of the patterns below is still checked once it's merged. +# +# Usage: nav3-r8-check-relevant.sh [--any-catalog-change] BASE HEAD +set -euo pipefail + +anyCatalogChange=false +if [[ "${1:-}" == "--any-catalog-change" ]]; then + anyCatalogChange=true + shift +fi +base="${1:?Usage: $0 [--any-catalog-change] BASE HEAD}" +head="${2:?Usage: $0 [--any-catalog-change] BASE HEAD}" +versionCatalog="gradle/libs.versions.toml" +matrixCatalog="gradle/dependency-matrix.versions.toml" + +# Paths (extended regular expressions, matched against the whole path) whose changes are always +# relevant. +RELEVANT_PATHS=( + 'sentry-android-navigation3/.*' + 'sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/.*' + # The settings, build script, and properties of the build that produces the R8 check's APKs. + 'sentry-android-integration-tests/[^/]*\.(gradle\.kts|properties)' + 'scripts/(test-nav3-backstack-entry-mapper-r8|test-nav3-kotlinx-versions|update-kotlinx-serialization-preview|dependency-matrix|nav3-r8-check-relevant)\.sh' + # Build settings, R8 flags, build logic, the Gradle version, and the root build's settings + # (which register the version catalogs) and build script, which all builds of the check use. + 'gradle\.properties' + 'settings\.gradle\.kts' + 'build\.gradle\.kts' + 'gradle/wrapper/.*' + 'buildSrc/.*' + 'build-logic/.*' + # Utilities the mappers use to filter arguments and report integrations. + 'sentry/src/main/java/io/sentry/util/.*' + '\.github/workflows/integration-tests-nav3-r8\.yml' +) + +# Version keys of gradle/libs.versions.toml that the check depends on, including the SDK levels its +# apps are built with. +relevantKeys='kotlin|agp|androidxCompose|composeCompiler|androidxLifecycle|androidxNavigation3|compileSdk|compileSdkMinor|minSdk|targetSdk' +# Module and plugin coordinates the check depends on, which also catches entries that declare +# their versions inline instead of referencing one of the keys above. +relevantCoordinates='org\.jetbrains\.kotlin|com\.android\.|androidx\.compose|androidx\.lifecycle|androidx\.savedstate|androidx\.navigation3|kotlinx-serialization' + +changedFiles="$(git diff --name-only "$base" "$head")" + +pathPattern="^($(IFS='|'; echo "${RELEVANT_PATHS[*]}"))$" +if grep -q -E "$pathPattern" <<< "$changedFiles"; then + echo true + exit 0 +fi + +if [[ "$anyCatalogChange" == "true" ]] \ + && grep -q -x -F -e "$versionCatalog" -e "$matrixCatalog" <<< "$changedFiles"; then + echo true + exit 0 +fi + +# Prints the added and removed lines of catalog $1, without the diff's file headers. +changedLines() { + git diff --unified=0 "$base" "$head" -- "$1" | grep -E '^[-+]' | grep -v -E '^(\+\+\+|---) ' || true +} + +if grep -q -E "^[-+][[:space:]]*($relevantKeys)[[:space:]]*=|$relevantCoordinates" <<< "$(changedLines "$versionCatalog")" \ + || grep -q -F "kotlinxSerialization" <<< "$(changedLines "$matrixCatalog")"; then + echo true +else + echo false +fi diff --git a/scripts/test-nav3-backstack-entry-mapper-r8.sh b/scripts/test-nav3-backstack-entry-mapper-r8.sh new file mode 100755 index 00000000000..c27e422fb3e --- /dev/null +++ b/scripts/test-nav3-backstack-entry-mapper-r8.sh @@ -0,0 +1,190 @@ +#!/usr/bin/env bash +# Verifies the behavior of BackStackEntryMapper.SerialName in R8-minified builds on a booted +# emulator or device. See +# sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/README.md. +# +# The app is built against kotlinxSerialization-floor in gradle/dependency-matrix.versions.toml, +# plus kotlinxSerialization-stable and, if it's newer, kotlinxSerialization-preview (or each version +# in NAV3_EXTRA_KOTLINX_VERSIONS instead), in R8 full mode, and against the floor in R8 compat mode +# too. +# +# A release candidate's APKs are advisory: if they fail to build or run, the script warns instead +# of failing, unless NAV3_PREVIEW_REQUIRED=true (set by CI on PRs that change +# kotlinxSerialization-preview). +# +# Usage: +# test-nav3-backstack-entry-mapper-r8.sh Build all APKs, then run them. +# test-nav3-backstack-entry-mapper-r8.sh build DIR Build all APKs into DIR. +# test-nav3-backstack-entry-mapper-r8.sh run DIR Install and run every APK built into DIR. +# +# The APKs go in a subdirectory of DIR that only this script writes to, so DIR may also hold +# unrelated files, which neither command touches. +set -euo pipefail + +module="nav3-backstack-entry-mapper-r8-check" +moduleDir="sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check" +appId="io.sentry.tests.nav3.r8" +tag="NAV3_R8_CHECK" +previewRequired="${NAV3_PREVIEW_REQUIRED:-false}" + +# Extra versions as " " lines. Defaults to stable and any newer preview from the +# matrix catalog. Override with, e.g., +# NAV3_EXTRA_KOTLINX_VERSIONS="1.10.0 1.12.0" to test the floor, 1.10.0, and 1.12.0, all required. +# (Provide an empty string to test the floor only.) +extraKotlinxVersions=() +if [[ -n "${NAV3_EXTRA_KOTLINX_VERSIONS+x}" ]]; then + for version in $NAV3_EXTRA_KOTLINX_VERSIONS; do + extraKotlinxVersions+=("extra $version") + done +else + matrixVersions="$("$(dirname "$0")/dependency-matrix.sh" extra-versions kotlinxSerialization)" + while read -r entry; do + extraKotlinxVersions+=("$entry") + done <<< "$matrixVersions" +fi + +# Reports a problem as a GitHub Actions annotation in CI, and as a plain warning otherwise. +warn() { + if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then + echo "::warning::$1" + else + echo "WARNING: $1" + fi +} + +# Whether failures of APKs built against a version of role $1 are advisory. +isAdvisory() { + [[ "$1" == "preview" && "$previewRequired" != "true" ]] +} + +copyApk() { + cp "${moduleDir}/build/outputs/apk/release/nav3-backstack-entry-mapper-r8-check-release.apk" "$1" +} + +# Prints the subdirectory of DIR $1 that holds this script's APKs. +apkDirIn() { + echo "$1/${module}" +} + +build() { + local outDir + outDir="$(apkDirIn "$1")" + mkdir -p "$outDir" + # Removes APKs from earlier builds, which run() would otherwise run too (e.g., one for a release + # candidate that's no longer tested). Only this script writes to outDir, so no other APKs are lost. + rm -f "$outDir"/*.apk + for mode in full compat; do + local fullMode=true + [[ "$mode" == "compat" ]] && fullMode=false + echo "Building R8 $mode mode APK (kotlinx floor)..." + ./gradlew -p sentry-android-integration-tests ":${module}:assembleRelease" "-Pandroid.enableR8.fullMode=${fullMode}" + copyApk "${outDir}/${mode}.apk" + + # Compat mode keeps more than full mode, so it's only tested with the floor, where it changes + # the outcome for named companion objects (kotlinx.serialization's own R8 rules only cover them + # from 1.10.0 on). + [[ "$mode" == "compat" ]] && continue + + # Apps may ship a newer kotlinx than our compile floor, so rebuild against each. + for entry in ${extraKotlinxVersions[@]+"${extraKotlinxVersions[@]}"}; do + local role version apkName + read -r role version <<< "$entry" + # run() tells release candidates' APKs apart by name. + apkName="${mode}-kotlinx-${version}" + [[ "$role" == "preview" ]] && apkName="${mode}-kotlinx-preview-${version}" + echo "Building R8 $mode mode APK (kotlinx ${version}, ${role})..." + if ./gradlew -p sentry-android-integration-tests ":${module}:assembleRelease" \ + "-Pandroid.enableR8.fullMode=${fullMode}" "-Pnav3CheckKotlinxVersion=${version}"; then + copyApk "${outDir}/${apkName}.apk" + elif isAdvisory "$role"; then + # E.g., the release candidate requires a newer Kotlin compiler than the repo uses. + warn "Couldn't build the R8 $mode mode APK against kotlinx.serialization release candidate $version. Skipping it." + else + exit 1 + fi + done + done +} + +# Installs and launches APK $1, prints what its check reports, and returns non-zero unless the check +# passed. Failures to install or launch the APK return non-zero too, rather than exiting, so that +# run() can apply the same advisory rule to them. +runApk() { + local apk="$1" + adb uninstall "$appId" > /dev/null 2>&1 || true + adb install "$apk" > /dev/null || return 1 + # Only read lines logged from this launch on, so a stale RESULT=PASS from the previous APK can't + # hide this one's failure. Doesn't clear the log, which would also discard unrelated logs on a + # development device. The timestamp is truncated to the second, so wait a second for it to + # postdate earlier lines. + local since + sleep 1 + since="$(adb shell "date +'%m-%d %H:%M:%S.000'" | tr -d '\r')" || return 1 + adb shell am start -W -n "${appId}/.BackStackEntryMapperActivity" > /dev/null || return 1 + + local output="" + for _ in $(seq 1 60); do + output="$(adb logcat -d -T "$since" -s "${tag}:I" | grep "${tag}" || true)" + if grep -q "RESULT=" <<< "$output"; then + break + fi + if adb logcat -d -T "$since" -b crash | grep -q "$appId"; then + break + fi + sleep 1 + done + + if [[ -n "$output" ]]; then + sed -E "s/^.*${tag}: //" <<< "$output" + fi + if ! grep -q "RESULT=PASS" <<< "$output"; then + adb logcat -d -T "$since" -b crash | grep -A 20 "$appId" || true + return 1 + fi +} + +run() { + local apkDir + apkDir="$(apkDirIn "$1")" + local failed=0 + shopt -s nullglob + local apks=("$apkDir"/*.apk) + if [[ ${#apks[@]} -eq 0 ]]; then + echo "No APKs found in $apkDir" + exit 1 + fi + + for apk in "${apks[@]}"; do + local name + name="$(basename "$apk" .apk)" + echo "=== $name" + if ! runApk "$apk"; then + echo "FAILED: $name" + if [[ "$name" == *-kotlinx-preview-* ]] && isAdvisory preview; then + warn "The R8 check failed for $name, which uses a kotlinx.serialization release candidate." + else + failed=1 + fi + fi + done + + if [[ $failed -ne 0 ]]; then + echo "Nav3 BackStackEntryMapper R8 check failed." + exit 1 + fi + echo "Nav3 BackStackEntryMapper R8 check passed." +} + +case "${1:-}" in + build) build "${2:?Usage: $0 build DIR}" ;; + run) run "${2:?Usage: $0 run DIR}" ;; + "") + apkDir="${moduleDir}/build/r8-check-apks" + build "$apkDir" + run "$apkDir" + ;; + *) + echo "Usage: $0 [build DIR | run DIR]" + exit 1 + ;; +esac diff --git a/scripts/test-nav3-kotlinx-versions.sh b/scripts/test-nav3-kotlinx-versions.sh new file mode 100755 index 00000000000..256ce3f2ad4 --- /dev/null +++ b/scripts/test-nav3-kotlinx-versions.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Runs all of sentry-android-navigation3's unit tests against newer kotlinx.serialization versions +# than the floor they compile against: kotlinxSerialization-stable in +# gradle/dependency-matrix.versions.toml and, if it's newer, kotlinxSerialization-preview (or each +# version in NAV3_EXTRA_KOTLINX_VERSIONS instead). The Build workflow runs them against the floor. +# +# Runs the whole suite rather than only the tests that appear to use kotlinx.serialization, as a +# test can depend on it through a shared fixture without naming it in its own source. +# +# A release candidate's failures are advisory: the script warns instead of failing, unless +# NAV3_PREVIEW_REQUIRED=true (set by CI on PRs that change kotlinxSerialization-preview). +# +# Usage: test-nav3-kotlinx-versions.sh +set -euo pipefail + +cd "$(dirname "$0")/../" +previewRequired="${NAV3_PREVIEW_REQUIRED:-false}" + +# Reports a problem as a GitHub Actions annotation in CI, and as a plain warning otherwise. +warn() { + if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then + echo "::warning::$1" + else + echo "WARNING: $1" + fi +} + +# " " lines, as for scripts/test-nav3-backstack-entry-mapper-r8.sh. +if [[ -n "${NAV3_EXTRA_KOTLINX_VERSIONS+x}" ]]; then + versions="" + for version in $NAV3_EXTRA_KOTLINX_VERSIONS; do + versions+="extra $version"$'\n' + done +else + versions="$(scripts/dependency-matrix.sh extra-versions kotlinxSerialization)" +fi + +failed=0 +while read -r role version; do + [[ -z "$role" ]] && continue + echo "Running unit tests against kotlinx.serialization $version ($role)..." + # Reads no stdin, so it can't consume the loop's remaining versions. + if ./gradlew :sentry-android-navigation3:testReleaseUnitTest \ + -Pnav3TestKotlinxVersion="$version" < /dev/null; then + : + elif [[ "$role" == "preview" && "$previewRequired" != "true" ]]; then + warn "Unit tests failed against kotlinx.serialization release candidate $version." + else + failed=1 + fi +done <<< "$versions" + +if [[ $failed -ne 0 ]]; then + echo "sentry-android-navigation3 unit tests failed against a newer kotlinx.serialization version." + exit 1 +fi diff --git a/scripts/update-kotlinx-serialization-preview.sh b/scripts/update-kotlinx-serialization-preview.sh new file mode 100755 index 00000000000..9ac0726dbff --- /dev/null +++ b/scripts/update-kotlinx-serialization-preview.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Script for testing sentry-android-navigation3 against new kotlinx.serialization release +# candidates. Updates kotlinxSerialization-preview in gradle/dependency-matrix.versions.toml, which +# the Nav3 R8 check and unit tests also run against while it's newer than +# kotlinxSerialization-stable. +# +# Run weekly by update-deps.yml, whose pattern only matches release candidate tags (e.g. +# v1.14.0-RC). Dependabot bumps kotlinxSerialization-stable, and nothing bumps +# kotlinxSerialization-floor. If the resulting PR fails, see "When a kotlinx.serialization bump +# fails" in sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/README.md. + +cd "$(dirname "$0")/../" +matrix=scripts/dependency-matrix.sh + +case "${1:-}" in +get-version) + # Printed as the release's tag (e.g. v1.12.0-RC), which the updater uses as the old ref when it + # compares upstream changelogs. + echo "v$("$matrix" get kotlinxSerialization preview)" + ;; +get-repo) + echo "https://github.com/Kotlin/kotlinx.serialization.git" + ;; +set-version) + # kotlinx.serialization tags are prefixed with "v" (e.g. v1.12.0-RC). + version=${2#v} + + echo "Setting kotlinxSerialization-preview to '$version'" + "$matrix" set kotlinxSerialization preview "$version" + ;; +*) + echo "Unknown argument '${1:-}'" + exit 1 + ;; +esac diff --git a/sentry-android-integration-tests/build.gradle.kts b/sentry-android-integration-tests/build.gradle.kts index 34b83c2c067..16be8b4011d 100644 --- a/sentry-android-integration-tests/build.gradle.kts +++ b/sentry-android-integration-tests/build.gradle.kts @@ -2,6 +2,7 @@ plugins { alias(libs.plugins.android.application) apply false alias(libs.plugins.kotlin.android) apply false alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.kotlin.serialization) apply false alias(libs.plugins.errorprone) apply false alias(libs.plugins.detekt) apply false alias(libs.plugins.gradle.versions) apply false diff --git a/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/README.md b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/README.md new file mode 100644 index 00000000000..86b9812cd20 --- /dev/null +++ b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/README.md @@ -0,0 +1,62 @@ +# nav3-backstack-entry-mapper-r8-check + +Verifies that `BackStackEntryMapper.SerialName` returns the expected names after R8 obfuscation. The SDK ships no keep rules for apps' +kotlinx.serialization classes; this app uses the library's consumer rules and per-class rules in `proguard-rules.pro`. + +The tests check serial names, including `/unknown` for keys the mapper can't name, which also shows that the mapper's compatibility probe +passed: a failed probe records `/unknown` for every key. The app initializes Sentry with a logger that records the mapper's messages, and +checks that the probe wasn't inconclusive and didn't fail (`ProbeLogChecks.kt`): an inconclusive name-lookup probe leaves names right but +can't detect an incompatible kotlinx.serialization version in minified apps. It also checks that R8 actually renamed a representative +class. + +## How to run it + +Run the tests against a booted emulator or device: + +```bash +./scripts/test-nav3-backstack-entry-mapper-r8.sh +``` + +The script tests the kotlinx.serialization versions in `gradle/dependency-matrix.versions.toml`: the floor +(`kotlinxSerialization-floor`), the latest stable release (`kotlinxSerialization-stable`), and the latest release candidate +(`kotlinxSerialization-preview`), when newer than stable. Each version runs in R8 full mode; the floor also runs in compat mode to cover +named-companion lookups with older consumer rules. + +`scripts/test-nav3-kotlinx-versions.sh` runs all of the module's unit tests against the same newer versions. + +Each APK must report `RESULT=PASS`. Release candidate build and run failures are advisory unless `NAV3_PREVIEW_REQUIRED=true`, which +CI sets on PRs that change `kotlinxSerialization-preview`. + +Set `NAV3_EXTRA_KOTLINX_VERSIONS="1.10.0 1.12.0"` to replace the extra versions with required versions of your choice. An empty string +tests only the floor, which always runs. + +## When a kotlinx.serialization bump fails + +Two kinds of PRs bump the versions this check and the module's unit tests run against: + +- Dependabot opens a PR that sets `kotlinxSerialization-stable` to the latest stable release. It waits until a release is three days old + (Dependabot's default cooldown), so it may skip a release that's quickly followed by another. +- Each week, `update-deps.yml` opens or updates a PR that sets `kotlinxSerialization-preview` to the latest release candidate, using + `scripts/update-kotlinx-serialization-preview.sh`. + +Each PR runs the R8 check and unit tests against the new version. A failure may affect apps already using that release or signal a +problem in the next stable release. Keep the existing floor supported; see "Version floor" in the `kotlinx` package README. + +**The PR doesn't compile.** A kotlinx.serialization release can require a newer Kotlin compiler than the repo uses (e.g., errors about +an incompatible Kotlin metadata version or `Require-Kotlin-Version`). Our tests and this app are compiled by +our Kotlin compiler against the new release, so they can't be built until the repo upgrades Kotlin. + +1. Leave the PR open and unmerged, so the version stays at the last release that compiles. Don't close a Dependabot PR: Dependabot then + ignores that version. Dependabot replaces its PR, and the updater updates its own, as new releases appear. +2. Open an issue to upgrade the repo's Kotlin version, and link it from the PR. +3. Merge the PR after the Kotlin upgrade lands and the PR passes. + +This doesn't mean apps on the new release are broken: they compile with their own, newer Kotlin compiler. It does mean that release is +untested until the Kotlin upgrade lands. + +**Tests or the R8 check fail.** Investigate whether kotlinx.serialization changed behavior the mapper relies on. + +1. Read the release's changelog, especially for changes to serializer lookup, serial descriptors, and the library's R8 rules. +2. Determine whether apps on the new release now record wrong names or `/unknown`. If so, fix it with a code path for the versions that + behave differently, so apps on older versions keep working. +3. Merge the PR together with the fix. diff --git a/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/build.gradle.kts b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/build.gradle.kts new file mode 100644 index 00000000000..1127a244555 --- /dev/null +++ b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/build.gradle.kts @@ -0,0 +1,85 @@ +// Checks BackStackEntryMapper.SerialName in R8-minified release builds. See README.md. +plugins { + id("com.android.application") + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.serialization) + id("io.sentry.spotless") + id("io.sentry.jdk-target") +} + +val sentryVersion = libs.versions.sentry.get() + +// Defaults to the min version sentry-android-navigation3 supports, whose R8 rules are the most +// limited. scripts/test-nav3-backstack-entry-mapper-r8.sh overrides it with +// -Pnav3CheckKotlinxVersion= to test newer versions. +val kotlinxVersionOverride = providers.gradleProperty("nav3CheckKotlinxVersion").orNull +val kotlinxFloor = matrixLibs.versions.kotlinxSerialization.floor.get() +val kotlinxVersion = kotlinxVersionOverride ?: kotlinxFloor + +// Whether the mapper can name a @Serializable class with a named companion object and no +// named-companion R8 rules of the app's own: "named", "unknown", or "either". +// - kotlinx.serialization's own R8 rules keep what its lookup needs from 1.10.0 on. +// - The floor's rules don't, in R8 full and compat mode alike (verified on a device), so the floor +// must record /unknown. Asserting it means a change in that behavior shows up here. +// - Between the two, it depends on the version and R8 mode (e.g., 1.9.x's lookup succeeds in +// compat mode only), so either outcome is accepted. +val namedCompanionOutcome = + kotlinxVersion.split('.', '-').let { parts -> + val major = parts[0].toInt() + val minor = parts.getOrNull(1)?.toIntOrNull() ?: 0 + when { + major > 1 || (major == 1 && minor >= 10) -> "named" + kotlinxVersion == kotlinxFloor -> "unknown" + else -> "either" + } + } + +android { + namespace = "io.sentry.tests.nav3.r8" + compileSdk = libs.versions.compileSdk.get().toInt() + compileSdkMinor = libs.versions.compileSdkMinor.get().toInt() + + defaultConfig { + applicationId = "io.sentry.tests.nav3.r8" + minSdk = libs.versions.minSdk.get().toInt() + targetSdk = libs.versions.targetSdk.get().toInt() + versionCode = 1 + versionName = "1.0" + buildConfigField("String", "NAMED_COMPANION_OUTCOME", "\"$namedCompanionOutcome\"") + } + + signingConfigs { + getByName("debug") { + storeFile = file("../../debug.keystore") + storePassword = "android" + keyAlias = "androiddebugkey" + keyPassword = "android" + } + } + + buildTypes { + release { + isMinifyEnabled = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro", + ) + signingConfig = signingConfigs.getByName("debug") + } + } + + buildFeatures { buildConfig = true } + + androidComponents.beforeVariants { it.enable = it.buildType == "release" } +} + +dependencies { + implementation("io.sentry:sentry-android-navigation3:$sentryVersion") + // Lets the check initialize Sentry with a logger that records the mapper's messages. + implementation("io.sentry:sentry-android-core:$sentryVersion") + // compileOnly in sentry-android-navigation3; always available for apps that use Nav3. + implementation(libs.androidx.compose.runtime) + + // Strict, so that no other dependency can raise the version the check runs against. + implementation(matrixLibs.kotlinxSerialization.core) { version { strictly(kotlinxVersion) } } +} diff --git a/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/proguard-rules.pro b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/proguard-rules.pro new file mode 100644 index 00000000000..b941e916c18 --- /dev/null +++ b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/proguard-rules.pro @@ -0,0 +1,20 @@ +# kotlinx.serialization's named-companion rules for R8 full mode, which also work in compat mode. +# Needed for the serialization floor (1.7.3); kotlinx.serialization 1.10.0+ supplies its own. +# See https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers +# https://github.com/Kotlin/kotlinx.serialization#android +-keepattributes InnerClasses + +-if @kotlinx.serialization.Serializable class +io.sentry.tests.nav3.r8.NamedCompanionKeyWithRules +{ + static **$* *; +} +-keepnames class <1>$$serializer { + static <1>$$serializer INSTANCE; +} + +-keepclasseswithmembers, allowshrinking, allowobfuscation, allowaccessmodification class +io.sentry.tests.nav3.r8.NamedCompanionKeyWithRules +{ + *; +} diff --git a/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/AndroidManifest.xml b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..266d73b6757 --- /dev/null +++ b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BackStackEntryMapperActivity.kt b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BackStackEntryMapperActivity.kt new file mode 100644 index 00000000000..29a54dd7cdf --- /dev/null +++ b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/BackStackEntryMapperActivity.kt @@ -0,0 +1,92 @@ +package io.sentry.tests.nav3.r8 + +import android.app.Activity +import android.os.Bundle +import android.util.Log +import android.widget.ScrollView +import android.widget.TextView +import io.sentry.compose.navigation3.BackStackEntryMapper + +/** + * Maps every [Expectation] with `BackStackEntryMapper.SerialName`, and reports the results. + * + * An exception crashes the Activity, which the runner script reports as a failure. + */ +class BackStackEntryMapperActivity : Activity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + // Before the mapper's first map() call, which runs its compatibility probe. + val logger = RecordingLogger() + initSentry(this, logger) + + val nameMapper = BackStackEntryMapper.SerialName + val expectations = + listOf( + Expectation("string", "home", null), + Expectation("non-serializable class", NotSerializable("1"), null), + Expectation("unannotated enum", UnannotatedEnum.A, null), + ) + serializableExpectations() + + val lines = mutableListOf() + var failures = 0 + + for (expectation in expectations) { + val named = nameMapper.map(expectation.key) + val matched = named?.name == expectation.expected && named?.arguments == null + val fellBack = expectation.alsoAcceptsUnnamed && named == null + val passed = matched || fellBack + + if (!passed) failures++ + + lines += + "${if (passed) "PASS" else "FAIL"} ${expectation.label} " + + "(runtime class ${expectation.key.javaClass.name}): " + + "expected=${expectation.expected} actual=${named?.name}" + + (named?.arguments?.let { " arguments=$it" } ?: "") + + if (fellBack) " (INFO: fell back to /unknown, also accepted)" else "" + } + + for (check in minificationChecks() + probeLogChecks(logger)) { + if (!check.passed) failures++ + lines += "${if (check.passed) "PASS" else "FAIL"} ${check.description}" + } + + lines += "RESULT=${if (failures == 0) "PASS" else "FAIL ($failures)"}" + + lines.forEach { Log.i(TAG, it) } + setContentView( + ScrollView(this).apply { + addView(TextView(context).apply { text = lines.joinToString(separator = "\n") }) + }, + ) + } + + private companion object { + const val TAG = "NAV3_R8_CHECK" + } +} + +/** A check of the build or the SDK's state, besides an [Expectation]. */ +class Check(val description: String, val passed: Boolean) + +/** + * A back stack key and the name [BackStackEntryMapper.SerialName] should produce for it, or `null` + * if it should be unnamed. + * + * If [alsoAcceptsUnnamed], the mapper may instead return `null` for the key in cases where neither + * kotlinx.serialization nor R8 guarantees whether it can be named. + */ +class Expectation( + val label: String, + val key: Any, + val expected: String?, + val alsoAcceptsUnnamed: Boolean = false, +) + +data class NotSerializable(val id: String) + +enum class UnannotatedEnum { + A, +} diff --git a/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt new file mode 100644 index 00000000000..37dd9c8f20a --- /dev/null +++ b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/ProbeLogChecks.kt @@ -0,0 +1,96 @@ +package io.sentry.tests.nav3.r8 + +import android.content.Context +import io.sentry.ILogger +import io.sentry.SentryLevel +import io.sentry.android.core.SentryAndroid +import java.util.Collections + +/** + * Records the messages the SDK logs, so the check can tell whether the mapper's compatibility probe + * ran conclusively under R8. + */ +class RecordingLogger : ILogger { + + val messages: MutableList = Collections.synchronizedList(mutableListOf()) + + override fun log(level: SentryLevel, message: String, vararg args: Any?) { + messages += format(message, args) + } + + override fun log(level: SentryLevel, message: String, throwable: Throwable?) { + messages += withError(message, throwable) + } + + override fun log( + level: SentryLevel, + throwable: Throwable?, + message: String, + vararg args: Any?, + ) { + messages += withError(format(message, args), throwable) + } + + override fun isEnabled(level: SentryLevel?): Boolean = true + + private fun format(message: String, args: Array): String = + if (args.isEmpty()) message else String.format(message, *args) + + /** Appends [throwable] and its causes, so a failed check shows why the probe failed. */ + private fun withError(message: String, throwable: Throwable?): String = + if (throwable == null) message + else message + generateSequence(throwable) { it.cause }.take(5).joinToString { " | $it" } +} + +/** + * Initializes Sentry with [logger] and `debug` enabled, so the mapper's logs reach it. The DSN + * points nowhere reachable; the check captures no events. + */ +fun initSentry(context: Context, logger: ILogger) { + SentryAndroid.init(context) { options -> + options.dsn = "https://key@localhost/0" + options.isDebug = true + options.setLogger(logger) + } +} + +/** + * Checks that the mapper's compatibility probe ran conclusively under R8, from the messages + * [logger] recorded after the mapper mapped every [Expectation]. + * + * The names already show whether a probe failed, but not whether the name lookup probe was + * inconclusive, e.g., because R8 removed what looking up its own fixture needs. The mapper then + * handles failures one type at a time, so names still come out right, but the probe can't detect an + * incompatible kotlinx.serialization version in minified apps. + * + * The probe's messages are matched by their fixed prefixes. A positive control, the warning for + * [NotSerializable], shows the logger receives the mapper's messages, so a probe message that + * changes its prefix is the only way these checks could pass vacuously. + */ +fun probeLogChecks(logger: RecordingLogger): List { + val messages = logger.messages.toList() + return listOf( + Check( + "the mapper's warnings reach the logger (one names ${NotSerializable::class.java.name})", + messages.any { NotSerializable::class.java.name in it }, + ), + ) + + PROBE_MESSAGE_PREFIXES.map { prefix -> + val logged = messages.firstOrNull { it.startsWith(prefix) } + Check( + "nothing logged \"$prefix…\"" + if (logged != null) " (logged: $logged)" else "", + logged == null, + ) + } +} + +/** + * The prefixes of the messages the mapper logs when its compatibility probe is inconclusive or + * fails, or a built-in mapper can't be created. See `KotlinxMapperDiagnostics` and + * `BuiltInBackStackEntryMappers` in sentry-android-navigation3. + */ +private val PROBE_MESSAGE_PREFIXES = + listOf( + "Nav3 couldn't verify kotlinx.serialization support", + "Nav3 built-in mapper creation failed", + ) diff --git a/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt new file mode 100644 index 00000000000..113ef4e4f98 --- /dev/null +++ b/sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/src/main/kotlin/io/sentry/tests/nav3/r8/SerializableKeys.kt @@ -0,0 +1,169 @@ +package io.sentry.tests.nav3.r8 + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +@Serializable data object PublicObject + +@Serializable @SerialName("Named") data class NamedClass(val id: String) + +@Serializable data class DefaultNamedClass(val id: String) + +@Serializable +sealed interface Sealed { + @Serializable data object Child : Sealed + + @Serializable data class Leaf(val id: String) : Sealed +} + +@Serializable +enum class SerializableEnum { + A, +} + +@Serializable data class Generic(val value: T) + +@Serializable private data object PrivateTopLevelObject + +@Serializable private data class PrivateTopLevelClass(val id: String) + +/** Named by its custom serializer, which the plugin's companion `serializer()` returns. */ +@Serializable(with = SlugSerializer::class) class Slug(val value: String) + +object SlugSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("slug", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Slug) = encoder.encodeString(value.value) + + override fun deserialize(decoder: Decoder): Slug = Slug(decoder.decodeString()) +} + +/** + * An enum whose constant has a body, so the constant is an instance of an anonymous subclass that + * isn't `@Serializable` itself. The mapper looks up the declaring enum instead. + */ +@Serializable +enum class TabWithBody { + HOME { + override fun icon(): String = "house" + }; + + abstract fun icon(): String +} + +/** A value class used as a back stack key itself, which is boxed when passed as `Any`. */ +@Serializable @JvmInline value class TabId(val id: String) + +/** + * Has a named companion object but no named-companion R8 rules of the app's own. + * kotlinx.serialization 1.10.0+'s own rules keep what its reflective serializer lookup needs, so + * the mapper must name it. The floor's rules don't, in R8 full and compat mode alike, so at the + * floor the mapper must record it as `/unknown`. In between, it depends on the version and R8 mode + * (e.g., 1.9.x's lookup survives in compat mode only), so either outcome is accepted. See + * `namedCompanionOutcome` in `build.gradle.kts`. + */ +@Serializable +data class NamedCompanionKey(val id: String) { + companion object Factory { + fun of(id: String): NamedCompanionKey = NamedCompanionKey(id) + } +} + +/** + * Like [NamedCompanionKey], but covered by kotlinx.serialization's named-companion R8 rules + * (`proguard-rules.pro`), as the + * [troubleshooting docs](https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers) + * tell apps to add. + */ +@Serializable +data class NamedCompanionKeyWithRules(val id: String) { + companion object Factory { + fun of(id: String): NamedCompanionKeyWithRules = NamedCompanionKeyWithRules(id) + } +} + +class Holder { + @Serializable private data object PrivateNestedObject + + @Serializable private data class PrivateNestedClass(val id: String) + + companion object { + fun keys(): List = + listOf( + Expectation( + "private nested object", + PrivateNestedObject, + "io.sentry.tests.nav3.r8.Holder.PrivateNestedObject", + ), + Expectation( + "private nested class", + PrivateNestedClass("1"), + "io.sentry.tests.nav3.r8.Holder.PrivateNestedClass", + ), + ) + } +} + +private const val PKG = "io.sentry.tests.nav3.r8" + +fun serializableExpectations(): List = + listOf( + Expectation("public data object", PublicObject, "$PKG.PublicObject"), + Expectation("data class with @SerialName", NamedClass("1"), "Named"), + Expectation("data class", DefaultNamedClass("1"), "$PKG.DefaultNamedClass"), + Expectation("sealed child object", Sealed.Child, "$PKG.Sealed.Child"), + Expectation("sealed leaf class", Sealed.Leaf("1"), "$PKG.Sealed.Leaf"), + Expectation( + "serializable enum", + SerializableEnum.A, + "$PKG.SerializableEnum", + ), + Expectation("generic class", Generic("x"), null), + Expectation("private top-level object", PrivateTopLevelObject, "$PKG.PrivateTopLevelObject"), + Expectation( + "private top-level class", + PrivateTopLevelClass("1"), + "$PKG.PrivateTopLevelClass", + ), + Expectation("class with a custom serializer", Slug("shoes"), "slug"), + Expectation( + "enum constant with a body", + TabWithBody.HOME, + "$PKG.TabWithBody", + ), + Expectation("value class", TabId("feed"), "$PKG.TabId"), + if (BuildConfig.NAMED_COMPANION_OUTCOME == "unknown") { + Expectation( + "named companion without rules (/unknown at the floor)", + NamedCompanionKey.of("1"), + null, + ) + } else { + Expectation( + "named companion without rules", + NamedCompanionKey.of("1"), + "$PKG.NamedCompanionKey", + alsoAcceptsUnnamed = BuildConfig.NAMED_COMPANION_OUTCOME == "either", + ) + }, + Expectation( + "named companion with rules", + NamedCompanionKeyWithRules.of("1"), + "$PKG.NamedCompanionKeyWithRules", + ), + ) + Holder.keys() + +fun minificationChecks(): List = + listOf( + Check( + "PublicObject was renamed (runtime class ${PublicObject::class.java.name})", + PublicObject::class.java.name != "$PKG.PublicObject", + ), + ) diff --git a/sentry-android-integration-tests/sentry-samples-android/build.gradle.kts b/sentry-android-integration-tests/sentry-samples-android/build.gradle.kts index aee693598cb..1ad562d1258 100644 --- a/sentry-android-integration-tests/sentry-samples-android/build.gradle.kts +++ b/sentry-android-integration-tests/sentry-samples-android/build.gradle.kts @@ -13,6 +13,7 @@ plugins { id("io.sentry.jdk-target") alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.compose) + alias(libs.plugins.kotlin.serialization) alias(libs.plugins.ksp) alias(libs.plugins.sentry) apply false alias(libs.plugins.sqldelight) diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt index 807fedad09a..1398c9c4e34 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt @@ -43,6 +43,7 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.navigation3.runtime.entryProvider import androidx.navigation3.ui.NavDisplay +import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry import io.sentry.compose.navigation3.SentryNavEffect import io.sentry.compose.navigation3.SentryNavOptions @@ -232,51 +233,65 @@ private fun Nav3SampleApp( } val performanceExtractorMode = performanceState.extractorMode val performanceArgumentMode = performanceState.argumentMode - val backStackEntryMapper = + val performanceMapperMode = performanceState.mapperMode + val backStackEntryMapper: BackStackEntryMapper = remember( isPerformanceScenario, performanceExtractorMode, performanceArgumentMode, + performanceMapperMode, integrationMode.includeArguments, ) { - { route: Nav3Route -> - val name = - if (isPerformanceScenario) { + if (!isPerformanceScenario) { + // Names each route after its serial name, and adds the arguments the route selects. + BackStackEntryMapper { route -> + BackStackEntryMapper.SerialName.map(route)?.let { entry -> + SentryBackStackEntry(name = entry.name, arguments = route.arguments) + } + } + } else if (performanceMapperMode == Nav3PerformanceMapperMode.SERIAL_NAME) { + // The built-in mapper itself, so SentryNavEffect.onBackStackChanged measures its real + // name lookups. It records no arguments. + BackStackEntryMapper.SerialName + } else { + // A custom mapper, so the performance scenario can time name and argument extraction + // separately and substitute synthetic arguments. + BackStackEntryMapper { route -> + val name = performanceState.recordNameExtraction("Nav3Stress.nameExtraction") { consumeNav3PerformanceExtractorWork( performanceExtractorMode, route.performanceSeed, ) - route.routeName + checkNotNull(BackStackEntryMapper.SerialName.map(route)) { + "${route::class.simpleName} can't be named by BackStackEntryMapper.SerialName." + } + .name } - } else { - route.routeName - } - val arguments = - if (isPerformanceScenario && !integrationMode.includeArguments) { - null - } else if (isPerformanceScenario) { - performanceState.recordArgumentExtraction("Nav3Stress.argumentsExtraction") { - consumeNav3PerformanceExtractorWork( - performanceExtractorMode, - route.performanceSeed, - ) - if (route is Nav3Route.Performance) { - nav3PerformanceArguments( - performanceArgumentMode, - route.index, - route.generation, + val arguments = + if (!integrationMode.includeArguments) { + null + } else { + performanceState.recordArgumentExtraction("Nav3Stress.argumentsExtraction") { + consumeNav3PerformanceExtractorWork( + performanceExtractorMode, + route.performanceSeed, ) - } else { - route.arguments + if (route is Nav3Route.Performance) { + nav3PerformanceArguments( + performanceArgumentMode, + route.index, + route.generation, + ) + } else { + route.arguments + } } } - } else { - route.arguments - } - SentryBackStackEntry(name = name, arguments = arguments) + SentryBackStackEntry(name = name, arguments = arguments) + } } } diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt index 4309cc66f08..6c9ccb0e886 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt @@ -54,7 +54,7 @@ import androidx.navigation3.ui.NavDisplay import androidx.navigationevent.compose.LocalNavigationEventDispatcherOwner import androidx.navigationevent.compose.rememberNavigationEventDispatcherOwner import io.sentry.compose.SentryModifier.sentryTag -import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryNavEffect import io.sentry.compose.navigation3.SentryNavOptions import io.sentry.samples.android.navigation.common.NavigationSampleConfig @@ -307,9 +307,7 @@ internal fun MultiRootNavDisplay( // Keep this before the NavDisplay below: TracedNav3Route's resume tagging relies on it. SentryNavEffect( backStack = backStack, - backStackEntryMapper = { route -> - SentryBackStackEntry(name = route.routeName, arguments = route.arguments) - }, + backStackEntryMapper = BackStackEntryMapper.SerialName, options = options, ) val onBack: () -> Unit = { diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt index e923948060f..eb14cb2db1e 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt @@ -52,6 +52,7 @@ internal class Nav3PerformanceState( var autoNavigate by mutableStateOf(false) var extractorMode by mutableStateOf(Nav3PerformanceExtractorMode.NORMAL) var argumentMode by mutableStateOf(Nav3PerformanceArgumentMode.FLAT) + var mapperMode by mutableStateOf(Nav3PerformanceMapperMode.CUSTOM) var integrationMode by mutableStateOf(Nav3PerformanceIntegrationMode.FULL_STACK) private set @@ -321,6 +322,7 @@ internal class Nav3PerformanceState( appendLine("status=$performanceStatus") appendLine("route=$currentRoute") appendLine("tracked_stack=$backStack") + appendLine("mapper_mode=${mapperMode.label}") appendLine("recomposition_requests=$recompositionRequests") appendLine("navigation_mutations=$navigationMutations") appendLine("destination_changes=$destinationChanges") @@ -512,6 +514,19 @@ internal enum class Nav3PerformanceArgumentMode(val label: String) { LARGE("Large"), } +/** + * Which mapper the performance scenario feeds to `SentryNavEffect`. + * + * [CUSTOM] times name and argument extraction separately and substitutes the synthetic + * [Nav3PerformanceArgumentMode] shapes. [SERIAL_NAME] runs the built-in mapper instead, so its name + * lookups are what `SentryNavEffect.onBackStackChanged` measures. The built-in mapper records no + * arguments, so the argument-shape control and the per-call extractor timings don't apply. + */ +internal enum class Nav3PerformanceMapperMode(val label: String) { + CUSTOM("Custom"), + SERIAL_NAME("SerialName"), +} + internal enum class Nav3PerformanceIntegrationMode( val label: String, val captureBackStack: Boolean, @@ -874,10 +889,21 @@ internal fun Nav3PerformancePanel( if (showExtractorControls) { PerfCard(title = "Extractor Inputs") { + val customExtractorControlsEnabled = + !state.performanceRunActive && state.mapperMode == Nav3PerformanceMapperMode.CUSTOM + PerfModeRow( + label = "Mapper", + selectedLabel = state.mapperMode.label, + enabled = !state.performanceRunActive, + options = + Nav3PerformanceMapperMode.entries.map { mode -> + mode.label to { state.mapperMode = mode } + }, + ) PerfModeRow( label = "Extractor cost", selectedLabel = state.extractorMode.label, - enabled = !state.performanceRunActive, + enabled = customExtractorControlsEnabled, options = Nav3PerformanceExtractorMode.entries.map { mode -> mode.label to { state.extractorMode = mode } @@ -886,7 +912,7 @@ internal fun Nav3PerformancePanel( PerfModeRow( label = "Argument shape", selectedLabel = state.argumentMode.label, - enabled = !state.performanceRunActive, + enabled = customExtractorControlsEnabled, options = Nav3PerformanceArgumentMode.entries.map { mode -> mode.label to { state.argumentMode = mode } diff --git a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt index 8dc18c45941..ee71488dbb5 100644 --- a/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt +++ b/sentry-android-integration-tests/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt @@ -11,8 +11,15 @@ import io.sentry.samples.android.navigation.common.RouteNames import io.sentry.samples.android.navigation.common.RouteSpec import io.sentry.samples.android.navigation.common.RouteSpecs import io.sentry.samples.android.navigation.common.displayRoute +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable -internal fun Nav3Route.displayRoute(): String = routeSpec().displayRoute(arguments) +internal fun Nav3Route.displayRoute(): String = + when (this) { + // Shows the index and generation that tell the performance scenario's routes apart. + is Nav3Route.Performance -> "/$previewName" + else -> routeSpec().displayRoute(arguments) + } internal fun Nav3Route.routeSpec(): RouteSpec = when (this) { @@ -228,8 +235,28 @@ internal fun SnapshotStateList.replacePerformanceTop(generation: Int) set(lastIndex, Nav3Route.Performance(index = lastIndex, generation = generation)) } +/** + * The sample's back stack keys. Each is `@Serializable`, so [BackStackEntryMapper.SerialName] can + * name it: the route's `@SerialName`, which matches the Nav2 sample's [RouteNames], becomes its + * Sentry name. Every member other than a route's constructor properties is a getter, so it isn't + * serialized. + * + * Screens, tags, and transaction checks use [routeName] and [arguments], which repeat what the + * sample's mapper records, instead of calling the mapper. Only `SentryNavEffect` runs the mapper, + * so its one-time setup and any diagnostics stay out of composition, and a route the mapper can't + * name is recorded as `/unknown` rather than breaking the screen that shows it. + */ internal sealed interface Nav3Route { + /** + * The route's name as Sentry records it, without the leading `/`. Each route returns the constant + * it passes to `@SerialName`. + */ val routeName: String + + /** + * The route's arguments as the sample's mapper records them: each property under the Nav2 + * sample's [NavArgs] name, with a `null` campaign left out, as in the Nav2 sample. + */ val arguments: Map get() = emptyMap() @@ -239,87 +266,168 @@ internal sealed interface Nav3Route { val performanceSeed: Int get() = hashCode() + @Serializable + @SerialName(RouteNames.LANDING) data object Landing : Nav3Route { - override val routeName: String = RouteNames.LANDING + override val routeName: String + get() = RouteNames.LANDING } + @Serializable + @SerialName(RouteNames.HOME) data object SingleStack : Nav3Route { - override val routeName: String = RouteNames.HOME + override val routeName: String + get() = RouteNames.HOME } + @Serializable + @SerialName(RouteNames.CUSTOM) data object Custom : Nav3Route { - override val routeName: String = "Custom" + override val routeName: String + get() = RouteNames.CUSTOM } + @Serializable + @SerialName(MultiActivity.NAME) data object MultiActivity : Nav3Route { - override val routeName: String = "MultiActivity" + const val NAME = "MultiActivity" + + override val routeName: String + get() = NAME } + @Serializable + @SerialName(MultiFragment.NAME) data object MultiFragment : Nav3Route { - override val routeName: String = "MultiFragment" + const val NAME = "MultiFragment" + + override val routeName: String + get() = NAME } + @Serializable + @SerialName(FragmentOverlay.NAME) data object FragmentOverlay : Nav3Route { - override val routeName: String = "FragmentOverlay" + const val NAME = "FragmentOverlay" + + override val routeName: String + get() = NAME } + @Serializable + @SerialName(ViewPager2.NAME) data object ViewPager2 : Nav3Route { - override val routeName: String = "ViewPager2" + const val NAME = "ViewPager2" + + override val routeName: String + get() = NAME } + @Serializable + @SerialName(RouteNames.DEEP_LINK) data object DeepLink : Nav3Route { - override val routeName: String = RouteNames.DEEP_LINK + override val routeName: String + get() = RouteNames.DEEP_LINK } + @Serializable + @SerialName(RouteNames.PRODUCT_LIST) data object ProductList : Nav3Route { - override val routeName: String = RouteNames.PRODUCT_LIST + override val routeName: String + get() = RouteNames.PRODUCT_LIST } + @Serializable + @SerialName(RouteNames.PRODUCT_DETAIL) data class ProductDetail( val productId: String, val source: String, val campaign: String? = null, ) : Nav3Route { - override val routeName: String = RouteNames.PRODUCT_DETAIL - override val arguments: Map = - mapOf( - NavArgs.PRODUCT_ID to productId, - NavArgs.SOURCE to source, - NavArgs.CAMPAIGN to campaign, - ) - .filterValues { it != null } - override val previewName: String = "ProductDetail($productId)" + override val routeName: String + get() = RouteNames.PRODUCT_DETAIL + + override val arguments: Map + get() = buildMap { + put(NavArgs.PRODUCT_ID, productId) + put(NavArgs.SOURCE, source) + campaign?.let { put(NavArgs.CAMPAIGN, it) } + } + + override val previewName: String + get() = "ProductDetail($productId)" } + @Serializable + @SerialName(RouteNames.CHECKOUT) data class Checkout(val productId: String) : Nav3Route { - override val routeName: String = RouteNames.CHECKOUT - override val arguments: Map = mapOf(NavArgs.PRODUCT_ID to productId) - override val previewName: String = "Checkout($productId)" + override val routeName: String + get() = RouteNames.CHECKOUT + + override val arguments: Map + get() = mapOf(NavArgs.PRODUCT_ID to productId) + + override val previewName: String + get() = "Checkout($productId)" } + @Serializable + @SerialName(RouteNames.CONFIRMATION) data class Confirmation(val orderId: String) : Nav3Route { - override val routeName: String = RouteNames.CONFIRMATION - override val arguments: Map = mapOf(NavArgs.ORDER_ID to orderId) - override val previewName: String = "Confirmation($orderId)" + override val routeName: String + get() = RouteNames.CONFIRMATION + + override val arguments: Map + get() = mapOf(NavArgs.ORDER_ID to orderId) + + override val previewName: String + get() = "Confirmation($orderId)" } + @Serializable + @SerialName(RouteNames.PROMO_DIALOG) data class PromoDialog(val promoId: String) : Nav3Route { - override val routeName: String = RouteNames.PROMO_DIALOG - override val arguments: Map = mapOf(NavArgs.PROMO_ID to promoId) - override val previewName: String = "PromoDialog($promoId)" + override val routeName: String + get() = RouteNames.PROMO_DIALOG + + override val arguments: Map + get() = mapOf(NavArgs.PROMO_ID to promoId) + + override val previewName: String + get() = "PromoDialog($promoId)" } + @Serializable + @SerialName(RouteNames.SHARE_SHEET) data class ShareSheet(val productId: String) : Nav3Route { - override val routeName: String = RouteNames.SHARE_SHEET - override val arguments: Map = mapOf(NavArgs.PRODUCT_ID to productId) - override val previewName: String = "ShareSheet($productId)" + override val routeName: String + get() = RouteNames.SHARE_SHEET + + override val arguments: Map + get() = mapOf(NavArgs.PRODUCT_ID to productId) + + override val previewName: String + get() = "ShareSheet($productId)" } + @Serializable + @SerialName(Performance.NAME) data class Performance(val index: Int, val generation: Int) : Nav3Route { - override val routeName: String = "Performance" - override val arguments: Map = mapOf("index" to index, "generation" to generation) - override val previewName: String = "Performance($index:$generation)" - override val performanceSeed: Int = 31 * index + generation + override val routeName: String + get() = NAME + + override val arguments: Map + get() = mapOf("index" to index, "generation" to generation) + + override val previewName: String + get() = "Performance($index:$generation)" + + override val performanceSeed: Int + get() = 31 * index + generation + + companion object { + const val NAME = "Performance" + } } } diff --git a/sentry-android-integration-tests/settings.gradle.kts b/sentry-android-integration-tests/settings.gradle.kts index 99bc456129f..47a89d0aa23 100644 --- a/sentry-android-integration-tests/settings.gradle.kts +++ b/sentry-android-integration-tests/settings.gradle.kts @@ -51,6 +51,7 @@ dependencyResolutionManagement { // gradle.properties links to the SDK build's, so versionName is the SDK version. version("sentry", providers.gradleProperty("versionName").get()) } + create("matrixLibs") { from(files("../gradle/dependency-matrix.versions.toml")) } } } @@ -66,3 +67,4 @@ include("sentry-uitest-android") include("sentry-uitest-android-critical") include("sentry-uitest-android-macrobenchmark") include("test-app-size") +include("nav3-backstack-entry-mapper-r8-check") diff --git a/sentry-android-navigation3/README.md b/sentry-android-navigation3/README.md index 95bbbeb006b..2135233aefd 100644 --- a/sentry-android-navigation3/README.md +++ b/sentry-android-navigation3/README.md @@ -6,7 +6,7 @@ Use `SentryNavEffect` alongside your `NavDisplay` to record navigation transacti users move around your app. Configure the data you want captured via `SentryNavOptions`. Because Nav3 back stacks can have arbitrary key types, host apps need to provide `SentryNavEffect` with a mapping between their back stack -keys and the data Sentry should display for each (see `BackStackEntryMapper`). +keys and the data Sentry should display for each (see `BackStackEntryMapper` and the built-in `SerialName` mapper). See the [Navigation for Android docs](https://docs.sentry.io/platforms/android/integrations/navigation/) for additional details, including configuration, supported setups, and limitations. diff --git a/sentry-android-navigation3/api/sentry-android-navigation3.api b/sentry-android-navigation3/api/sentry-android-navigation3.api index 45f0482ed82..04c3349cd46 100644 --- a/sentry-android-navigation3/api/sentry-android-navigation3.api +++ b/sentry-android-navigation3/api/sentry-android-navigation3.api @@ -1,7 +1,12 @@ public abstract interface class io/sentry/compose/navigation3/BackStackEntryMapper { + public static final field Companion Lio/sentry/compose/navigation3/BackStackEntryMapper$Companion; public abstract fun map (Ljava/lang/Object;)Lio/sentry/compose/navigation3/SentryBackStackEntry; } +public final class io/sentry/compose/navigation3/BackStackEntryMapper$Companion { + public final fun getSerialName ()Lio/sentry/compose/navigation3/BackStackEntryMapper; +} + public final class io/sentry/compose/navigation3/BuildConfig { public static final field BUILD_TYPE Ljava/lang/String; public static final field DEBUG Z diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index 7a6cf51d181..7555dee9d3b 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -7,6 +7,7 @@ plugins { alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.compose) alias(libs.plugins.gradle.versions) + alias(libs.plugins.kotlin.serialization) id("io.sentry.detekt") id("io.sentry.spotless") id("io.sentry.jdk-target") @@ -15,6 +16,8 @@ plugins { id("io.sentry.robolectric") } +val kotlinxSerializationFloor = matrixLibs.versions.kotlinxSerialization.floor.get() + android { compileSdk = libs.versions.compileSdk.get().toInt() namespace = "io.sentry.compose.navigation3" @@ -45,6 +48,8 @@ android { // AGP 9.5 can't create the Compose Preview task without it, which breaks any // build that creates every task, such as an LSP's Gradle import. isIncludeAndroidResources = true + // Lets tests check that MIN_KOTLINX_SERIALIZATION_VERSION matches the catalog's floor. + all { it.systemProperty("nav3.kotlinxSerializationFloor", kotlinxSerializationFloor) } } } @@ -72,12 +77,35 @@ android { kotlin { explicitApi() } +// Unit tests run against the kotlinx.serialization floor by default. CI also runs them against the +// latest stable release and any newer release candidate (-Pnav3TestKotlinxVersion=), as +// apps may ship a newer kotlinx.serialization dependency than sentry-android-navigation3 compiles +// against. +val testKotlinxVersion = + providers.gradleProperty("nav3TestKotlinxVersion").orNull ?: kotlinxSerializationFloor + dependencies { implementation(projects.sentry) compileOnly(libs.androidx.lifecycle.runtime.compose) compileOnly(libs.androidx.compose.runtime) compileOnly(libs.androidx.compose.ui) + // Every Nav3 release depends on kotlinx.serialization (navigation3-runtime declares the floor, + // 1.7.3, directly), so this never raises a Nav3 app's version. It guarantees the built-in + // mappers' classes are present for apps that use this module without Nav3. A minimum, as the + // version is + // published: strictly() would force it on apps. + implementation(matrixLibs.kotlinxSerialization.core) { + version { require(kotlinxSerializationFloor) } + } + // Compiles against exactly the floor. Strict, as other compile dependencies (e.g., Compose UI + // via savedstate) also bring in kotlinx.serialization. With a mere minimum, a bump of one of + // those could silently raise the version we compile against, and the same source could then + // compile to calls that the floor version's runtime lacks. compileOnly, so it isn't published. + // verifyKotlinxSerializationCompileVersion checks the result. + compileOnly(matrixLibs.kotlinxSerialization.core) { + version { strictly(kotlinxSerializationFloor) } + } testImplementation(projects.sentryAndroidCore) testImplementation(projects.sentryTestSupport) @@ -88,11 +116,137 @@ dependencies { testImplementation(libs.androidx.viewpager2) testImplementation(libs.google.truth) testImplementation(libs.kotlin.test.junit) + testImplementation(matrixLibs.kotlinxSerialization.core) { + // A minimum, not strictly(), so that a test dependency that needs a newer version (e.g., a + // future Nav3) raises the resolved version instead of being silently downgraded, and + // verifyKotlinxSerializationTestVersion fails. + version { require(testKotlinxVersion) } + } testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) testImplementation(libs.roboelectric) } +/** + * Registers a task that fails the build if [configurationName] resolves kotlinx-serialization-core + * to any version other than [expectedVersion], naming the dependencies that requested another one. + * [problem] describes why the version matters, and [fix] what to do if it's wrong. + */ +fun registerKotlinxSerializationVersionCheck( + name: String, + configurationName: String, + expectedVersion: String, + problem: String, + fix: String, +) = + tasks.register(name) { + val resolution = + configurations.named(configurationName).flatMap { classpath -> + classpath.incoming.resolutionResult.rootComponent.map { root -> + val resolved = sortedSetOf() + val requests = sortedSetOf() + val visited = mutableSetOf() + fun visit(component: ResolvedComponentResult) { + if (!visited.add(component)) return + val id = component.id + if ( + id is ModuleComponentIdentifier && + id.group == "org.jetbrains.kotlinx" && + id.module.startsWith("kotlinx-serialization-core") + ) { + resolved += "${id.module}:${id.version}" + } + for (dependency in component.dependencies) { + val requested = dependency.requested.displayName + if ( + "org.jetbrains.kotlinx:kotlinx-serialization-core" in requested && + !dependency.isConstraint && + !requested.endsWith(":$expectedVersion") && + // kotlinx-serialization-core requests its own -jvm variant. + !id.displayName.startsWith("org.jetbrains.kotlinx:kotlinx-serialization-core") + ) { + requests += "${dependency.from.id.displayName} requests $requested" + } + when (dependency) { + is ResolvedDependencyResult -> visit(dependency.selected) + is UnresolvedDependencyResult -> + if ("kotlinx-serialization-core" in requested) { + resolved += "$requested (unresolved)" + } + } + } + } + visit(root) + listOf(resolved.toList(), requests.toList()) + } + } + inputs.property("expectedVersion", expectedVersion) + inputs.property("resolution", resolution) + doLast { + val (resolved, requests) = resolution.get() + val unexpected = resolved.filterNot { it.endsWith(":$expectedVersion") } + check(resolved.isNotEmpty() && unexpected.isEmpty()) { + "$problem, but $configurationName resolved " + + "${resolved.ifEmpty { listOf("no kotlinx-serialization-core") }}" + + (if (requests.isEmpty()) "" else " (${requests.joinToString("; ")})") + + ". $fix" + } + } + } + +/** + * Fails the build if the release compile classpath resolves kotlinx.serialization to any version + * other than the floor, e.g., because another dependency declared a conflicting strict version or a + * resolution rule forced one. We must compile against the floor, as that's the oldest runtime the + * module promises to work with. + */ +val verifyKotlinxSerializationCompileVersion = + registerKotlinxSerializationVersionCheck( + name = "verifyKotlinxSerializationCompileVersion", + configurationName = "releaseCompileClasspath", + expectedVersion = kotlinxSerializationFloor, + problem = + "sentry-android-navigation3 must compile against kotlinx.serialization " + + "$kotlinxSerializationFloor (the kotlinxSerialization-floor in " + + "gradle/dependency-matrix.versions.toml)", + fix = "Find what changed the version, e.g., a strict version or a resolution rule.", + ) + +/** + * Fails the build if the unit tests would run against a kotlinx.serialization version other than + * the one under test, e.g., because a test dependency such as Nav3 now requires a newer one. The + * tests would then not test that version, and a pin that downgraded the dependency instead would + * run it on a version it doesn't support, which no real app can have. + */ +val verifyKotlinxSerializationTestVersion = + registerKotlinxSerializationVersionCheck( + name = "verifyKotlinxSerializationTestVersion", + configurationName = "releaseUnitTestRuntimeClasspath", + expectedVersion = testKotlinxVersion, + problem = "The unit tests must run against kotlinx.serialization $testKotlinxVersion", + fix = + "If a test dependency (e.g., navigation3-runtime) now requires a newer version, test the " + + "floor with the newest release of that dependency that accepts the floor, as apps on " + + "older releases still run the floor. Raise kotlinxSerialization-floor only to drop " + + "support for those apps. See \"Version floor\" in the kotlinx package README.", + ) + +tasks + .named { it == "compileReleaseKotlin" } + .configureEach { + dependsOn(verifyKotlinxSerializationCompileVersion) + } + +tasks + .named { it == "testReleaseUnitTest" } + .configureEach { + dependsOn(verifyKotlinxSerializationTestVersion) + } + +tasks.named("check") { + dependsOn(verifyKotlinxSerializationCompileVersion, verifyKotlinxSerializationTestVersion) +} + tasks.withType().configureEach { // Target version of the generated JVM bytecode. It is used for type resolution. jvmTarget = JavaVersion.VERSION_1_8.toString() diff --git a/sentry-android-navigation3/proguard-rules.pro b/sentry-android-navigation3/proguard-rules.pro index 244282115a5..ed816f5b2bd 100644 --- a/sentry-android-navigation3/proguard-rules.pro +++ b/sentry-android-navigation3/proguard-rules.pro @@ -5,3 +5,16 @@ -keepattributes LineNumberTable,SourceFile ##---------------End: proguard configuration for Compose ---------- + +##---------------Begin: proguard configuration for the kotlinx.serialization compatibility probe ---------- + +# The probe looks up this SDK-owned fixture's serializer by reflection, as the built-in mappers look +# up those of apps' back stack entries. kotlinx.serialization's rules before 1.10.0 keep an object's +# serializer() only while its INSTANCE field is kept, and R8 full mode removes INSTANCE here, as the +# SDK only refers to the object's class. The probe would then be inconclusive for object lookups. +-keepclassmembers class io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe$Companion$ProbeObject { + public static ** INSTANCE; + kotlinx.serialization.KSerializer serializer(...); +} + +##---------------End: proguard configuration for the kotlinx.serialization compatibility probe ---------- diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt index b977c6fccc9..46da46219b9 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackEntryMapper.kt @@ -1,5 +1,6 @@ package io.sentry.compose.navigation3 +import io.sentry.compose.navigation3.internal.backstack.BuiltInBackStackEntryMappers import org.jetbrains.annotations.ApiStatus /** Info about a given back stack entry, suitable for display in Sentry. */ @@ -53,12 +54,16 @@ public class SentryBackStackEntry( /** * Maps a back stack entry to a displayable name and optional diagnostic arguments. * - * To be implemented by the host app. + * If you use kotlinx.serialization, see [SerialName] for convenient, out-of-the-box mappers. + * Otherwise, provide your own implementation. (Note: Custom implementations can always fall back to + * `SerialName` for any entries that don't have to be special-cased.) * * **Privacy / PII** * - * Values returned from [map] are ***not*** scrubbed by the Sentry SDK before being sent to Sentry. - * Only return names and arguments that are known to be safe or have been pre-scrubbed. + * Custom mappers are responsible for filtering their own arguments. + * + * Only return names and arguments that are known to be safe or have been pre-scrubbed. All + * arguments remain subject to size and structural limits. * * **Performance** * @@ -83,6 +88,13 @@ public class SentryBackStackEntry( * `/detail` throws, the back stack record will be `/home -> /unknown -> /settings` rather than * `/home -> /settings`. * + * Each "/unknown" entry records why it has no name, as `unknown_entry_reason` in the back stack + * record and navigation transactions, and as `to_unknown_entry_reason` or + * `from_unknown_entry_reason` on breadcrumbs (e.g., `"unknown_entry_reason": "unmapped"`): + * `mapping_failed` if [map] threw, `blank_name` for a blank name, and `unmapped` if [map] returned + * `null`. The built-in mappers record more specific reasons when they return `null` (see + * [SerialName]), and so does a custom mapper that returns the `null` a built-in mapper returned. + * * **Choosing appropriate arguments** * * Argument values may be any of the following scalar types: @@ -113,41 +125,93 @@ public class SentryBackStackEntry( * arguments are cyclic, too deeply nested, or too large, or contain a map with two keys that are * stringified the same way (e.g., `1` and `"1"`). If the SDK drops an entry's arguments, it adds a * `dropped_by_sentry` field and corresponding reason (e.g., `duplicate_key`) in the Sentry UI. - * - * **Using kotlinx.serialization** - * - * If your back stack contains `@Serializable` entry types, consider giving each entry an explicit - * `@SerialName` and using its `descriptor.serialName`. For performance reasons, don't serialize - * back stack keys in their entirety as `arguments` if they might be large, deeply nested, or - * contain PII or other sensitive information. - * - * For instance: - * ```kotlin - * @Serializable - * @SerialName("Home") - * data class Home(val userName: String) : NavKey - * - * @Serializable - * @SerialName("ProductDetail") - * data class ProductDetail(val userName: String, val productId: String) : NavKey - * - * ... - * - * val backStackItemMapper = BackStackEntryMapper { entry -> - * when (entry) { - * is Home -> SentryBackStackEntry(Home.serializer().descriptor.serialName) - * is ProductDetail -> SentryBackStackEntry( - * name = ProductDetail.serializer().descriptor.serialName, - * // Select a subset of diagnostic arguments when serialization is unsafe - * // or non-performant. - * arguments = mapOf("product_id" to entry.productId) - * ) - * ... - * } - * } - * ``` */ @ApiStatus.Experimental -public fun interface BackStackEntryMapper { +public fun interface BackStackEntryMapper { + public fun map(backStackEntry: T): SentryBackStackEntry? + + public companion object { + + /** + * A convenience [BackStackEntryMapper] for apps that use kotlinx.serialization and only need to + * track the serial name of each of their back stack entries (and not each entry's properties). + * + * For instance, given: + * ``` + * @Serializable + * @SerialName("ProductDetail") + * data class ProductDetail( + * val userId: String, + * val productId: String + * ) : NavKey + * ``` + * + * when navigating to `ProductDetail(userId = "123abc", productId = "zyx987")`, this mapper + * would return `"ProductDetail"` as the destination's name, but would ***not*** return the + * destination's properties (`userId` and `productId`). + * + * **Name == SerialDescriptor.serialName** + * + * This mapper names each back stack entry after the entry's + * [`SerialDescriptor.serialName`][kotlinx.serialization.descriptors.SerialDescriptor.serialName], + * i.e.: + * + * - the entry's `@SerialName` if it has one; or else + * - the entry's fully qualified class name (e.g., "com.example.Home"). + * + * **Unknown names** + * + * This mapper returns `null` for an entry, which Sentry displays as `"/unknown"`, with the + * `unknown_entry_reason` in parentheses, if: + * + * - the entry class isn't annotated with `@Serializable` itself, even if kotlinx.serialization + * can serialize it without the annotation (e.g., `String`, `List`, an unannotated enum, or a + * class marked with a custom `@MetaSerializable` annotation) (`not_serializable`); + * + * - the entry class is generic (e.g., `SettingsScreen`), as its serializer needs type + * arguments that can't be recovered from the entry at runtime (`generic_type`); + * + * - looking up the entry's serializer finds none, e.g., because R8 removed what the lookup + * needs (`serializer_not_found`), or throws, e.g., because a custom serializer throws + * (`serializer_lookup_threw`); or + * + * - the app's kotlinx.serialization version is incompatible with this SDK, in which case every + * entry is unnamed (`kotlinx_serialization_version`). + * + * `serializer_not_found` often only happens in minified release builds. In particular, if the + * app is minified by R8 and uses a kotlinx.serialization version below 1.10.0, an entry class + * with a named companion object (e.g., `companion object Factory`) may be named in unminified + * debug builds but not in minified release builds, depending on the kotlinx.serialization + * version and R8 mode. To fix this, upgrade kotlinx.serialization to 1.10.0 or later, or add + * the keep rules from Troubleshooting (linked below). + * + * The first entry of each class that can't be named logs a warning explaining why, visible when + * the SDK's `debug` option is enabled. For fixes, see + * [Troubleshooting](https://docs.sentry.io/platforms/android/integrations/navigation/#troubleshooting-kotlinxserialization-mappers) + * in the Sentry Android Navigation docs. + * + * **Sharing names** + * + * Entries share a Sentry name whenever their serializers share a serial name. In particular: + * + * - All constants of an enum are named after the enum. A `@SerialName` on a constant does not + * change the destination name. + * + * - Classes that use the same custom serializer (`@Serializable(with = ...)`) are named after + * that serializer's descriptor, which ignores a `@SerialName` on the class. + * + * To tell such entries apart, define a custom [BackStackEntryMapper], e.g., one that names enum + * constants after [Enum.name]. + * + * **One-time setup** + * + * Reading this mapper (e.g., to pass it to [SentryNavEffect]) does no work. Its first [map] + * call does a one-time setup, which checks the app's kotlinx.serialization version, so that + * call takes longer than later ones. [SentryNavEffect] makes that call when it first records + * the back stack, after composition. + */ + public val SerialName: BackStackEntryMapper + get() = BuiltInBackStackEntryMappers.serialName + } } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt index 0646c13ad90..8de067601a1 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt @@ -33,9 +33,7 @@ import org.jetbrains.annotations.ApiStatus * // destination are attributed to the appropriate nav transaction. * SentryNavEffect( * backStack = navBackStack, - * backStackEntryMapper = { entry -> - * SentryBackStackEntry(entry.toName(), entry.extractArguments()) - * }, + * backStackEntryMapper = BackStackEntryMapper.SerialName, * options = SentryNavOptions(), * ) * @@ -57,6 +55,9 @@ import org.jetbrains.annotations.ApiStatus * - a screen name * - a record of the current back stack (last 5 entries) * + * A destination that can't be named is recorded as "/unknown", with a reason why. See + * [BackStackEntryMapper]. + * * You can configure the above defaults via [SentryNavOptions]. (Screen names can be disabled via * [SentryOptions.setEnableScreenTracking].) * @@ -80,7 +81,10 @@ import org.jetbrains.annotations.ApiStatus * [Navigation for Android docs](https://docs.sentry.io/platforms/android/integrations/navigation/#supported-setups) * for a detailed list of supported vs unsupported configurations. * - * @param backStack The navigation backstack to observe. + * @param backStack The navigation backstack to observe: your list of back stack keys (e.g., the one + * you pass to `NavDisplay`'s `backStack`). Don't pass `NavEntry`s, such as those returned by + * `rememberDecoratedNavEntries` for `NavDisplay`'s `entries` overload. They aren't your keys, so + * [BackStackEntryMapper.SerialName] can't name them and records every screen as "/unknown". * @param backStackEntryMapper Maps each entry of the [backStack] to a name and optional arguments * for display in Sentry. See the [BackStackEntryMapper] KDoc for best practices. * @param options The kinds of navigation info this effect should record. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt new file mode 100644 index 00000000000..8b56ad7be92 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentConversion.kt @@ -0,0 +1,461 @@ +package io.sentry.compose.navigation3.internal.backstack + +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import java.util.IdentityHashMap + +/** + * The core contract for the subsystem that converts properties of back stack entries into Sentry + * arguments. + * + * An [ArgumentSource] pushes information about back stack properties into this sink. Sink + * implementations are expected to materialize the provided info into a tree of Sentry arguments, + * where the tree has a bounded size and height. + * + * **The argument conversion subsystem** + * + * With Nav3, host apps manage their own nav back stack, which they implement as a list of + * arbitrarily typed entries. In order to be displayed in Sentry, each of those entries has to be + * mapped to a Sentry name (e.g., ProductDetailScreen) and zero or more arguments (e.g., productId) + * via a `BackStackEntryMapper`. + * + * `ArgumentSink` and `ArgumentSource` create the seam that lets us support variable processing on + * the source side (e.g., a plain map supplied by the host app vs. arguments that write themselves) + * but uniform processing on the sink side (argument pruning, protecting against constraint + * violation, and tree materialization). + * + * Here are the moving parts: + * ```text + * ArgumentSource + * ┌────────────────────┐ + * │ HostArgumentSource │ + * │ (plain host map) │ + * └─────────┬──────────┘ + * ▼ + * ┌───────────────────────────────┐ + * │ ArgumentSink │ + * └───────────────────────────────┘ + * ▲ sole impl + * ┌───────────────┴───────────────┐ + * │ TreeArgumentWriter │ + * │ │ ┌────────────────┐ + * │ Enforce + materialize: │ spends ──▶│ ArgumentBudget │ + * │ • builds the argument tree │ └────────────────┘ + * │ • prevents constraint │ ┌────────────────┐ + * │ violation (e.g., cycles) │ throws ──▶│ DropArguments │ + * └───────────────────────────────┘ └────────────────┘ + * + * Note: BackStackConverter.ArgumentSanitizer owns the ArgumentBudget and + * selects the ArgumentSource based on what the host app provides. + * ``` + * + * Receives one back stack entry's arguments as a [source][ArgumentSource] produces them, enforcing + * the argument limits as it goes. + * + * Throws [DropArguments] when a write violates a constraint or [reject] is called. Every write + * thereafter will also throw. + */ +internal interface ArgumentSink { + + /** + * The first [DropArguments] thrown either by a write constraint violation or by a call to + * [reject]; `null` if neither has occurred. + * + * Preserves the original drop reason even if intervening code (e.g., a host app serializer) + * catches it and throws its own exception instead. + */ + val failure: DropArguments? + + /** + * Throws [failure], if there is one. + * + * The recorded failure always wins: code that catches an exception while writing calls this + * before handling the exception itself, as intervening code (e.g., host app code) may have caught + * the original [DropArguments] and thrown something else, and the recorded reason decides whether + * older entries keep their arguments. + */ + fun throwIfFailed() { + failure?.let { throw it } + } + + /** + * Starts a map as the next value. [identity] is the object being written, if any, so that one + * that contains itself is rejected instead of written until a limit is reached. + * + * Call [end] when finished. + */ + fun beginMap(identity: Any? = null) + + /** + * Starts a list as the next value. [identity] is as for [beginMap]. + * + * Call [end] when finished. + */ + fun beginList(identity: Any? = null) + + /** + * Names the next value in the current map. If the map already has a value named [name], writing + * the next value throws [DropArguments]. + * + * [describeDuplicate], if provided, returns the warning to log in that case instead of + * [DropArguments.DUPLICATE_KEY_WARNING]. It's only called for a duplicate, so it may do work that + * would be wasteful for every key, e.g., finding the key that [name] collides with. + */ + fun key(name: String, describeDuplicate: (() -> String)? = null) + + /** + * Writes [value] as the next value. Supports `null`, [Boolean], [Number], [CharSequence], and + * [Char]; text is recorded as a [String]. + */ + fun scalar(value: Any?) + + /** + * Writes the value [compute] returns as the next value, as for [scalar]. + * + * By default, computes the value first and then writes it through [scalar], so nothing is checked + * before [compute] runs. [TreeArgumentWriter] overrides this to check that the value can be + * written before calling [compute], so that host app code (e.g., a `toString()`) doesn't run for + * a value that won't be recorded, and can't replace the limit's drop reason with its own failure. + * A sink that wraps another must forward this method to keep that check. + */ + fun computedScalar(compute: () -> Any?) { + scalar(compute()) + } + + /** Ends the most recently started map or list. */ + fun end() + + /** + * Reports the violation of a constraint that a source enforces itself, rather than one broken via + * a write (e.g., how deeply serializers nest), and throws the resulting [DropArguments]. + * + * If a constraint was already violated, throws that instead. + */ + fun reject(reason: ArgumentDropReason, warning: String): Nothing +} + +/** + * Writes a back stack entry's arguments to an [ArgumentSink]. + * + * Sources decide which data to expose and whether to filter sensitive values. The sink applies size + * and structural limits without performing sensitive-data filtering. + */ +internal interface ArgumentSource { + fun writeTo(sink: ArgumentSink) +} + +/** + * Materializes an argument tree for a single back stack entry and enforces argument constraints. + * Argument inputs are provided by an [ArgumentSource]. + * + * **Argument constraints** + * + * Rejects cycles, excessive nesting, duplicate keys, and writes that exceed the value or character + * limits in [budget]. Writes in violation of those limits throw [DropArguments], as does [reject] + * for a constraint the source enforces itself. Once thrown, subsequent writes and + * [argumentsOrThrow] rethrow that failure so a source can't accidentally return partial arguments. + * + * [budget] is shared across all back stack entries processed in one update, limiting their combined + * value and character counts. + * + * [rootIdentity] identifies the source object represented by this entry's root argument map, + * allowing references back to that object to be detected as cycles. + */ +@Suppress("TooManyFunctions") +internal class TreeArgumentWriter( + private val budget: ArgumentBudget, + rootIdentity: Any? = null, +) : ArgumentSink { + + private val root = LinkedHashMap() + + /** The open containers, innermost last, with the identity each was written from. */ + private val containers = ArrayList().apply { add(root) } + private val identities = ArrayList().apply { add(rootIdentity) } + private val activeIdentities = + IdentityHashMap().apply { rootIdentity?.let { put(it, Unit) } } + + private var pendingKey: String? = null + private var describePendingDuplicate: (() -> String)? = null + + override var failure: DropArguments? = null + private set + + override fun beginMap(identity: Any?) = guarded { begin(LinkedHashMap(), identity) } + + override fun beginList(identity: Any?) = guarded { begin(ArrayList(), identity) } + + override fun key(name: String, describeDuplicate: (() -> String)?) = guarded { + pendingKey = budget.spendText(name) + describePendingDuplicate = describeDuplicate + } + + override fun scalar(value: Any?) = writeScalar { value } + + override fun computedScalar(compute: () -> Any?) = writeScalar(compute) + + override fun end() = guarded { + check(containers.size > 1) { "end() without an open map or list." } + containers.removeAt(containers.lastIndex) + identities.removeAt(identities.lastIndex)?.let(activeIdentities::remove) + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing { + throwIfFailed() + throw DropArguments(reason, warning).also { failure = it } + } + + /** + * Returns the entry's arguments, or re-throws the [DropArguments] a write threw, even if the + * source caught it. + * + * Should only be called after the [ArgumentSource] has completed all writes and closed every + * nested map and list. + */ + fun argumentsOrThrow(): Map { + throwIfFailed() + return root + } + + /** Adds [container] as the next value, and makes it the container that later writes fill. */ + private fun begin(container: Any, identity: Any?) { + visitValue() + if (identity != null && activeIdentities.put(identity, Unit) != null) { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + add(container) + containers += container + identities += identity + } + + /** + * Checks the value about to be added before it's computed: enforces the depth limit, rejects a + * key that's already taken, and then spends one value from [budget]. + */ + private fun visitValue() { + // A value added while n containers are open has a depth of n. + if (containers.size > MAX_ARGUMENT_DEPTH) { + throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + val key = pendingKey + val map = containers.last() as? LinkedHashMap<*, *> + if (key != null && map != null && map.containsKey(key)) { + throw duplicateKey() + } + budget.spendValue() + } + + @Suppress("UNCHECKED_CAST") + private fun add(value: Any?) { + when (val parent = containers.last()) { + is ArrayList<*> -> (parent as ArrayList) += value + else -> { + val key = checkNotNull(pendingKey) { "A map value was written without a key." } + (parent as LinkedHashMap)[key] = value + pendingKey = null + describePendingDuplicate = null + } + } + } + + private fun duplicateKey(): DropArguments = + DropArguments( + ArgumentDropReason.DUPLICATE_KEY, + describePendingDuplicate?.invoke() ?: DropArguments.DUPLICATE_KEY_WARNING, + ) + + private inline fun writeScalar(compute: () -> Any?) = guarded { + visitValue() + add( + when (val value = compute()) { + null, + is Boolean -> value + // JSON has no NaN or infinity, and Sentry's JSON writer throws for them, which would drop + // the whole event these arguments are attached to. We record them as strings instead. + is Number -> if (value.isNonFinite()) budget.spendText(value.toString()) else value + is CharSequence -> budget.spendText(value) + is Char -> budget.spendText(value.toString()) + else -> + throw IllegalArgumentException("Unsupported scalar of type ${value.javaClass.name}.") + }, + ) + } + + private inline fun guarded(write: () -> Unit) { + throwIfFailed() + try { + write() + } catch (e: DropArguments) { + failure = e + throw e + } + } +} + +/** + * Writes a host app's argument map to an [ArgumentSink]. + * + * Nested maps are traversed recursively, collections and arrays become lists, and enums use their + * names. Map keys and unsupported values are stringified; unsupported types are reported to + * [onUnsupportedValue]. + * + * Traversal and string conversion may invoke host app code. + */ +internal class HostArgumentSource( + private val arguments: Map<*, *>, + private val onUnsupportedValue: (typeName: String?) -> Unit, +) : ArgumentSource { + + override fun writeTo(sink: ArgumentSink) { + writeEntries(arguments, sink) + } + + private fun writeEntries(map: Map<*, *>, sink: ArgumentSink) { + for ((key, value) in map) { + val name = key.toString() + sink.key(name) { duplicateKeyWarning(map, key, name) } + write(value, sink) + } + } + + /** + * Names only the colliding keys' types, as the keys themselves may contain host data. Collisions + * are rare, so we re-scan [map] instead of tracking the original keys of every map. + */ + private fun duplicateKeyWarning(map: Map<*, *>, key: Any?, name: String): String { + val otherKey = map.keys.firstOrNull { it !== key && it.toString() == name } + return "A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same " + + "string as another key (${otherKey?.let { it::class.simpleName }}). Dropping this " + + "entry's arguments." + } + + private fun write(value: Any?, sink: ArgumentSink) { + val collection = value?.asCollectionOrNull() + when { + value is Map<*, *> -> { + sink.beginMap(identity = value) + writeEntries(value, sink) + sink.end() + } + collection != null -> { + sink.beginList(identity = value) + // Iterated without reading the collection's size, which the host app controls. + for (element in collection) { + write(element, sink) + } + sink.end() + } + // Computed only once the sink has checked the value fits, as it may run host app code. + else -> sink.computedScalar { scalarOf(value) } + } + } + + private fun scalarOf(value: Any?): Any? = + when (value) { + null, + is Boolean, + is Number, + is CharSequence, + is Char -> value + is Enum<*> -> value.name + else -> { + onUnsupportedValue(value::class.simpleName) + value.toString() + } + } +} + +/** Returns this collection, or this array as a list, or `null` if it's neither. */ +private fun Any.asCollectionOrNull(): Collection<*>? = + when (this) { + is Collection<*> -> this + is Array<*> -> asList() + is BooleanArray -> asList() + is ByteArray -> asList() + is ShortArray -> asList() + is IntArray -> asList() + is LongArray -> asList() + is FloatArray -> asList() + is DoubleArray -> asList() + is CharArray -> asList() + else -> null + } + +/** + * Control-flow signal to drop an entry's arguments. Overrides [fillInStackTrace] to skip + * stack-trace capture. + * + * [warning] is logged when the arguments are dropped. Use `null` if no warning is needed, for + * example when the source already logged the failure. + */ +internal class DropArguments( + val reason: ArgumentDropReason, + val warning: String?, +) : RuntimeException() { + + override fun fillInStackTrace(): Throwable = this + + companion object { + + const val DUPLICATE_KEY_WARNING = + "Nav3 map keys stringify to the same string. Dropping this entry's arguments." + + const val MAX_CHARACTER_WARNING = + "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + + "this and older entries." + + const val MAX_COUNT_WARNING = + "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + + "and older entries." + + const val STRUCTURE_WARNING = + "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + + "entry's arguments." + } +} + +/** + * The value and character budgets shared by the entries of one back stack update. Throws + * [DropArguments] when a value or text doesn't fit in what's left. + */ +internal class ArgumentBudget { + + private var remainingValues = MAX_ARGUMENT_VALUES + private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + + /** Spends one value. */ + fun spendValue() { + if (--remainingValues < 0) { + throw DropArguments(ArgumentDropReason.MAX_COUNT, DropArguments.MAX_COUNT_WARNING) + } + } + + /** Returns [text] after spending its characters. */ + fun spendText(text: String): String { + checkFits(text.length) + remainingCharacters -= text.length + return text + } + + /** + * Returns [text] as a [String] after spending its characters. + * + * Checks [text]'s length before converting it, so that host app text that doesn't fit isn't + * copied, and again after, in case a custom [CharSequence]'s length doesn't match its text. + */ + fun spendText(text: CharSequence): String { + checkFits(text.length) + return spendText(text.toString()) + } + + private fun checkFits(characters: Int) { + if (characters > remainingCharacters) { + throw DropArguments(ArgumentDropReason.CHARACTER_LIMIT, DropArguments.MAX_CHARACTER_WARNING) + } + } +} + +/** Whether this is a NaN or infinite `Double` or `Float`. */ +private fun Number.isNonFinite(): Boolean = + (this is Double && !isFinite()) || (this is Float && !isFinite()) 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 e15194da1c2..bb0b0a689cb 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 @@ -5,13 +5,10 @@ import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH -import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.backstack.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY import io.sentry.util.ExceptionUtils -import java.util.IdentityHashMap /** * Converts the host app back stack into a list of [NormalizedSentryBackStackEntry]s. @@ -69,21 +66,24 @@ internal class BackStackConverter( sanitizer: ArgumentSanitizer, warningState: WarningState, ): NormalizedSentryBackStackEntry { - val info = + val (info, reportedReason) = try { - entryMapper.map(backStackEntry) + UnknownEntryReasonReports.collect { entryMapper.map(backStackEntry) } } catch (t: Throwable) { // Back stack entry mappers are host app callbacks. ExceptionUtils.rethrowIfFatal(t) warningState.logMapperFailureWarning(logger, t) return NormalizedSentryBackStackEntry( name = UNKNOWN_ENTRY_NAME, - argumentDropReason = ArgumentDropReason.MAPPING_FAILED, + unknownEntryReason = UnknownEntryReason.MAPPING_FAILED, ) } if (info == null) { - return NormalizedSentryBackStackEntry(name = UNKNOWN_ENTRY_NAME) + return NormalizedSentryBackStackEntry( + name = UNKNOWN_ENTRY_NAME, + unknownEntryReason = reportedReason ?: UnknownEntryReason.UNMAPPED, + ) } val sanitizedArguments = @@ -101,6 +101,7 @@ internal class BackStackConverter( name = UNKNOWN_ENTRY_NAME, arguments = sanitizedArguments.values, argumentDropReason = sanitizedArguments.dropReason, + unknownEntryReason = UnknownEntryReason.BLANK_NAME, ) } else { NormalizedSentryBackStackEntry( @@ -139,27 +140,37 @@ internal class BackStackConverter( ) /** - * Sanitizes a back stack entry's arguments and writes them in a serializable form. It bounds - * depth and total value count, and it rejects cyclic structures. + * Sanitizes a back stack entry's raw argument inputs and returns them in a + * [serializable form][SanitizedArguments.values]. * - * One instance is shared across every entry in a single [convert] call, so the value budget is - * enforced across the whole update. Once the budget is spent, the overflowing entry and every - * older entry are dropped, while newer (already-processed) entries are preserved. + * Internally, this class processes argument inputs returned by the [entryMapper] passed to the + * outer converter instance. Those inputs can come from built-in or custom + * [BackStackEntryMapper]s. + * + * Built-in mappers supply their own [ArgumentSource], while custom mappers typically supply an + * ordinary map. [HostArgumentSource] adapts ordinary maps to the [ArgumentSource] contract, so + * both paths can be handled by the same processing pipeline. */ internal class ArgumentSanitizer( private val logger: ILogger, private val warningState: WarningState, ) { - private val activeContainers = IdentityHashMap() - private var remainingValues = MAX_ARGUMENT_VALUES - private var remainingCharacters = MAX_ARGUMENT_CHARACTERS + // One instance per sanitizer, so the budgets span every entry of a back stack update. + private val budget = ArgumentBudget() private var dropReason: ArgumentDropReason? = null /** - * Sanitizes one entry's arguments, or returns an empty map to drop them, either because the - * structure is cyclic or too deeply nested (this entry only), or because the shared per-update - * value budget is spent (this entry and every older one). + * Sanitizes one entry's raw argument inputs and returns the result. + * + * [SanitizedArguments.values] will be empty if [raw] is empty or if the arguments were dropped. + * Arguments can be dropped if: + * + * - a previously processed entry exceeded the shared value or character budget; + * - an argument constraint is violated; or + * - conversion fails. + * + * [SanitizedArguments.dropReason] will be non-null if and only if arguments are dropped. */ @Suppress("TooGenericExceptionCaught") fun sanitizeEntry(raw: Map): SanitizedArguments { @@ -167,161 +178,37 @@ internal class BackStackConverter( return SanitizedArguments(emptyMap(), reason) } + // Use the raw inputs' own source implementation when available; otherwise, provide them with + // an adapter. + val source = + raw as? ArgumentSource + ?: HostArgumentSource(raw) { warningState.logUnsupportedValueWarning(it, logger) } + val sink = TreeArgumentWriter(budget, rootIdentity = raw) + + // A constraint violation the sink recorded takes precedence over whatever the source threw, + // as for ArgumentSink.throwIfFailed. Here it's the reason the arguments are dropped with. return try { - SanitizedArguments(sanitizeMap(raw, depth = 0)) - } catch (drop: DropSubtree) { - if (drop.reason.exhaustsUpdateBudget) { - dropReason = drop.reason - } - logger.log(WARNING, drop.warning) - SanitizedArguments(emptyMap(), drop.reason) + source.writeTo(sink) + SanitizedArguments(sink.argumentsOrThrow()) + } catch (drop: DropArguments) { + drop(sink.failure ?: drop) } catch (t: Throwable) { // Extracted maps may invoke host app code while iterating or stringifying values. ExceptionUtils.rethrowIfFatal(t) - logger.log(WARNING, STRUCTURE_WARNING, t) - SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) - } - } - - private fun sanitizeMap(value: Map<*, *>, depth: Int): Map { - enter(value) - try { - val sanitized = mutableMapOf() - for ((key, childValue) in value) { - val keyString = key.toString() - consumeCharacters(keyString.length) - if (sanitized.containsKey(keyString)) { - // Types only b/c key strings may contain host data. Collisions are rare, so we re-scan - // instead of tracking original keys for every map. - val otherKey = value.keys.firstOrNull { it !== key && it.toString() == keyString } - throw DropSubtree( - "A Nav3 map key (${key?.let { it::class.simpleName }}) stringifies to the same " + - "string as another key (${otherKey?.let { it::class.simpleName }}). " + - "Dropping this entry's arguments.", - ArgumentDropReason.DUPLICATE_KEY, - ) - } - sanitized[keyString] = sanitizeValue(childValue, depth + 1) - } - return sanitized - } finally { - exit(value) - } - } - - private fun sanitizeCollection(value: Collection<*>, depth: Int): List { - enter(value) - try { - // The value budget bounds allocation instead of the caller-provided collection size. - val sanitized = mutableListOf() - for (childValue in value) { - sanitized += sanitizeValue(childValue, depth + 1) + sink.failure?.let { + return drop(it) } - return sanitized - } finally { - exit(value) - } - } - - private fun sanitizeValue(value: Any?, depth: Int): Any? { - visit(depth) - val collection = value?.asSanitizableCollectionOrNull() - - return when { - value is Map<*, *> -> sanitizeMap(value, depth) - collection != null -> sanitizeCollection(collection, depth) - else -> sanitizeScalar(value) - } - } - - private fun sanitizeScalar(value: Any?): Any? = - when (value) { - null, - is Boolean -> value - is Number -> - if (value.isNonFinite()) { - value.toString().also { consumeCharacters(it.length) } - } else value - is String -> value.also { consumeCharacters(it.length) } - is CharSequence, - is Char -> value.toString().also { consumeCharacters(it.length) } - is Enum<*> -> value.name.also { consumeCharacters(it.length) } - else -> { - warningState.logUnsupportedValueWarning(value::class.simpleName, logger) - value.toString().also { consumeCharacters(it.length) } - } - } - - private fun Any.asSanitizableCollectionOrNull(): Collection<*>? = - when (this) { - is Collection<*> -> this - is Array<*> -> asList() - is BooleanArray -> asList() - is ByteArray -> asList() - is ShortArray -> asList() - is IntArray -> asList() - is LongArray -> asList() - is FloatArray -> asList() - is DoubleArray -> asList() - is CharArray -> asList() - else -> null - } - - /** - * Records a visit to one value, enforcing the per-entry depth cap and the shared per-update - * value budget. Throws [DropSubtree] to abort the current subtree when either is exceeded. - */ - private fun visit(depth: Int) { - if (depth > MAX_ARGUMENT_DEPTH) { - throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE) - } - if (--remainingValues < 0) { - throw DropSubtree(MAX_COUNT_WARNING, ArgumentDropReason.MAX_COUNT) - } - } - - private fun consumeCharacters(count: Int) { - if (count > remainingCharacters) { - throw DropSubtree(MAX_CHARACTER_WARNING, ArgumentDropReason.CHARACTER_LIMIT) + logger.log(WARNING, DropArguments.STRUCTURE_WARNING, t) + SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED) } - remainingCharacters -= count } - private fun enter(container: Any) { - if (activeContainers.put(container, Unit) != null) { - throw DropSubtree(STRUCTURE_WARNING, ArgumentDropReason.INVALID_STRUCTURE) + private fun drop(drop: DropArguments): SanitizedArguments { + if (drop.reason.exhaustsUpdateBudget) { + dropReason = drop.reason } - } - - private fun exit(container: Any) { - activeContainers.remove(container) - } - - /** - * Control-flow signal to abort sanitization of the current subtree. Internal to - * [ArgumentSanitizer]. - * - * [reason] distinguishes entry-local drops from update-wide budget exhaustion. Overrides - * [fillInStackTrace] to skip stack-trace capture. - */ - private class DropSubtree(val warning: String, val reason: ArgumentDropReason) : - RuntimeException() { - override fun fillInStackTrace(): Throwable = this - } - - companion object { - - const val MAX_CHARACTER_WARNING = - "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + - "this and older entries." - - const val MAX_COUNT_WARNING = - "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + - "and older entries." - - const val STRUCTURE_WARNING = - "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + - "entry's arguments." + drop.warning?.let { logger.log(WARNING, it) } + return SanitizedArguments(emptyMap(), drop.reason) } } @@ -383,6 +270,8 @@ internal data class NormalizedSentryBackStackEntry( * The reason why the SDK dropped host-provided arguments, or null if no arguments were dropped. */ val argumentDropReason: ArgumentDropReason? = null, + /** Why the entry was recorded as [UNKNOWN_ENTRY_NAME], or `null` if it has a name. */ + val unknownEntryReason: UnknownEntryReason? = null, ) { companion object { @@ -424,13 +313,32 @@ internal data class NormalizedSentryBackStackEntry( * } * } * ``` + * + * An unnamed entry also has its [unknownEntryReason], e.g.: + * ``` + * { + * "entry": "/unknown" + * "unknown_entry_reason": "not_serializable" + * } + * ``` */ fun serialize(): Map = buildMap { put("entry", name) + unknownEntryReason?.let { put(UNKNOWN_ENTRY_REASON_KEY, it.serializedValue) } argumentsWithMetadata().takeIf { it.isNotEmpty() }?.let { put("entry_arguments", it) } } } +/** + * Returns the data to set on the nav transaction of a destination this entry is the top of: its + * `arguments`, as for [NormalizedSentryBackStackEntry.argumentsWithMetadata], and its + * `unknown_entry_reason`, each if it has any. + */ +internal fun NormalizedSentryBackStackEntry.transactionData(): Map = buildMap { + argumentsWithMetadata().takeIf { it.isNotEmpty() }?.let { put("arguments", it) } + unknownEntryReason?.let { put(UNKNOWN_ENTRY_REASON_KEY, it.serializedValue) } +} + internal fun List.serialize(): List> = map(NormalizedSentryBackStackEntry::serialize) @@ -443,7 +351,6 @@ internal enum class ArgumentDropReason( CHARACTER_LIMIT("max_character_limit_exceeded", exhaustsUpdateBudget = true), DUPLICATE_KEY("duplicate_key"), INVALID_STRUCTURE("invalid_structure"), - MAPPING_FAILED("mapping_failed"), MAX_COUNT("max_argument_count_exceeded", exhaustsUpdateBudget = true), SANITIZATION_FAILED("sanitization_failed"); @@ -451,7 +358,3 @@ internal enum class ArgumentDropReason( const val ARGUMENT_DROP_REASON_KEY = "dropped_by_sentry" } } - -/** Whether this is a NaN or infinite Double or Float. */ -private fun Number.isNonFinite(): Boolean = - (this is Double && !isFinite()) || (this is Float && !isFinite()) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt index 988000c6b67..7eb12b4459b 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserver.kt @@ -15,6 +15,7 @@ import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.Reten import io.sentry.compose.navigation3.internal.backstack.PreparedChange.BackStackHasNewTop import io.sentry.compose.navigation3.internal.backstack.PreparedChange.BackStackHasSameTop import io.sentry.compose.navigation3.internal.backstack.PreparedChange.BackStackIsEmpty +import io.sentry.compose.navigation3.internal.backstack.UnknownEntryReason.Companion.UNKNOWN_ENTRY_REASON_KEY import io.sentry.compose.navigation3.internal.lifecycle.INavScope import io.sentry.compose.navigation3.internal.lifecycle.INavScopes import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_CONTEXT_KEY @@ -237,7 +238,7 @@ internal class BackStackObserver( return NavTransactionRequest.forDestination( name = top.name, - arguments = top.argumentsWithMetadata(), + data = top.transactionData(), contexts = navContext.forTransaction(backStack.capturedEntriesNormalized), viewNames = if (scopes.options.isEnableScreenTracking) listOf(top.name) else null, options = scopes.options, @@ -362,6 +363,9 @@ private class NavBreadcrumbs(private val scopes: INavScopes) { fromEntry?.let { entry -> data["from"] = entry.name + entry.unknownEntryReason?.let { + data["from_$UNKNOWN_ENTRY_REASON_KEY"] = it.serializedValue + } entry .argumentsWithMetadata() .takeIf { it.isNotEmpty() } @@ -371,6 +375,9 @@ private class NavBreadcrumbs(private val scopes: INavScopes) { } data["to"] = toEntry.name + toEntry.unknownEntryReason?.let { + data["to_$UNKNOWN_ENTRY_REASON_KEY"] = it.serializedValue + } toEntry .argumentsWithMetadata() .takeIf { it.isNotEmpty() } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt new file mode 100644 index 00000000000..98a61fa7f53 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt @@ -0,0 +1,119 @@ +package io.sentry.compose.navigation3.internal.backstack + +import androidx.annotation.VisibleForTesting +import io.sentry.ILogger +import io.sentry.ScopesAdapter +import io.sentry.SentryLevel.WARNING +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap + +internal object BuiltInBackStackEntryMappers { + + private val logger: () -> ILogger = { ScopesAdapter.getInstance().options.logger } + + /** + * A built-in [BackStackEntryMapper] for apps that use kotlinx.serialization and only need to + * track the serial name of each of their back stack entries (and not each entry's properties). + * + * The kotlinx mapper is created when this first maps an entry; see + * [DeferredBackStackEntryMapper]. Falls back to [UnavailableBackStackEntryMapper] if it can't be + * created. + * + * See [BackStackEntryMapper.SerialName] for more details. + */ + val serialName: BackStackEntryMapper = DeferredBackStackEntryMapper { + create(logger) { KotlinxBackStackEntryMapper(logger = logger) } + } + + /** + * Returns the mapper created by [newKotlinxMapper], or an [UnavailableBackStackEntryMapper] if + * the mapper can't be linked or initialized. + */ + @VisibleForTesting + fun create( + logger: () -> ILogger, + newKotlinxMapper: () -> BackStackEntryMapper, + ): BackStackEntryMapper { + return try { + newKotlinxMapper() + } catch (e: LinkageError) { + // An incompatible kotlinx.serialization version can throw a LinkageError while the mapper is + // created, either because a class the mapper uses can't be linked or because the mapper's + // compatibility probe failed to look up names. We catch the error here so that every entry + // falls back to UNKNOWN_ENTRY_NAME instead of crashing the app. + // + // Construction runs no host app code, only kotlinx.serialization's and the SDK's, so this + // also catches an ExceptionInInitializerError from either. We fall back rather than crash, + // and log the error for diagnosis. + logger() + .log( + WARNING, + // The compiler inlines INCOMPATIBLE_KOTLINX_ADVICE, and its use here doesn't access any + // kotlinx.serialization code. + "Nav3 built-in mapper creation failed. Using $UNKNOWN_ENTRY_NAME for all entries. See " + + "the attached error. $INCOMPATIBLE_KOTLINX_ADVICE", + e, + ) + UnavailableBackStackEntryMapper(logger) + } + } +} + +/** + * A built-in [BackStackEntryMapper] that creates the mapper it delegates to when it first maps an + * entry, rather than when the app reads it. + * + * Apps read the built-in mappers while composing, e.g., as an argument to `SentryNavEffect`. + * Creating a mapper looks up serializers by reflection and may log. Deferring that work to the + * first [map] call keeps it out of composition, which Compose may discard, and runs it where + * `SentryNavEffect` maps entries: in an effect, after the composition is applied, where a failure + * only affects the entries being mapped. + * + * If [create] throws, [map] throws too, and the next [map] call tries to create the mapper again. + */ +internal class DeferredBackStackEntryMapper( + create: () -> BackStackEntryMapper, +) : BackStackEntryMapper { + + // PUBLICATION avoids holding a lock while mapper creation calls the app's logger. Threads that + // race on the first map() may each create and probe a mapper and log warnings, but all of them + // use the instance published first. + private val mapper by lazy(LazyThreadSafetyMode.PUBLICATION, create) + + override fun map(backStackEntry: Any): SentryBackStackEntry? = mapper.map(backStackEntry) +} + +/** + * A fallback for when a built-in [BackStackEntryMapper] isn't supported by the host app. + * + * Maps every back stack entry to `null`, which Sentry records as [UNKNOWN_ENTRY_NAME] with + * [UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION]. Logs once per entry type. + */ +internal class UnavailableBackStackEntryMapper( + private val logger: () -> ILogger, +) : BackStackEntryMapper { + + private val loggedTypes = Collections.newSetFromMap(ConcurrentHashMap, Boolean>()) + + override fun map(backStackEntry: Any): SentryBackStackEntry? { + val type = backStackEntry.javaClass + + if (loggedTypes.add(type)) { + logger() + .log( + WARNING, + "Nav3 mapper unavailable for type %s. Using $UNKNOWN_ENTRY_NAME. Use a custom " + + "BackStackEntryMapper.", + type.name, + ) + } + + UnknownEntryReasonReports.report(UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION) + return null + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/UnknownEntryReason.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/UnknownEntryReason.kt new file mode 100644 index 00000000000..4d00672d2f0 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/UnknownEntryReason.kt @@ -0,0 +1,91 @@ +package io.sentry.compose.navigation3.internal.backstack + +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME + +/** + * Why a back stack entry was recorded as [UNKNOWN_ENTRY_NAME], recorded next to it under + * [UNKNOWN_ENTRY_REASON_KEY] (prefixed with `to_` or `from_` on breadcrumbs) so that the reason + * reaches Sentry without debug logs. + * + * Values contain no app data or class names. + */ +internal enum class UnknownEntryReason(val serializedValue: String) { + + /** The mapper returned a name that's empty after trimming. The entry's arguments are kept. */ + BLANK_NAME("blank_name"), + + /** A built-in mapper can't name the entry, as its `@Serializable` class has type parameters. */ + GENERIC_TYPE("generic_type"), + + /** + * The built-in mappers couldn't be created, as the app's kotlinx.serialization version can't be + * linked or failed their compatibility check. + */ + KOTLINX_SERIALIZATION_VERSION("kotlinx_serialization_version"), + + /** The mapper threw. */ + MAPPING_FAILED("mapping_failed"), + + /** A built-in mapper can't name the entry, as its class isn't annotated with `@Serializable`. */ + NOT_SERIALIZABLE("not_serializable"), + + /** + * A built-in mapper can't name the entry, as reading its class's annotations, serializer, or + * descriptor threw. + */ + SERIALIZER_LOOKUP_THREW("serializer_lookup_threw"), + + /** + * A built-in mapper can't name the entry, as looking up its `@Serializable` class's serializer + * found none, e.g., because R8 removed what the lookup needs. + */ + SERIALIZER_NOT_FOUND("serializer_not_found"), + + /** + * The mapper returned `null` without a built-in mapper reporting why, i.e., a custom mapper chose + * not to name the entry. + */ + UNMAPPED("unmapped"); + + companion object { + const val UNKNOWN_ENTRY_REASON_KEY: String = "unknown_entry_reason" + } +} + +/** + * Passes the [UnknownEntryReason] a built-in [BackStackEntryMapper] knows to the back stack + * converter, as the mapper reports a failure by returning `null`, which is public API. + * + * A built-in mapper [report]s the reason right before returning `null`, and the converter + * [collect]s it around each call to the app's mapper. So a custom mapper that forwards a built-in + * mapper's `null` forwards its reason too, while one that returns `null` itself reports nothing, + * and one that returns a name has its reason ignored. If a custom mapper calls built-in mappers + * several times for one entry, the last reason reported is kept. + * + * Kept per thread, as mappers run on the converter's thread. + */ +internal object UnknownEntryReasonReports { + + private val reported = ThreadLocal() + + /** Reports why the built-in mapper that's about to return `null` can't name its entry. */ + fun report(reason: UnknownEntryReason) { + reported.set(reason) + } + + /** + * Runs [map] and returns its result with the last reason reported while it ran, or `null` if none + * was. Clears the report before and after, even if [map] throws, so a reason can't carry over to + * another entry. + */ + fun collect(map: () -> R): Pair { + reported.remove() + try { + val result = map() + return result to reported.get() + } finally { + reported.remove() + } + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt new file mode 100644 index 00000000000..a6cf856d5e3 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapper.kt @@ -0,0 +1,378 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.ILogger +import io.sentry.SentryLevel.DEBUG +import io.sentry.SentryLevel.WARNING +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import io.sentry.compose.navigation3.internal.backstack.UnknownEntryReason +import io.sentry.compose.navigation3.internal.backstack.UnknownEntryReasonReports +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.util.ExceptionUtils +import java.lang.reflect.GenericSignatureFormatError +import java.lang.reflect.InvocationTargetException +import java.lang.reflect.MalformedParameterizedTypeException +import java.util.concurrent.ConcurrentHashMap +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable + +/** Implementation of [BackStackEntryMapper.SerialName]. */ +internal class KotlinxBackStackEntryMapper( + /** + * Returns the serializer of a back stack entry's `@Serializable` class, or `null` if there's none + * (e.g. for a generic class). Only called for classes marked `@Serializable`. + * + * May throw, as the lookup can run the app's serializer code for the first time. + */ + private val lookUpSerializer: (Class<*>) -> KSerializer<*>? = ::reflectiveSerializerOrNull, + logger: () -> ILogger, + probe: KotlinxCompatibilityProbe = KotlinxCompatibilityProbe, + /** + * Whether a back stack entry's class is annotated with `@Serializable`. + * + * May throw, as reading the class's annotations can fail. + */ + private val isAnnotatedSerializable: (Class<*>) -> Boolean = serializableAnnotationCheck(), +) : BackStackEntryMapper { + + // Serializer lookups use reflection and mapping runs on every navigation, so we cache each + // class's name. Cache size is bounded by the number of back stack entry types. + private val types = ConcurrentHashMap, CachedType>() + + private val diagnostics = KotlinxMapperDiagnostics(logger) + + init { + // Check name-lookup support during construction so an incompatible kotlinx.serialization + // version triggers the use of UnavailableBackStackEntryMapper. Later LinkageErrors likely come + // from the entry's own type and are handled per type. + probe + .nameLookupLinkageError { error -> + diagnostics.inconclusiveProbe(NAME_LOOKUP_CAPABILITY, error) + } + ?.let { throw it } + } + + override fun map(backStackEntry: Any): SentryBackStackEntry? { + // An enum constant with a body is an instance of an anonymous subclass, which isn't + // @Serializable itself, so we look up the enum class instead. + val type = (backStackEntry as? Enum<*>)?.declaringJavaClass ?: backStackEntry.javaClass + val cached = + when (val cachedType = cachedType(type)) { + is CachedType.Resolved -> cachedType + is CachedType.Unresolved -> { + UnknownEntryReasonReports.report(cachedType.reason) + return null + } + } + + return SentryBackStackEntry(cached.name) + } + + private fun cachedType(type: Class<*>): CachedType = + // getOrPut may look up a type more than once if threads race on its first entry. That can cause + // a failed lookup to be logged more than once, but only one result will ever be cached. + types.getOrPut(type) { lookUp(type) } + + /** + * Looks up [type]'s serializer and name. Logs if it can't be named. + * + * Never throws for a non-fatal error. Instead, a lookup that fails returns + * [CachedType.Unresolved] with the reason, which [cachedType] caches, so each type's failure is + * queried and logged only once. + */ + @OptIn(ExperimentalSerializationApi::class) + private fun lookUp(type: Class<*>): CachedType { + preLookupProblem(type)?.let { + return CachedType.Unresolved(it) + } + + // Serializer lookup and descriptor access may run host app code. Failures affect only this + // type. + val serializer = + when (val lookup = lookUpSerializerCatching(type)) { + is SerializerLookup.Found -> lookup.serializer + is SerializerLookup.NotFound -> { + diagnostics.unresolved(type, lookup.error) + return CachedType.Unresolved( + if (lookup.error == null) { + UnknownEntryReason.SERIALIZER_NOT_FOUND + } else { + UnknownEntryReason.SERIALIZER_LOOKUP_THREW + }, + ) + } + } + + return try { + CachedType.Resolved(serializer.descriptor.serialName) + } catch (e: LinkageError) { + // Treat descriptor linkage errors as type-specific, including incompatibilities caused by a + // serializer compiled against another kotlinx.serialization version. + diagnostics.unresolved(type, e) + CachedType.Unresolved(UnknownEntryReason.SERIALIZER_LOOKUP_THREW) + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Custom descriptors may throw anything. Catch broadly to log once and cache the type as + // unresolved, avoiding repeated lookups. Entries use UNKNOWN_ENTRY_NAME. + ExceptionUtils.rethrowIfFatal(t) + diagnostics.unresolved(type, t) + CachedType.Unresolved(UnknownEntryReason.SERIALIZER_LOOKUP_THREW) + } + } + + /** + * Returns why [type] can't be named before looking up its serializer, logging it, or `null` if + * the lookup should decide. + * + * The annotation is checked first, as the lookup would otherwise return serializers for types + * that aren't `@Serializable`. Generic types are checked next: the lookup can't find their + * serializers either, and this way the reason and the warning say why. + */ + private fun preLookupProblem(type: Class<*>): UnknownEntryReason? = + serializableAnnotationProblem(type) + ?: if (isGeneric(type)) { + diagnostics.genericType(type) + UnknownEntryReason.GENERIC_TYPE + } else { + null + } + + /** + * Returns why [type] can't be named if it isn't annotated with `@Serializable` or its annotations + * can't be read, logging it, or `null` if it's annotated. + * + * We only name types the host app marks as `@Serializable`. kotlinx.serialization provides + * serializers for built-in types (e.g. String, Int) and enums, but their serial names would be + * misleading ("kotlin.String") or derived from an obfuscated class name. + */ + private fun serializableAnnotationProblem(type: Class<*>): UnknownEntryReason? = + try { + if (isAnnotatedSerializable(type)) { + null + } else { + diagnostics.notSerializable(type) + UnknownEntryReason.NOT_SERIALIZABLE + } + } catch (e: LinkageError) { + // As for the serializer lookup, a LinkageError from reading this type's annotations only + // fails this type. + diagnostics.unresolved(type, e) + UnknownEntryReason.SERIALIZER_LOOKUP_THREW + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Catch broadly because annotation parsing has undocumented failure modes. Cache failures as + // unresolved so the type records UNKNOWN_ENTRY_NAME and logs once, rather than throwing from + // map() and retrying on every navigation. + ExceptionUtils.rethrowIfFatal(t) + diagnostics.unresolved(type, t) + UnknownEntryReason.SERIALIZER_LOOKUP_THREW + } + + /** + * Whether [type] has type parameters, so its serializer needs type arguments that can't be + * recovered from an entry at runtime. + * + * `false` if its generic signature can't be read, e.g., because it's malformed, so that the + * lookup decides. R8 may also remove generic signatures, which also leaves the lookup to decide, + * as it can't find a generic class's serializer either. + */ + private fun isGeneric(type: Class<*>): Boolean = + try { + type.typeParameters.isNotEmpty() + } catch (_: GenericSignatureFormatError) { + false + } catch (_: MalformedParameterizedTypeException) { + false + } catch (_: TypeNotPresentException) { + false + } + + /** + * Looks up [type]'s serializer, returning the error that made it fail, if any, instead of + * throwing it. + */ + private fun lookUpSerializerCatching(type: Class<*>): SerializerLookup = + try { + lookUpSerializer(type)?.let(SerializerLookup::Found) + ?: SerializerLookup.NotFound(error = null) + } catch (e: InvocationTargetException) { + // kotlinx.serialization (or our fallback for private objects) calls the type's + // generated serializer() method reflectively, and it threw. For instance, a custom + // serializer object whose initializer throws arrives here with an + // ExceptionInInitializerError as its cause. Only this type is affected. + val cause = e.cause ?: e + // Reflection wraps everything the method throws, fatal errors included, so we apply the + // SDK's fatal-error check to the cause. A LinkageError cause (e.g., that + // ExceptionInInitializerError) only fails this type, so it's exempt. + if (cause !is LinkageError) { + ExceptionUtils.rethrowIfFatal(cause) + } + SerializerLookup.NotFound(cause) + } catch (e: ReflectiveOperationException) { + // Any other reflective failure is specific to this type's serializer members. + SerializerLookup.NotFound(e) + } catch (e: LinkageError) { + // The creation-time probe checks library compatibility. A later LinkageError may come + // from this type's serializer or its dependencies, so cache it as unresolved without + // disabling other types. Catch before rethrowIfFatal, which rethrows LinkageErrors. + SerializerLookup.NotFound(e) + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because the lookup reflects over the app's classes, and the reflection and + // annotation APIs it uses can throw unchecked exceptions of their own (e.g., a + // TypeNotPresentException when R8 removed the serializer a @Serializable(with = ...) + // names). Without this catch, the exception would escape map() uncached and the lookup + // would be repeated on every navigation. Instead, the type is cached as unresolved and + // recorded as UNKNOWN_ENTRY_NAME, with the error logged once. + ExceptionUtils.rethrowIfFatal(t) + SerializerLookup.NotFound(t) + } + + /** What [lookUp] found for a back stack entry type, cached so each type is looked up once. */ + private sealed interface CachedType { + + /** A type that can be named, and its [name]. */ + class Resolved(val name: String) : CachedType + + /** + * A type that can't be named, e.g., because it isn't `@Serializable` or reading its serializer + * failed. Its entries are recorded as [UNKNOWN_ENTRY_NAME], with [reason]. + */ + class Unresolved(val reason: UnknownEntryReason) : CachedType + } + + /** The result of looking up a type's serializer. */ + private sealed interface SerializerLookup { + + class Found(val serializer: KSerializer<*>) : SerializerLookup + + /** + * No serializer was found. [error] is what made the lookup fail, or `null` if the lookup found + * none without throwing (e.g., for a generic class). + */ + class NotFound(val error: Throwable?) : SerializerLookup + } + + internal companion object { + /** The capability the name lookup check verifies, as its inconclusive log names it. */ + const val NAME_LOOKUP_CAPABILITY: String = "name lookups" + + /** Returns whether a class is annotated with `@Serializable`. */ + private fun serializableAnnotationCheck(): (Class<*>) -> Boolean { + // Resolved here, when the mapper is created, rather than on the first map() call, so that if + // the annotation class can't be linked, creating this mapper fails and + // BuiltInBackStackEntryMappers falls back to UnavailableBackStackEntryMapper. + val serializableAnnotation: Class = Serializable::class.java + return { type -> type.isAnnotationPresent(serializableAnnotation) } + } + } +} + +/** + * The warnings [KotlinxBackStackEntryMapper] logs when it can't name a back stack entry. + * + * Only decides what's logged. Whether a type is looked up again is up to the mapper. + */ +internal class KotlinxMapperDiagnostics(private val logger: () -> ILogger) { + + /** Logs that entries of [type] can't be named because the type isn't `@Serializable`. */ + fun notSerializable(type: Class<*>) { + logger() + .log( + WARNING, + "Nav3 can't name entries of type %s because the type is not @Serializable. Using " + + "$UNKNOWN_ENTRY_NAME. Add @Serializable or use a custom BackStackEntryMapper.", + type.name, + ) + } + + /** + * Logs that entries of [type] can't be named because the type is generic, so its serializer needs + * type arguments that can't be recovered from an entry. + */ + fun genericType(type: Class<*>) { + logger() + .log( + WARNING, + "Nav3 can't name entries of type %s because the type has type parameters. Using " + + "$UNKNOWN_ENTRY_NAME. Use a custom BackStackEntryMapper.", + type.name, + ) + } + + /** + * Logs that the probe couldn't verify support for [capability], due to [error] or a missing probe + * serializer if the error is `null`. The mapper handles subsequent failures per type. + */ + fun inconclusiveProbe(capability: String, error: Throwable?) { + // DEBUG b/c an inconclusive probe doesn't affect what's recorded. + logger() + .log( + DEBUG, + error, + "Nav3 couldn't verify kotlinx.serialization support for %s because %s. Handling " + + "failures per entry type.", + capability, + if (error != null) PROBE_THREW else PROBE_SERIALIZER_NOT_FOUND, + ) + } + + /** + * Logs why [type] can't be named. [error] is what reading its annotations, serializer, or + * descriptor threw, or `null` if the serializer lookup found none without throwing. + * + * [error] is attached as is. Looking up a type's serializer never sees an entry's values, so its + * errors can't contain route data, although their messages can be the app's own text (e.g., from + * a custom serializer or a static initializer). Like the exceptions the app's `beforeSend` + * callback throws, they're logged in full, which only happens with `debug` enabled. + */ + fun unresolved(type: Class<*>, error: Throwable?) { + val reason = if (error != null) LOOK_UP_FAILED else SERIALIZER_NOT_FOUND + val advice = + if (error is LinkageError) { + // The probe can miss an incompatible version, which then fails every type one at a time. + "See the attached error. If all types fail, kotlinx.serialization may be incompatible. " + + INCOMPATIBLE_KOTLINX_ADVICE + } else if (error != null) { + "See the attached error or use a custom BackStackEntryMapper." + } else { + "See BackStackEntryMapper.SerialName's documentation or use a custom BackStackEntryMapper." + } + logger() + .log( + WARNING, + error, + "Nav3 can't name entries of type %s because %s. Using $UNKNOWN_ENTRY_NAME. $advice", + type.name, + reason, + ) + } + + companion object { + + /** Why the compatibility probe was inconclusive, if it threw. */ + const val PROBE_THREW: String = "the compatibility probe threw (see the attached error)" + + /** Why the compatibility probe was inconclusive, if a probe type's serializer wasn't found. */ + const val PROBE_SERIALIZER_NOT_FOUND: String = "a probe serializer wasn't found" + + /** Why a type can't be named, if reading its annotations, serializer, or descriptor threw. */ + const val LOOK_UP_FAILED: String = "reading its annotations, serializer, or descriptor failed" + + /** Why a type can't be named, if its serializer lookup found none without throwing. */ + const val SERIALIZER_NOT_FOUND: String = + "no serializer was found (the type may be generic or require R8 keep rules)" + + /** + * The oldest kotlinx.serialization version [KotlinxBackStackEntryMapper] supports. + * + * Must match `kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`. + */ + const val MIN_KOTLINX_SERIALIZATION_VERSION: String = "1.7.3" + + const val INCOMPATIBLE_KOTLINX_ADVICE: String = + "Requires kotlinx.serialization $MIN_KOTLINX_SERIALIZATION_VERSION or later. " + + "Upgrade kotlinx.serialization or the Sentry SDK. If both are current, report this at " + + "https://github.com/getsentry/sentry-java/issues/new/choose. Use a custom " + + "BackStackEntryMapper as a workaround." + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt new file mode 100644 index 00000000000..9656ba3867c --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbe.kt @@ -0,0 +1,126 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.util.ExceptionUtils +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable + +/** + * Checks whether the app's kotlinx.serialization version successfully links against the APIs used + * by [KotlinxBackStackEntryMapper]. It does so via two built-in probe types ([ProbeClass] and + * [ProbeObject]). + * + * **Disambiguating serializer errors from library incompatibility** + * + * Without a check like this, `KotlinxBackStackEntryMapper` would have to infer an incompatible + * kotlinx.serialization version from [LinkageError]s thrown while handling the host app's own back + * stack entry types. But such errors can also come from the host app's serializer code, and should + * therefore only fail for the entry types that can't be deserialized. `ProbeClass` and + * `ProbeObject` don't execute any host app code, so a `LinkageError` while handling them means the + * app's kotlinx.serialization version is incompatible. + * + * Note: Only a `LinkageError` is conclusive. Any other failure, or a probe type whose serializer + * can't be found, leaves the check inconclusive: it's reported to the caller's `onInconclusive` and + * otherwise ignored, as a real type that hits the same failure is handled and logged on its own. + */ +internal interface KotlinxCompatibilityProbe { + + /** + * Verifies [KotlinxBackStackEntryMapper]'s serializer and name lookups with [ProbeClass] and + * [ProbeObject]. + * + * Returns a [LinkageError] if those lookups can't link against the host app's + * kotlinx.serialization version, or `null` if they succeed or the check is inconclusive. + * + * Calls [onInconclusive] for each inconclusive result, passing the cause or `null` if a probe + * type's serializer is unavailable. + */ + fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? + + /** Probes the app's kotlinx.serialization version using [ProbeClass] and [ProbeObject]. */ + companion object : KotlinxCompatibilityProbe { + + override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? = + nameLookupLinkageError(::reflectiveSerializerOrNull, onInconclusive) + + /** + * Like [nameLookupLinkageError], but looks up the probe types' serializers with + * [lookUpSerializer], so tests can make the lookup fail. + */ + internal fun nameLookupLinkageError( + lookUpSerializer: (Class<*>) -> KSerializer<*>?, + onInconclusive: (Throwable?) -> Unit, + ): LinkageError? { + var isSerializerMissing = false + + val error = + probe(onInconclusive) { + val descriptors = + listOf(ProbeClass::class.java, ProbeObject::class.java).map { type -> + lookUpSerializer(type)?.descriptor + } + for (descriptor in descriptors.filterNotNull()) { + descriptor.serialName + descriptor.elementsCount + descriptor.kind + } + isSerializerMissing = null in descriptors + } + + // Call outside probe() so an exception from onInconclusive isn't caught and reported back to + // the same callback. If a serializer is missing, the remaining lookup steps cannot be checked + // for that type. + if (isSerializerMissing) { + onInconclusive(null) + } + return error + } + + /** + * Runs [check], returning any [LinkageError] and rethrowing fatal errors. Returns `null` if the + * check succeeds or is inconclusive. + * + * Reports other errors to [onInconclusive], passing the cause. + */ + private inline fun probe( + onInconclusive: (Throwable) -> Unit, + check: () -> Unit, + ): LinkageError? = + try { + check() + null + } catch (e: LinkageError) { + e + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { + // Broad because the app's kotlinx.serialization version may throw anything. Only + // LinkageError confirms incompatibility. Other non-fatal failures are inconclusive. + // Failures for actual back stack types are handled and logged per type. + ExceptionUtils.rethrowIfFatal(t) + onInconclusive(t) + null + } + + /** + * A known serializable type used to test whether the app's kotlinx.serialization version + * supports serializer lookup, without running host app code. + * + * Internal visibility lets the probe look up its serializer the same way + * [KotlinxBackStackEntryMapper] looks up serializers for the host app's public back stack entry + * types. + */ + @Serializable + internal data class ProbeClass( + val name: String = "probe", + val values: List = listOf(1), + val counts: Map = mapOf("count" to 1), + ) + + /** + * A known serializable object used to test serializer lookup for the host app's object-based + * back stack entries. This lookup reads the object's singleton instance. + */ + @Serializable internal object ProbeObject + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt new file mode 100644 index 00000000000..e1de1e154c5 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookup.kt @@ -0,0 +1,55 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.util.ExceptionUtils +import java.lang.reflect.InvocationTargetException +import kotlinx.serialization.KSerializer +import kotlinx.serialization.serializerOrNull + +/** + * Returns the serializer of [type], or `null` if kotlinx.serialization can't provide one (e.g. for + * a generic class whose serializer needs type arguments). + * + * Unlike kotlinx.serialization's [serializerOrNull], this also finds the serializers of private + * `@Serializable` objects. Like it, this returns serializers for built-in types (e.g. `String`) and + * enums that aren't `@Serializable`. + * + * This method may throw, as looking up a serializer can run the type's serializer code for the + * first time (e.g. an [InvocationTargetException] whose cause is the serializer initializer's + * error). + * + * Reflection wraps whatever that code throws in an [InvocationTargetException], which callers' + * fatal-error checks don't recognize as fatal. So a fatal cause, such as an [OutOfMemoryError], is + * rethrown unwrapped instead. A wrapped [LinkageError] stays wrapped: callers treat a + * [LinkageError] thrown directly as a sign that kotlinx.serialization itself is incompatible, while + * one from the app's serializer code is specific to that type. + */ +@Suppress("SwallowedException") +internal fun reflectiveSerializerOrNull(type: Class<*>): KSerializer<*>? = + try { + try { + serializerOrNull(type) + } catch (_: IllegalAccessException) { + // kotlinx.serialization reads a serializable object's INSTANCE field without making it + // accessible, which fails for private objects. + privateObjectSerializerOrNull(type) + } + } catch (e: InvocationTargetException) { + val cause = e.cause + if (cause != null && cause !is LinkageError) { + ExceptionUtils.rethrowIfFatal(cause) + } + throw e + } + +/** + * Uses reflection to look up the serializer of a private `@Serializable object` through the members + * the serialization compiler plugin generates for it. (kotlinx.serialization's consumer R8 rules + * keep both members.) + * + * Propagates any exception thrown by the reflective lookup. + */ +private fun privateObjectSerializerOrNull(type: Class<*>): KSerializer<*>? { + val instance = type.getDeclaredField("INSTANCE").apply { isAccessible = true }.get(null) + return type.getDeclaredMethod("serializer").apply { isAccessible = true }.invoke(instance) + as? KSerializer<*> +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md new file mode 100644 index 00000000000..57c850c2d1c --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/README.md @@ -0,0 +1,79 @@ +# `io.sentry.compose.navigation3.internal.backstack.kotlinx` + +This package isolates access to kotlinx.serialization APIs. + +## Dependency isolation + +kotlinx.serialization is an `implementation` dependency of `sentry-android-navigation3`, declared as a minimum at the floor, so its classes +are always present. Every Nav3 release depends on the same version via `navigation3-runtime`, so the dependency never raises a Nav3 app's +version. We compile against exactly the floor through a separate, unpublished `compileOnly` declaration. + +The kotlinx.serialization ***version***, however, is determined by the host app, and may be incompatible with the APIs we use. To protect +against crashes, only classes in the `kotlinx` subpackage may reference kotlinx.serialization APIs, and code outside is limited to a single +entry point, viz., `BuiltInBackStackEntryMappers.create`. That's where we catch the `LinkageError` thrown if an incompatible version can't +be linked. + +Creating a mapper runs `KotlinxCompatibilityProbe`'s name lookup on SDK-owned `@Serializable` types, without running app serializers. +A `LinkageError` prevents mapper creation. Other non-fatal lookup failures are inconclusive; mapping continues with failures handled per +entry type. Later name-lookup failures are cached per entry type. + +To keep our isolation policy intact: + +- put any new classes that reference kotlinx.serialization in the `.kotlinx` subpackage and give them a `Kotlinx*` prefix; +- don't expose kotlinx.serialization types outside the `Kotlinx*` classes; and +- reference a `Kotlinx*` class from outside the subpackage only via `BuiltInBackStackEntryMappers.create`. + +In addition, the `.kotlinx` subpackage may ***not*** depend on Android framework APIs, AndroidX, or the `internal.lifecycle` package. + +## Version floor + +The floor (`kotlinxSerialization-floor` in `gradle/dependency-matrix.versions.toml`) is the oldest kotlinx.serialization version our +built-in mappers support. It matches the oldest supported Nav3 release's dependency: 1.7.3 for `navigation3-runtime` 1.0.0. We publish +the floor as a minimum, so raising it upgrades kotlinx.serialization in apps on older Nav3 releases. + +We compile against exactly the floor. `build.gradle.kts` pins it strictly for compiling, as other dependencies also bring in +kotlinx.serialization, and `verifyKotlinxSerializationCompileVersion` fails the build if the compile classpath resolves any other version. +Compiling against a newer version could produce calls the floor's runtime lacks. + +The unit tests run against the floor, or the version `-Pnav3TestKotlinxVersion` names, as a minimum rather than strictly, and +`verifyKotlinxSerializationTestVersion` fails the build if a test dependency raises it. A strict pin would instead silently run that +dependency on a version it doesn't support, which no real app can have. If a test dependency, e.g., `navigation3-runtime`, starts requiring +a newer version, test the floor with the newest release of that dependency that accepts the floor, as apps on its older releases still run +the floor. + +Rules for changing the floor: + +- Raise it only when the oldest supported Nav3 release requires a newer kotlinx.serialization, never as a side effect of another + dependency bump. +- Raise it in a reviewed change of its own, with a CHANGELOG entry and a note in the Nav3 integration docs. +- Update `MIN_KOTLINX_SERIALIZATION_VERSION` in `KotlinxBackStackEntryMapper.kt` to match. A unit test fails if the two differ. +- Support behavior that only newer kotlinx.serialization versions need with a version-specific code path, not by raising the floor. + +## Minification + +`sentry-android-navigation3` ships no rules for apps' kotlinx.serialization classes, only one that keeps the compatibility probe's own +object fixture (see `proguard-rules.pro`). kotlinx.serialization is an `implementation` dependency at the floor, which every Nav3 +release also depends on, so its classes are always present. Serial names survive R8 minification because Kotlin's serialization +compiler plugin fixes them at compile time. `KotlinxBackStackEntryMapper`'s fallback for private `@Serializable` objects +relies on members preserved by kotlinx.serialization's own consumer rules. + +`KotlinxBackStackEntryMapper` only names classes whose `@Serializable` annotation is present at runtime. kotlinx.serialization's consumer +rules (from our 1.7.3 floor on) keep that annotation: `kotlinx-serialization-common.pro` keeps `RuntimeVisibleAnnotations`, and +`kotlinx-serialization-r8.pro` keeps every `@Serializable` class (allowing shrinking and obfuscation) so that R8 full mode doesn't strip +the annotation. kotlinx.serialization relies on the annotation itself, e.g., to pick sealed-class serializers, so an app that disables those +rules breaks kotlinx.serialization as well as our mappers. + +We also don't ship rules for `@Serializable` classes with named companion objects. kotlinx.serialization's rules only cover those from +1.10.0 on. A generic rule set that fixes older versions exists, but we don't apply it because it would keep `InnerClasses` and +named-companion class names in every host app. + +The [R8 check](../../../../../../../../../../../sentry-android-integration-tests/nav3-backstack-entry-mapper-r8-check/README.md) +verifies `SerialName` after minification, including named-companion lookups. + +## Newer versions + +CI also runs all of the module's unit tests (`scripts/test-nav3-kotlinx-versions.sh`), and +`nav3-backstack-entry-mapper-r8-check`, against the latest stable release +(`kotlinxSerialization-stable`, bumped by Dependabot) and any newer release candidate (`kotlinxSerialization-preview`, bumped by a +weekly job in `update-deps.yml`). Release candidate failures block only PRs that change the preview version. For failure handling, +see "When a kotlinx.serialization bump fails" in the R8 check's README. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequest.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequest.kt index ffe39e13d56..d1206937266 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequest.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequest.kt @@ -42,10 +42,13 @@ internal class NavTransactionRequest( private const val TRANSACTION_ORIGIN = "auto.navigation.nav3" - /** Creates a request whose transaction options are read when each transaction starts. */ + /** + * Creates a request whose transaction options are read when each transaction starts, and whose + * transactions get [data] (see [ITransaction.setData]). + */ fun forDestination( name: String, - arguments: Map, + data: Map, contexts: Map, viewNames: List?, options: SentryOptions, @@ -62,7 +65,7 @@ internal class NavTransactionRequest( it.origin = TRANSACTION_ORIGIN } }, - data = if (arguments.isNotEmpty()) mapOf("arguments" to arguments) else emptyMap(), + data = data, contexts = contexts, viewNames = viewNames, ) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt index 2ba320a31e8..122d7161e03 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -4,7 +4,7 @@ import com.google.common.truth.Truth.assertThat import java.io.File import org.junit.Test -/** Enforces the lifecycle package's dependency boundary. */ +/** Enforces internal dependency rules for `sentry-android-navigation3`. */ class PackageBoundariesTest { private val sources: List = @@ -14,6 +14,50 @@ class PackageBoundariesTest { .map(SourceFile::parse) .toList() + @Test + fun `only the kotlinx package may import kotlinx serialization`() { + val otherSources = sources.filterNot { it.packageName.isIn(KOTLINX) } + + val violations = otherSources.importsMatching { it.isIn("kotlinx.serialization") } + + assertThat(otherSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `source files in the kotlinx package have names that start with Kotlinx`() { + val kotlinxSources = sources.filter { it.packageName.isIn(KOTLINX) } + + val violations = kotlinxSources.filterNot { it.name.startsWith("Kotlinx") }.map { it.path } + + assertThat(kotlinxSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `only the kotlinx package and the mapper factory may import the kotlinx package`() { + val otherSources = sources.filterNot { + it.packageName.isIn(KOTLINX) || it.path == MAPPER_FACTORY_PATH + } + + val violations = otherSources.importsMatching { it.isIn(KOTLINX) } + + assertThat(otherSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + @Test + fun `the kotlinx package has no imports from Android, AndroidX, or the lifecycle package`() { + val kotlinxSources = sources.filter { it.packageName.isIn(KOTLINX) } + + val violations = kotlinxSources.importsMatching { + it.isIn("android") || it.isIn("androidx") || it.isIn(LIFECYCLE) + } + + assertThat(kotlinxSources).isNotEmpty() + assertThat(violations).isEmpty() + } + @Test fun `the lifecycle package has no imports from other Sentry navigation3 packages, Compose, or AndroidX Nav3`() { val lifecycleSources = sources.filter { it.packageName.isIn(LIFECYCLE) } @@ -66,6 +110,7 @@ class PackageBoundariesTest { /** A source file's location, package, and import targets. */ private class SourceFile( val path: String, + val name: String, val packageName: String, val imports: List, ) { @@ -77,6 +122,7 @@ class PackageBoundariesTest { val lines = file.readLines().map(String::trim) return SourceFile( path = file.invariantSeparatorsPath, + name = file.name, packageName = lines.firstNotNullOfOrNull { PACKAGE.find(it)?.groupValues?.get(1) }.orEmpty(), imports = lines.mapNotNull { IMPORT.find(it)?.groupValues?.get(1) }, @@ -88,7 +134,10 @@ class PackageBoundariesTest { private companion object { const val SOURCE_ROOT = "src/main/kotlin" const val ROOT = "io.sentry.compose.navigation3" + const val KOTLINX = "$ROOT.internal.backstack.kotlinx" const val LIFECYCLE = "$ROOT.internal.lifecycle" + const val MAPPER_FACTORY_PATH = + "$SOURCE_ROOT/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappers.kt" /** Whether this name is [packageName] or lies inside it. */ fun String.isIn(packageName: String): Boolean = diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt index 850802400a4..b8765b83db0 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt @@ -34,6 +34,8 @@ import io.sentry.SentryTracer import io.sentry.TransactionContext import io.sentry.TransactionOptions import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable import org.junit.Rule import org.junit.Test import org.junit.rules.TestWatcher @@ -75,6 +77,10 @@ class SentryNavEffectTest { private data class ProfileRoute(val userId: String) + @Serializable @SerialName("SerializableHome") private data object SerializableHomeRoute + + @Serializable private data class SerializableProfileRoute(val userId: String) + private class Fixture { val options = SentryOptions().apply { @@ -353,6 +359,43 @@ class SentryNavEffectTest { assertThat(observedTransactionNames).containsExactly("/HomeRoute", "/ProfileRoute").inOrder() } + @Test + fun `SerialName records serial names, and unknown names with their reason for entries that aren't @Serializable`() { + val fixture = Fixture() + val backStack = mutableStateListOf(SerializableHomeRoute) + + composeRule.setContent { + SentryNavEffect( + backStack = backStack, + backStackEntryMapper = BackStackEntryMapper.SerialName, + options = SentryNavOptions(), + scopes = fixture.scopes, + coordinator = fixture.coordinator, + ) + } + composeRule.waitForIdle() + + composeRule.runOnIdle { + backStack.add(SerializableProfileRoute("123")) + backStack.add(ProfileRoute("456")) + } + composeRule.waitForIdle() + + val profileName = "/io.sentry.compose.navigation3.SentryNavEffectTest.SerializableProfileRoute" + assertThat(fixture.breadcrumbs.first().data["to"]).isEqualTo("/SerializableHome") + assertThat(fixture.transactions.first().name).isEqualTo("/SerializableHome") + assertThat(fixture.scope.screen).isEqualTo("/unknown") + assertThat(fixture.breadcrumbs.last().data["to_unknown_entry_reason"]) + .isEqualTo("not_serializable") + assertThat(fixture.scope.navigationBackStack()) + .containsExactly( + mapOf("entry" to "/unknown", "unknown_entry_reason" to "not_serializable"), + mapOf("entry" to profileName), + mapOf("entry" to "/SerializableHome"), + ) + .inOrder() + } + @Test fun `updated entry mapper is used for later navigation changes`() { val fixture = Fixture() diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgetTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgetTest.kt new file mode 100644 index 00000000000..09fed2fb5e0 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgetTest.kt @@ -0,0 +1,63 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import kotlin.test.assertFailsWith +import org.junit.Test + +class ArgumentBudgetTest { + + // spendText(CharSequence) + + @Test + fun `spendText(CharSequence) - returns text exactly as long as the remaining characters as a String`() { + val budget = budgetWithCharactersRemaining(2) + + val spent = budget.spendText(StringBuilder("ab")) + + assertThat(spent).isEqualTo("ab") + } + + @Test + fun `spendText(CharSequence) - spends the characters of the text`() { + val budget = budgetWithCharactersRemaining(2) + budget.spendText(StringBuilder("ab")) + + val drop = assertFailsWith { budget.spendText(StringBuilder("c")) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + } + + @Test + fun `spendText(CharSequence) - spends the characters of the text rather than its reported length`() { + val budget = budgetWithCharactersRemaining(2) + budget.spendText(CountingText(length = 0, text = "ab")) + + val drop = assertFailsWith { budget.spendText(StringBuilder("c")) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + } + + @Test + fun `spendText(CharSequence) - throws for the character limit without converting text that's too long`() { + val budget = budgetWithCharactersRemaining(1) + val text = CountingText(length = 2, text = "ab") + + val drop = assertFailsWith { budget.spendText(text) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + assertThat(text.toStringCalls).isEqualTo(0) + } + + @Test + fun `spendText(CharSequence) - throws for the character limit when text is longer than its reported length`() { + val budget = budgetWithCharactersRemaining(1) + + val drop = + assertFailsWith { budget.spendText(CountingText(length = 1, text = "ab")) } + + assertThat(drop.reason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) + assertThat(drop.warning).isEqualTo(DropArguments.MAX_CHARACTER_WARNING) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt new file mode 100644 index 00000000000..4f77307b74e --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentBudgets.kt @@ -0,0 +1,12 @@ +package io.sentry.compose.navigation3.internal.backstack + +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES + +/** Returns a budget with only [remaining] values left, as if other entries spent the rest. */ +internal fun budgetWithValuesRemaining(remaining: Int): ArgumentBudget = + ArgumentBudget().apply { repeat(MAX_ARGUMENT_VALUES - remaining) { spendValue() } } + +/** Returns a budget with only [remaining] characters left, as if other entries spent the rest. */ +internal fun budgetWithCharactersRemaining(remaining: Int): ArgumentBudget = + ArgumentBudget().apply { spendText("x".repeat(MAX_ARGUMENT_CHARACTERS - remaining)) } 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 d9f0f76864a..7067a8cfc55 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 @@ -16,6 +16,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 { @@ -74,6 +75,88 @@ class ArgumentSanitizerTest { verify(logger, times(1)).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue")) } + // 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 DropArguments(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 DropArguments(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 DropArguments(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(DropArguments.MAX_CHARACTER_WARNING)) + verify(logger, never()).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), any()) + } + + @Test + fun `sanitizeEntry() - records the broken limit when an ArgumentSource replaces it with its own DropArguments`() { + val arguments = overCharacterLimitReplacedWith { + DropArguments(ArgumentDropReason.INVALID_STRUCTURE, warning = null) + } + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + // Dropped arguments @Test @@ -82,7 +165,7 @@ class ArgumentSanitizerTest { val sanitized = sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES) { it })) assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_COUNT_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArguments.MAX_COUNT_WARNING)) } @Test @@ -92,7 +175,7 @@ class ArgumentSanitizerTest { assertThat(sanitized) .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + verify(logger).log(eq(WARNING), eq(DropArguments.MAX_CHARACTER_WARNING)) } @Test @@ -142,6 +225,74 @@ class ArgumentSanitizerTest { assertThat(third).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 `an entry dropped for a duplicate map key doesn't spend the value budget of later entries`() { + // A list and its elements, which leave three values: two for the duplicate entry's nested map + // and its first value, and one for the later entry's value. + sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES - 4) { it })) + + val duplicate = sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", "1" to "b"))) + val later = sanitizer.sanitizeEntry(mapOf("one" to 1)) + + assertThat(duplicate) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.DUPLICATE_KEY)) + assertThat(later).isEqualTo(SanitizedArguments(mapOf("one" to 1))) + } + + @Test + fun `a duplicate map key with no values left drops only that entry, for the duplicate key`() { + // A list and its elements, which leave two values, for the duplicate entry's nested map and its + // first value. + sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES - 3) { it })) + + val duplicate = sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", "1" to "b"))) + val later = sanitizer.sanitizeEntry(emptyMap()) + + assertThat(duplicate) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.DUPLICATE_KEY)) + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), dropReason = null)) + } + // Failures @Test @@ -158,7 +309,7 @@ class ArgumentSanitizerTest { sanitizer.sanitizeEntry(mapOf("throwing" to throwing)) - verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), eq(throwing.failure)) + verify(logger).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), eq(throwing.failure)) } @Test @@ -171,8 +322,7 @@ class ArgumentSanitizerTest { assertFailsWith { sanitizer.sanitizeEntry(mapOf("fatal" to fatal)) } - verify(logger, never()) - .log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), any()) + verify(logger, never()).log(eq(WARNING), eq(DropArguments.STRUCTURE_WARNING), any()) } @Test @@ -195,7 +345,7 @@ class ArgumentSanitizerTest { val later = sanitizer.sanitizeEntry(laterArguments) assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) - verify(logger, times(1)).log(eq(WARNING), eq(ArgumentSanitizer.MAX_COUNT_WARNING)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArguments.MAX_COUNT_WARNING)) } @Test @@ -205,7 +355,45 @@ class ArgumentSanitizerTest { val later = sanitizer.sanitizeEntry(laterArguments) assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) - verify(logger, times(1)).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + verify(logger, times(1)).log(eq(WARNING), eq(DropArguments.MAX_CHARACTER_WARNING)) + } + + @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 DropArguments are dropped`() { + sanitizer.sanitizeEntry( + overCharacterLimitReplacedWith { + DropArguments(ArgumentDropReason.INVALID_STRUCTURE, warning = null) + }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) } @Test @@ -228,6 +416,17 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) } + @Test + fun `an ArgumentSource that drops its arguments for invalid structure doesn't drop later entries`() { + sanitizer.sanitizeEntry( + SelfWritingArguments { throw DropArguments(ArgumentDropReason.INVALID_STRUCTURE, null) }, + ) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + @Test fun `an entry that failed sanitization doesn't drop later entries`() { sanitizer.sanitizeEntry(mapOf("throwing" to ThrowingValue())) @@ -236,4 +435,19 @@ class ArgumentSanitizerTest { assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) } + + /** + * Arguments that write one character more than the character budget, then catch the sink's + * [DropArguments] 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: DropArguments) { + 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 d07f3733118..e9bdff2b289 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 @@ -9,11 +10,10 @@ import io.sentry.SentryLevel.WARNING import io.sentry.SentryOptions import io.sentry.compose.navigation3.BackStackEntryMapper import io.sentry.compose.navigation3.SentryBackStackEntry -import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.RetentionPolicy import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME import java.io.StringWriter -import java.util.AbstractCollection import kotlin.test.assertFailsWith import org.junit.Test import org.mockito.kotlin.any @@ -56,6 +56,13 @@ class BackStackConverterTest { SentryBackStackEntry(entry::class.simpleName ?: "") } + /** Reports a reason and returns `null`, like a built-in mapper that can't name an entry. */ + private val notSerializableMapper = + BackStackEntryMapper { + UnknownEntryReasonReports.report(UnknownEntryReason.NOT_SERIALIZABLE) + null + } + private fun getSut( entryMapper: BackStackEntryMapper = defaultEntryMapper, ): BackStackConverter = @@ -328,12 +335,23 @@ class BackStackConverterTest { } @Test - fun `convert returns unknown name if mapper name is blank`() { + fun `convert returns a named entry without an unnamed reason if mapper returns a name`() { + val sut = getSut() + + assertThat(sut.convert(HomeScreen()).unknownEntryReason).isNull() + } + + @Test + fun `convert returns unknown name with the blank name reason and arguments if mapper name is blank`() { val sut = getSut(entryMapper = { SentryBackStackEntry(" ", mapOf("userId" to "123")) }) assertThat(sut.convert(HomeScreen())) .isEqualTo( - NormalizedSentryBackStackEntry(name = "/unknown", arguments = mapOf("userId" to "123")), + NormalizedSentryBackStackEntry( + name = "/unknown", + arguments = mapOf("userId" to "123"), + unknownEntryReason = UnknownEntryReason.BLANK_NAME, + ), ) verify(logger) .log( @@ -352,167 +370,175 @@ class BackStackConverterTest { } @Test - fun `convert returns unknown name without arguments if mapper returns null`() { + fun `convert returns unknown name with the unmapped reason if mapper returns null without a report`() { val sut = getSut(entryMapper = { null }) assertThat(sut.convert(HomeScreen())) - .isEqualTo(NormalizedSentryBackStackEntry(UNKNOWN_ENTRY_NAME)) + .isEqualTo( + NormalizedSentryBackStackEntry( + UNKNOWN_ENTRY_NAME, + unknownEntryReason = UnknownEntryReason.UNMAPPED, + ), + ) } @Test - fun `convert returns unknown name without arguments if mapper throws`() { - val sut = getSut(entryMapper = { error("boom") }) + fun `convert returns unknown name with the reported reason if mapper reports one and returns null`() { + val sut = getSut(entryMapper = notSerializableMapper) assertThat(sut.convert(HomeScreen())) .isEqualTo( NormalizedSentryBackStackEntry( UNKNOWN_ENTRY_NAME, - argumentDropReason = ArgumentDropReason.MAPPING_FAILED, + unknownEntryReason = UnknownEntryReason.NOT_SERIALIZABLE, ), ) - verify(logger) - .log( - eq(WARNING), - eq(MAPPER_FAILURE_WARNING), - any(), - ) } @Test - fun `convert logs the mapper failure warning once per back stack update`() { - val sut = getSut(entryMapper = { error("boom") }) + fun `convert returns the reported reason if a custom mapper forwards a reporting mapper's null`() { + val sut = getSut(entryMapper = { entry -> notSerializableMapper.map(entry) }) - sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) - - verify(logger, times(1)).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + assertThat(sut.convert(HomeScreen()).unknownEntryReason) + .isEqualTo(UnknownEntryReason.NOT_SERIALIZABLE) } @Test - fun `convert rethrows fatal errors thrown by the mapper`() { - val sut = getSut(entryMapper = { throw StackOverflowError("fatal") }) + fun `convert returns the built-in mapper's reason if a custom mapper forwards SerialName's null`() { + val sut = getSut(entryMapper = { entry -> BackStackEntryMapper.SerialName.map(entry) }) - assertFailsWith { sut.convert(HomeScreen()) } - verify(logger, never()).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + assertThat(sut.convert(HomeScreen())) + .isEqualTo( + NormalizedSentryBackStackEntry( + UNKNOWN_ENTRY_NAME, + unknownEntryReason = UnknownEntryReason.NOT_SERIALIZABLE, + ), + ) } @Test - fun `convert returns arguments in proper serializable form`() { - val text = StringBuilder("hello") + fun `convert returns a named entry if a custom mapper names an entry after a reporting mapper's null`() { val sut = getSut( entryMapper = { entry -> - entryInfo( - entry, - mapOf( - "str" to "hello", - "charSequence" to text, - "char" to 'x', - "num" to 42, - "bool" to true, - "enum" to PrivacyMode.PRIVATE, - "nil" to null, - "nested" to mapOf("inner" to "value"), - "tags" to listOf("a", "b", "c"), - "array" to arrayOf("a", 1, false, PrivacyMode.PUBLIC, 'z'), - "ints" to intArrayOf(1, 2, 3), - "chars" to charArrayOf('a', 'b'), - "bytes" to byteArrayOf(4, 5), - ), - ) + notSerializableMapper.map(entry) ?: SentryBackStackEntry("fallback") }, ) - assertThat(sut.convert(HomeScreen()).arguments) - .isEqualTo( - mapOf( - "str" to "hello", - "charSequence" to "hello", - "char" to "x", - "num" to 42, - "bool" to true, - "enum" to "PRIVATE", - "nil" to null, - "nested" to mapOf("inner" to "value"), - "tags" to listOf("a", "b", "c"), - "array" to listOf("a", 1, false, "PUBLIC", "z"), - "ints" to listOf(1, 2, 3), - "chars" to listOf("a", "b"), - "bytes" to listOf(4.toByte(), 5.toByte()), - ), + assertThat(sut.convert(HomeScreen())) + .isEqualTo(NormalizedSentryBackStackEntry(name = "/fallback")) + } + + @Test + fun `convert returns the unmapped reason if a custom mapper returns null after another mapper names the entry`() { + val sut = + getSut( + entryMapper = { entry -> + defaultEntryMapper.map(entry) + null + }, ) + + assertThat(sut.convert(HomeScreen()).unknownEntryReason).isEqualTo(UnknownEntryReason.UNMAPPED) } @Test - fun `convert sanitizes arguments with nested supported containers recursively`() { + fun `convert does not carry a reported reason over to the next back stack entry`() { val sut = getSut( entryMapper = { entry -> - entryInfo( - entry, - mapOf( - "nested" to - mapOf( - "items" to - arrayOf( - StringBuilder("x"), - listOf('y', PrivacyMode.PRIVATE), - booleanArrayOf(true, false), - charArrayOf('q'), - ), - ), - ), - ) + when (entry) { + is HomeScreen -> notSerializableMapper.map(entry) + else -> null + } }, ) - assertThat(sut.convert(HomeScreen()).arguments) + val routes = sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + + assertThat(routes.map { it.unknownEntryReason }) + .containsExactly(UnknownEntryReason.NOT_SERIALIZABLE, UnknownEntryReason.UNMAPPED) + .inOrder() + } + + @Test + fun `convert returns unknown name with the mapping failed reason and no arguments if mapper throws`() { + val sut = getSut(entryMapper = { error("boom") }) + + assertThat(sut.convert(HomeScreen())) .isEqualTo( - mapOf( - "nested" to - mapOf("items" to listOf("x", listOf("y", "PRIVATE"), listOf(true, false), listOf("q"))), + NormalizedSentryBackStackEntry( + UNKNOWN_ENTRY_NAME, + unknownEntryReason = UnknownEntryReason.MAPPING_FAILED, ), ) + verify(logger) + .log( + eq(WARNING), + eq(MAPPER_FAILURE_WARNING), + any(), + ) } @Test - fun `convert coerces arguments with unsupported values to strings`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" - } + fun `convert returns the mapping failed reason if mapper throws after reporting a reason`() { + val sut = + getSut( + entryMapper = { entry -> + notSerializableMapper.map(entry) + error("boom") + }, + ) - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("bad" to OpaqueValue())) }) + assertThat(sut.convert(HomeScreen()).unknownEntryReason) + .isEqualTo(UnknownEntryReason.MAPPING_FAILED) + } + + @Test + fun `convert logs the mapper failure warning once per back stack update`() { + val sut = getSut(entryMapper = { error("boom") }) + + sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("bad" to "opaque-value")) + verify(logger, times(1)).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) } @Test - fun `convert logs an unsupported value warning once per back stack update`() { - class OpaqueValue { - override fun toString(): String = "opaque-value" - } + fun `convert rethrows fatal errors thrown by the mapper`() { + val sut = getSut(entryMapper = { throw StackOverflowError("fatal") }) + + assertFailsWith { sut.convert(HomeScreen()) } + verify(logger, never()).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + } + @Test + fun `convert returns the mapper's arguments sanitized`() { val sut = getSut( entryMapper = { entry -> - entryInfo( - entry, - when (entry) { - is HomeScreen -> mapOf("bad" to OpaqueValue()) - is ProfileScreen -> mapOf("alsoBad" to OpaqueValue()) - else -> emptyMap() - }, - ) + entryInfo(entry, mapOf("mode" to PrivacyMode.PRIVATE, "ids" to intArrayOf(1, 2))) }, ) - sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + assertThat(sut.convert(HomeScreen()).arguments) + .isEqualTo(mapOf("mode" to "PRIVATE", "ids" to listOf(1, 2))) + } - verify(logger, times(1)) - .log( - eq(WARNING), - eq(UNSUPPORTED_VALUE_WARNING), - eq("OpaqueValue"), + @Test + fun `convert drops the arguments for the character limit without converting mapper text that's too long`() { + val text = CountingText(length = MAX_ARGUMENT_CHARACTERS + 1, text = "short") + val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("title" to text)) }) + + val route = sut.convert(HomeScreen()) + + assertThat(route) + .isEqualTo( + NormalizedSentryBackStackEntry( + "/HomeScreen", + argumentDropReason = ArgumentDropReason.CHARACTER_LIMIT, + ), ) + assertThat(text.toStringCalls).isEqualTo(0) } @Test @@ -533,6 +559,28 @@ class BackStackConverterTest { assertThat(observedReads).isEmpty() } + @Test + fun `convert hides state reads by an ArgumentSource from snapshot observation`() { + val state = mutableStateOf("value") + val arguments = SelfWritingArguments { sink -> + sink.key("state") + sink.scalar(state.value) + } + val sut = getSut(entryMapper = { entry -> entryInfo(entry, arguments) }) + val observedReads = mutableListOf() + val snapshot = Snapshot.takeSnapshot(readObserver = { observedReads += it }) + + val converted = + try { + snapshot.enter { sut.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 { @@ -554,54 +602,6 @@ class BackStackConverterTest { ) } - @Test - fun `convert returns empty arguments for cyclic structures`() { - val cyclic = mutableMapOf() - cyclic["self"] = cyclic - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("cyclic" to cyclic)) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert returns empty arguments for deeply nested structures`() { - var nested: Any? = "value" - repeat(25) { nested = listOf(nested) } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("nested" to nested)) }) - - val entry = sut.convert(ProfileScreen("123")) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.INVALID_STRUCTURE) - } - - @Test - fun `convert drops oversized arguments`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(1_001) { it })) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.MAX_COUNT) - } - - @Test - fun `convert drops arguments when character budget is exceeded`() { - val sut = - getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to "x".repeat(4_097))) }) - - val entry = sut.convert(HomeScreen()) - - assertThat(entry.arguments).isEmpty() - assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) - } - @Test fun `convert starts each back stack update with a fresh argument budget`() { val sut = @@ -614,40 +614,6 @@ class BackStackConverterTest { assertThat(entry.argumentDropReason).isNull() } - @Test - fun `convert reports sanitization failures`() { - class ThrowingValue { - override fun toString(): String = error("boom") - } - - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("value" to ThrowingValue())) }) - - val converted = sut.convert(HomeScreen()) - - assertThat(converted.arguments).isEmpty() - assertThat(converted.argumentDropReason).isEqualTo(ArgumentDropReason.SANITIZATION_FAILED) - } - - @Test - fun `arguments do not use caller collection size for allocation`() { - val values = - object : AbstractCollection() { - var wasSizeRead = false - - override val size: Int - get() { - wasSizeRead = true - return 2 - } - - override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() - } - val sut = getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to values)) }) - - assertThat(sut.convert(HomeScreen()).arguments).isEqualTo(mapOf("values" to listOf(1, 2))) - assertThat(values.wasSizeRead).isFalse() - } - @Test fun `omitted arguments normalize to an empty map`() { val sut = getSut() @@ -710,21 +676,4 @@ class BackStackConverterTest { """{"entry":"/HomeScreen","entry_arguments":{"price":"NaN","limits":["Infinity","-Infinity"]}}""", ) } - - @Test - fun `serialize includes the reason arguments were dropped`() { - val entry = - NormalizedSentryBackStackEntry( - name = "/HomeScreen", - argumentDropReason = ArgumentDropReason.MAX_COUNT, - ) - - assertThat(entry.serialize()) - .isEqualTo( - mapOf( - "entry" to "/HomeScreen", - "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "max_argument_count_exceeded"), - ), - ) - } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserverTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserverTest.kt index 250a0c0ab08..87485ff92ba 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserverTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BackStackObserverTest.kt @@ -664,6 +664,10 @@ class BackStackObserverTest { }, ) + val unknown = NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME + val blankNameEntry = mapOf("entry" to unknown, "unknown_entry_reason" to "blank_name") + val mappingFailedEntry = mapOf("entry" to unknown, "unknown_entry_reason" to "mapping_failed") + // Navigate to the home screen and verify that a transaction has started and related Sentry data // have been generated (i.e., screen name, breadcrumb, and updated back stack context), as the // host app's BackStackEntryMapper returned a valid name for the home screen entry. @@ -676,28 +680,26 @@ class BackStackObserverTest { assertThat(fixture.breadcrumbs).hasSize(1) assertThat(fixture.scope.navigationBackStack()).isEqualTo(listOf(mapOf("entry" to "/home"))) - // Navigate to the profile screen and verify the invalid route name is recorded as /unknown so - // the transition history remains intact. + // Navigate to the profile screen and verify the invalid route name is recorded as /unknown, + // with + // the reason why, so the transition history remains intact. sut.onBackStackChanged(listOf(home, profile)) assertThat(transaction.isFinished).isTrue() assertThat(fixture.startedTransactions).hasSize(2) val profileTransaction = fixture.startedTransactions.last() assertThat(profileTransaction.isFinished).isFalse() - assertThat(profileTransaction.name).isEqualTo(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) + assertThat(profileTransaction.name).isEqualTo(unknown) + assertThat(profileTransaction.getData("unknown_entry_reason")).isEqualTo("blank_name") assertThat(fixture.scope.transaction).isSameInstanceAs(profileTransaction) - assertThat(fixture.scope.screen).isEqualTo(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) - assertThat(fixture.scope.contexts.app?.viewNames) - .isEqualTo(listOf(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME)) + assertThat(fixture.scope.screen).isEqualTo(unknown) + assertThat(fixture.scope.contexts.app?.viewNames).isEqualTo(listOf(unknown)) assertThat(fixture.breadcrumbs).hasSize(2) assertThat(fixture.breadcrumbs.last().data) - .containsExactly("from", "/home", "to", NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) - assertThat(fixture.scope.navigationBackStack()) .isEqualTo( - listOf( - mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), - mapOf("entry" to "/home"), - ), + mapOf("from" to "/home", "to" to unknown, "to_unknown_entry_reason" to "blank_name"), ) + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo(listOf(blankNameEntry, mapOf("entry" to "/home"))) // Navigate to the cart screen and verify the later failure is also recorded as /unknown rather // than collapsing the route history. @@ -706,34 +708,24 @@ class BackStackObserverTest { assertThat(fixture.startedTransactions).hasSize(3) val cartTransaction = fixture.startedTransactions.last() assertThat(cartTransaction.isFinished).isFalse() - assertThat(cartTransaction.name).isEqualTo(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) - assertThat(cartTransaction.getData("arguments")) - .isEqualTo(mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed")) + assertThat(cartTransaction.name).isEqualTo(unknown) + assertThat(cartTransaction.getData("arguments")).isNull() + assertThat(cartTransaction.getData("unknown_entry_reason")).isEqualTo("mapping_failed") assertThat(fixture.scope.transaction).isSameInstanceAs(cartTransaction) - assertThat(fixture.scope.screen).isEqualTo(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME) - assertThat(fixture.scope.contexts.app?.viewNames) - .isEqualTo(listOf(NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME)) + assertThat(fixture.scope.screen).isEqualTo(unknown) + assertThat(fixture.scope.contexts.app?.viewNames).isEqualTo(listOf(unknown)) assertThat(fixture.breadcrumbs).hasSize(3) assertThat(fixture.breadcrumbs.last().data) - .containsExactly( - "from", - NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, - "to", - NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, - "to_arguments", - mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed"), - ) - assertThat(fixture.scope.navigationBackStack()) .isEqualTo( - listOf( - mapOf( - "entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, - "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed"), - ), - mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), - mapOf("entry" to "/home"), + mapOf( + "from" to unknown, + "from_unknown_entry_reason" to "blank_name", + "to" to unknown, + "to_unknown_entry_reason" to "mapping_failed", ), ) + assertThat(fixture.scope.navigationBackStack()) + .isEqualTo(listOf(mappingFailedEntry, blankNameEntry, mapOf("entry" to "/home"))) // Navigate to the settings screen and verify a new /settings transaction is started and Sentry // data are generated again, as we received a valid route name. @@ -744,28 +736,25 @@ class BackStackObserverTest { val settingsTransaction = fixture.startedTransactions.last() assertThat(settingsTransaction.isFinished).isFalse() assertThat(settingsTransaction.name).isEqualTo("/settings") + assertThat(settingsTransaction.getData("unknown_entry_reason")).isNull() assertThat(fixture.scope.transaction).isSameInstanceAs(settingsTransaction) assertThat(fixture.scope.screen).isEqualTo("/settings") assertThat(fixture.scope.contexts.app?.viewNames).isEqualTo(listOf("/settings")) assertThat(fixture.breadcrumbs).hasSize(4) assertThat(fixture.breadcrumbs.last().data) - .containsExactly( - "from", - NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, - "from_arguments", - mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed"), - "to", - "/settings", + .isEqualTo( + mapOf( + "from" to unknown, + "from_unknown_entry_reason" to "mapping_failed", + "to" to "/settings", + ), ) assertThat(fixture.scope.navigationBackStack()) .isEqualTo( listOf( mapOf("entry" to "/settings"), - mapOf( - "entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME, - "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "mapping_failed"), - ), - mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), + mappingFailedEntry, + blankNameEntry, mapOf("entry" to "/home"), ), ) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt new file mode 100644 index 00000000000..d0496555662 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/BuiltInBackStackEntryMappersTest.kt @@ -0,0 +1,406 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.Sentry +import io.sentry.SentryIntegrationPackageStorage +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.MIN_KOTLINX_SERIALIZATION_VERSION +import io.sentry.test.initForTest +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.SerialName +import kotlinx.serialization.Serializable +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions + +/** + * The built-in mappers are singletons whose caches and warning history persist across tests. Tests + * that assert logs must use `create()` or a fresh class loader to isolate that state. + */ +class BuiltInBackStackEntryMappersTest { + + @Serializable @SerialName("Home") data object Home + + @Serializable @SerialName("Detail") data class Detail(val id: String) + + data class NotSerializable(val id: String) + + private val kotlinxMapper = BackStackEntryMapper { SentryBackStackEntry("Kotlinx") } + private val logger = mock() + + @Before + fun clearIntegrations() { + SentryIntegrationPackageStorage.getInstance().clearStorage() + } + + @After + fun clearIntegrationsAfterTest() { + SentryIntegrationPackageStorage.getInstance().clearStorage() + } + + // serialName + + @Test + fun `serialName names entries without recording their properties`() { + val mapper = BuiltInBackStackEntryMappers.serialName + + val mapped = listOf(Home, Detail("1")).map(mapper::map) + + assertThat(mapped) + .containsExactly(SentryBackStackEntry("Home"), SentryBackStackEntry("Detail")) + .inOrder() + } + + @Test + fun `serialName returns the same mapper on every access`() { + assertThat(BuiltInBackStackEntryMappers.serialName) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialName) + } + + // BackStackEntryMapper's companion mappers + + @Test + fun `BackStackEntryMapper SerialName returns the built-in mapper`() { + assertThat(BackStackEntryMapper.SerialName) + .isSameInstanceAs(BuiltInBackStackEntryMappers.serialName) + } + + @Test + fun `BackStackEntryMapper SerialName can serve as the mapper for any entry type`() { + val homeMapper: BackStackEntryMapper = BackStackEntryMapper.SerialName + + assertThat(homeMapper.map(Home)).isEqualTo(SentryBackStackEntry("Home")) + } + + @Test + fun `reading BackStackEntryMapper SerialName doesn't create the kotlinx mapper`() { + val classLoader = KotlinxMapperHidingClassLoader() + + classLoader.companionMapper("getSerialName") + + assertThat(classLoader.wasKotlinxMapperRequested).isFalse() + } + + @Test + fun `BackStackEntryMapper SerialName maps entries to null when the kotlinx mapper can't be loaded`() { + val classLoader = KotlinxMapperHidingClassLoader() + + val mapper = classLoader.companionMapper("getSerialName") + + assertThat(mapper.map(Home)).isNull() + assertThat(classLoader.wasKotlinxMapperRequested).isTrue() + } + + @Test + fun `BackStackEntryMapper SerialName maps entries to null when kotlinx serialization is missing`() { + val classLoader = KotlinxMapperHidingClassLoader(hidesKotlinx = true) + val entry = classLoader.notSerializableEntry("1") + + val mapper = classLoader.companionMapper("getSerialName") + + assertThat(mapper.map("home")).isNull() + assertThat(mapper.map(entry)).isNull() + assertThat(classLoader.wasKotlinxRequested).isTrue() + } + + // First mapping from several threads + + @Test + fun `BackStackEntryMapper SerialName holds no lock while creating the mapper logs on first mapping`() { + val race = raceOnFirstMapping("getSerialName") + + assertThat(race.otherThreadLoggerGotAppLock).isTrue() + } + + @Test + fun `BackStackEntryMapper SerialName uses the mapper published first for racing and later mappings`() { + val race = raceOnFirstMapping("getSerialName") + + assertThat(race.unavailableTypeWarnings).isEqualTo(1) + } + + // MIN_KOTLINX_SERIALIZATION_VERSION + + @Test + fun `MIN_KOTLINX_SERIALIZATION_VERSION matches kotlinxSerialization-floor in the dependency matrix catalog`() { + val floor = + checkNotNull(System.getProperty(KOTLINX_SERIALIZATION_FLOOR_PROPERTY)) { + "System property $KOTLINX_SERIALIZATION_FLOOR_PROPERTY is missing. Run this test through " + + "Gradle, which sets it from kotlinxSerialization-floor in " + + "gradle/dependency-matrix.versions.toml." + } + + assertThat(MIN_KOTLINX_SERIALIZATION_VERSION).isEqualTo(floor) + } + + // create() + + @Test + fun `create() - returns the kotlinx mapper without logging when it can be created`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + kotlinxMapper + } + + assertThat(mapper).isSameInstanceAs(kotlinxMapper) + verifyNoInteractions(logger) + } + + @Test + fun `create() - maps entries to null when creating the kotlinx mapper throws NoClassDefFoundError`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw NoClassDefFoundError("kotlinx/serialization/KSerializer") + } + + assertThat(mapper.map(Home)).isNull() + } + + @Test + fun `create() - maps entries to null when creating the kotlinx mapper throws ExceptionInInitializerError`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw ExceptionInInitializerError("static initializer failed") + } + + assertThat(mapper.map(Home)).isNull() + } + + @Test + fun `create() - reports the kotlinx serialization version as the reason when mapper creation fails`() { + val mapper = + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw NoClassDefFoundError("kotlinx/serialization/KSerializer") + } + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Home) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION) + } + + @Test + fun `create() - logs the LinkageError and compatibility advice when mapper creation fails`() { + val error = NoClassDefFoundError("kotlinx/serialization/KSerializer") + + BuiltInBackStackEntryMappers.create(logger = { logger }) { throw error } + + val message = argumentCaptor() + verify(logger, times(1)).log(eq(SentryLevel.WARNING), message.capture(), eq(error)) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `create() - adds no Nav3 integration to the SDK when creating the kotlinx mapper throws a LinkageError`() { + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw NoClassDefFoundError("kotlinx/serialization/KSerializer") + } + + assertThat( + SentryIntegrationPackageStorage.getInstance().integrations.filter { + it.startsWith(NAV3_INTEGRATION_PREFIX) + }, + ) + .isEmpty() + } + + @Test + fun `create() - propagates an exception that isn't a LinkageError from creating the kotlinx mapper`() { + val exception = IllegalStateException("mapper bug") + + val thrown = + assertFailsWith { + BuiltInBackStackEntryMappers.create(logger = { logger }) { + throw exception + } + } + + assertThat(thrown).isSameInstanceAs(exception) + } + + /** + * Races the first mappings of [Home] by the mapper of [getterName] to detect lock inversion: this + * thread holds an app lock while mapping, and the other thread's mapper creation logs through a + * logger that needs the same lock. Holding a lazy-initialization lock while logging would + * deadlock. Then maps [Home] once more. + * + * Both threads create an [UnavailableBackStackEntryMapper], which warns once per entry type, so a + * single warning shows that every mapping used the one mapper published first. + * + * Bounded waits prevent a hang. Assertions inside the helper verify the race's preconditions. + */ + private fun raceOnFirstMapping(getterName: String): FirstMappingRace { + val appLock = ReentrantLock() + val logger = LockingLogger(appLock, thisThread = Thread.currentThread()) + initForTest( + { + it.dsn = "https://key@sentry.io/proj" + it.isDebug = true + it.setLogger(logger) + }, + true, + ) + try { + val mapper = KotlinxMapperHidingClassLoader().companionMapper(getterName) + appLock.lock() + val otherThread = thread(name = "other-mapper-user") { mapper.map(Home) } + assertThat(logger.otherThreadLogging.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue() + + try { + mapper.map(Home) + } finally { + appLock.unlock() + } + otherThread.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS * 2)) + assertThat(otherThread.isAlive).isFalse() + mapper.map(Home) + + return FirstMappingRace( + otherThreadLoggerGotAppLock = logger.otherThreadGotLock, + unavailableTypeWarnings = logger.unavailableTypeWarnings.get(), + ) + } finally { + Sentry.close() + } + } + + private class FirstMappingRace( + val otherThreadLoggerGotAppLock: Boolean, + /** How many times the racing and later mappings warned that [Home]'s mapper is unavailable. */ + val unavailableTypeWarnings: Int, + ) + + /** + * An app's logger that takes [appLock] to log that the built-in mappers couldn't be created, as + * an app's logger might, giving up after a timeout. Records whether a thread other than + * [thisThread] got the lock, and counts warnings that an entry type's mapper is unavailable. + */ + private class LockingLogger(private val appLock: ReentrantLock, private val thisThread: Thread) : + ILogger { + val otherThreadLogging = CountDownLatch(1) + + val unavailableTypeWarnings = AtomicInteger() + + @Volatile var otherThreadGotLock = false + + override fun log(level: SentryLevel, message: String, vararg args: Any?) { + if (message.startsWith(MAPPER_UNAVAILABLE)) unavailableTypeWarnings.incrementAndGet() + } + + override fun log(level: SentryLevel, message: String, throwable: Throwable?) { + if (!message.startsWith(CREATION_FAILED)) return + val isOtherThread = Thread.currentThread() != thisThread + if (isOtherThread) otherThreadLogging.countDown() + val gotLock = appLock.tryLock(TIMEOUT_SECONDS, TimeUnit.SECONDS) + if (isOtherThread) otherThreadGotLock = gotLock + if (gotLock) appLock.unlock() + } + + override fun log( + level: SentryLevel, + throwable: Throwable?, + message: String, + vararg args: Any?, + ) = Unit + + override fun isEnabled(level: SentryLevel?): Boolean = true + } + + /** + * Loads its own copy of this module's classes, so their singletons are created anew, but can't + * find [KotlinxBackStackEntryMapper], as when it can't be linked against the app's + * kotlinx.serialization. Other classes come from the test's class loader. + * + * With `hidesKotlinx = true`, it finds [KotlinxBackStackEntryMapper] but not + * kotlinx.serialization itself, as when the app doesn't depend on it. + */ + private class KotlinxMapperHidingClassLoader(private val hidesKotlinx: Boolean = false) : + ClassLoader(BuiltInBackStackEntryMappersTest::class.java.classLoader) { + + @Volatile + var wasKotlinxMapperRequested = false + private set + + @Volatile + var wasKotlinxRequested = false + private set + + /** Returns a [NotSerializable] loaded by this class loader, which doesn't need kotlinx. */ + fun notSerializableEntry(id: String): Any = + loadClass(NotSerializable::class.java.name).getConstructor(String::class.java).newInstance(id) + + /** Returns the mapper of this class loader's `BackStackEntryMapper.Companion.`. */ + fun companionMapper(getterName: String): Mapper { + val companion = + loadClass(BackStackEntryMapper::class.java.name).getField("Companion").get(null) + return Mapper(companion.javaClass.getMethod(getterName).invoke(companion)) + } + + override fun loadClass(name: String, resolve: Boolean): Class<*> = + synchronized(this) { + when { + name == HIDDEN_CLASS && !hidesKotlinx -> { + wasKotlinxMapperRequested = true + throw ClassNotFoundException(name) + } + name.startsWith(KOTLINX_PACKAGE) && hidesKotlinx -> { + wasKotlinxRequested = true + throw ClassNotFoundException(name) + } + !name.startsWith(ISOLATED_PACKAGE) -> super.loadClass(name, resolve) + else -> findLoadedClass(name) ?: define(name) + } + } + + private fun define(name: String): Class<*> { + val bytes = + parent.getResourceAsStream(name.replace('.', '/') + ".class")?.use { it.readBytes() } + ?: throw ClassNotFoundException(name) + return defineClass(name, bytes, 0, bytes.size) + } + + /** A mapper loaded by this class loader, whose types differ from the test's. */ + class Mapper(val delegate: Any) { + val type: Class<*> = delegate.javaClass + + fun map(backStackEntry: Any): Any? = + type.getMethod("map", Any::class.java).invoke(delegate, backStackEntry) + } + + private companion object { + const val ISOLATED_PACKAGE = "io.sentry.compose.navigation3." + const val KOTLINX_PACKAGE = "kotlinx.serialization." + val HIDDEN_CLASS: String = KotlinxBackStackEntryMapper::class.java.name + } + } + + private companion object { + /** Bounds every wait, so that a deadlock fails the test rather than hanging it. */ + const val TIMEOUT_SECONDS = 5L + + const val CREATION_FAILED = "Nav3 built-in mapper creation failed." + + const val MAPPER_UNAVAILABLE = "Nav3 mapper unavailable for type" + + const val NAV3_INTEGRATION_PREFIX = "ComposeNavigation3" + + /** Set by the module's Gradle build from `kotlinxSerialization-floor`. */ + const val KOTLINX_SERIALIZATION_FLOOR_PROPERTY = "nav3.kotlinxSerializationFloor" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/DeferredBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/DeferredBackStackEntryMapperTest.kt new file mode 100644 index 00000000000..4d78dd61d1f --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/DeferredBackStackEntryMapperTest.kt @@ -0,0 +1,88 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.BackStackEntryMapper +import io.sentry.compose.navigation3.SentryBackStackEntry +import kotlin.test.assertFailsWith +import org.junit.Test + +class DeferredBackStackEntryMapperTest { + + @Test + fun `doesn't create the delegate mapper before it maps an entry`() { + val fixture = Fixture.create() + + assertThat(fixture.creations).isEqualTo(0) + } + + // map() + + @Test + fun `map() - creates the delegate mapper on the first call and returns its result for the entry`() { + val fixture = Fixture.create() + val deferredMapper = fixture.deferredMapper + + val mapped = deferredMapper.map("home") + + assertThat(mapped).isEqualTo(SentryBackStackEntry("mapped home")) + assertThat(fixture.creations).isEqualTo(1) + } + + @Test + fun `map() - reuses the created delegate mapper for later entries`() { + val fixture = Fixture.create() + val deferredMapper = fixture.deferredMapper + deferredMapper.map("home") + + val mapped = listOf("detail", "settings").map(deferredMapper::map) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("mapped detail"), + SentryBackStackEntry("mapped settings"), + ) + .inOrder() + assertThat(fixture.creations).isEqualTo(1) + } + + @Test + fun `map() - propagates the exception thrown while creating the delegate mapper`() { + val exception = IllegalStateException("creation failed") + val fixture = Fixture.create(creationFailure = exception) + val deferredMapper = fixture.deferredMapper + + val thrown = assertFailsWith { deferredMapper.map("home") } + + assertThat(thrown).isSameInstanceAs(exception) + } + + @Test + fun `map() - creates the delegate mapper again after creating it threw`() { + val fixture = Fixture.create(creationFailure = IllegalStateException("creation failed")) + val deferredMapper = fixture.deferredMapper + assertFailsWith { deferredMapper.map("home") } + fixture.creationFailure = null + + val mapped = deferredMapper.map("home") + + assertThat(mapped).isEqualTo(SentryBackStackEntry("mapped home")) + assertThat(fixture.creations).isEqualTo(2) + } + + private class Fixture private constructor(var creationFailure: RuntimeException?) { + var creations = 0 + private set + + private val delegateMapper = BackStackEntryMapper { SentryBackStackEntry("mapped $it") } + + val deferredMapper = DeferredBackStackEntryMapper { + creations++ + creationFailure?.let { throw it } + delegateMapper + } + + companion object { + fun create(creationFailure: RuntimeException? = null) = Fixture(creationFailure) + } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt new file mode 100644 index 00000000000..0b143b10418 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/HostArgumentSourceTest.kt @@ -0,0 +1,436 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.BeginList +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.BeginMap +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.End +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.Key +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.Scalar +import io.sentry.compose.navigation3.internal.backstack.HostArgumentSourceTest.Event.UncomputedScalar +import java.math.BigDecimal +import java.util.AbstractCollection +import kotlin.test.assertFailsWith +import org.junit.Test + +class HostArgumentSourceTest { + + private enum class PrivacyMode { + PUBLIC, + PRIVATE, + } + + private class OpaqueValue { + override fun toString(): String = "opaque-value" + } + + private class OpaqueIterable : Iterable { + override fun iterator(): Iterator = listOf("a").iterator() + + override fun toString(): String = "opaque-iterable" + } + + private class OpaqueSequence : Sequence { + override fun iterator(): Iterator = listOf("a").iterator() + + override fun toString(): String = "opaque-sequence" + } + + private class CountingValue { + var toStringCalls = 0 + + override fun toString(): String { + toStringCalls++ + return "counting-value" + } + } + + private val unsupportedTypeNames = mutableListOf() + private val sink = RecordingArgumentSink() + + // Arguments + + @Test + fun `writeTo() - writes each argument as its key followed by its value`() { + val source = hostArgumentSource(mapOf("id" to "123", "page" to 2)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("id"), Scalar("123"), Key("page"), Scalar(2)) + .inOrder() + } + + @Test + fun `writeTo() - writes nothing for empty arguments`() { + val source = hostArgumentSource(emptyMap()) + + source.writeTo(sink) + + assertThat(sink.events).isEmpty() + } + + @Test + fun `writeTo() - writes map keys by toString`() { + val key = + object { + override fun toString(): String = "custom-key" + } + val source = + hostArgumentSource(mapOf(1 to "a", PrivacyMode.PUBLIC to "b", key to "c", null to "d")) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly(Key("1"), Key("PUBLIC"), Key("custom-key"), Key("null")) + .inOrder() + } + + // Containers + + @Test + fun `writeTo() - writes a nested map between beginMap() and end()`() { + val nested = mapOf(1 to "a") + val source = hostArgumentSource(mapOf("nested" to nested)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("nested"), BeginMap(nested), Key("1"), Scalar("a"), End) + .inOrder() + } + + @Test + fun `writeTo() - passes a nested map as its own identity`() { + val nested = mapOf("k" to "v") + val source = hostArgumentSource(mapOf("nested" to nested)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(nested) + } + + @Test + fun `writeTo() - writes a collection as a list`() { + val set = linkedSetOf("a", "b") + val source = hostArgumentSource(mapOf("set" to set)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("set"), BeginList(set), Scalar("a"), Scalar("b"), End) + .inOrder() + } + + @Test + fun `writeTo() - passes a collection as its own identity`() { + val list = listOf("a") + val source = hostArgumentSource(mapOf("list" to list)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(list) + } + + @Test + fun `writeTo() - writes an object array as a list`() { + val array = arrayOf("a", 1) + val source = hostArgumentSource(mapOf("array" to array)) + + source.writeTo(sink) + + assertThat(sink.events) + .containsExactly(Key("array"), BeginList(array), Scalar("a"), Scalar(1), End) + .inOrder() + } + + @Test + fun `writeTo() - writes primitive arrays as lists of their elements`() { + val source = + hostArgumentSource( + mapOf( + "booleans" to booleanArrayOf(true), + "bytes" to byteArrayOf(1), + "shorts" to shortArrayOf(2), + "ints" to intArrayOf(3), + "longs" to longArrayOf(4L), + "floats" to floatArrayOf(5f), + "doubles" to doubleArrayOf(6.0), + "chars" to charArrayOf('7'), + ), + ) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly( + Scalar(true), + Scalar(1.toByte()), + Scalar(2.toShort()), + Scalar(3), + Scalar(4L), + Scalar(5f), + Scalar(6.0), + Scalar('7'), + ) + .inOrder() + assertThat(sink.events.count { it is BeginList }).isEqualTo(8) + } + + @Test + fun `writeTo() - passes a primitive array as its own identity`() { + val ints = intArrayOf(1, 2) + val source = hostArgumentSource(mapOf("ints" to ints)) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance().single().identity).isSameInstanceAs(ints) + } + + @Test + fun `writeTo() - writes containers nested in containers recursively`() { + val inner = listOf(1) + val outer = mapOf("inner" to inner) + val source = hostArgumentSource(mapOf("outer" to listOf(outer))) + + source.writeTo(sink) + + assertThat(sink.events.drop(1)) + .containsExactly( + BeginList(listOf(outer)), + BeginMap(outer), + Key("inner"), + BeginList(inner), + Scalar(1), + End, + End, + End, + ) + .inOrder() + } + + @Test + fun `writeTo() - doesn't read the size of a collection`() { + val values = + object : AbstractCollection() { + var wasSizeRead = false + + override val size: Int + get() { + wasSizeRead = true + return Int.MAX_VALUE + } + + override fun iterator(): MutableIterator = mutableListOf(1, 2).iterator() + } + val source = hostArgumentSource(mapOf("values" to values)) + + source.writeTo(sink) + + assertThat(values.wasSizeRead).isFalse() + } + + // Scalars + + @Test + fun `writeTo() - passes null, Boolean, and Number values unchanged`() { + val bigDecimal = BigDecimal("1.25") + val source = + hostArgumentSource( + mapOf("null" to null, "boolean" to true, "nan" to Double.NaN, "bigDecimal" to bigDecimal), + ) + + source.writeTo(sink) + + assertThat(sink.events.filterIsInstance()) + .containsExactly(Scalar(null), Scalar(true), Scalar(Double.NaN), Scalar(bigDecimal)) + .inOrder() + } + + @Test + fun `writeTo() - passes CharSequence and Char values unchanged`() { + val text = StringBuilder("hello") + val source = hostArgumentSource(mapOf("text" to text, "char" to 'x')) + + source.writeTo(sink) + + val scalars = sink.events.filterIsInstance() + assertThat(scalars[0].value).isSameInstanceAs(text) + assertThat(scalars[1].value).isEqualTo('x') + } + + @Test + fun `writeTo() - writes enums by name`() { + val source = hostArgumentSource(mapOf("mode" to PrivacyMode.PRIVATE)) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("mode"), Scalar("PRIVATE")).inOrder() + } + + @Test + fun `writeTo() - doesn't report supported values as unsupported`() { + val source = + hostArgumentSource( + mapOf( + "string" to "a", + "char" to 'b', + "number" to 1, + "boolean" to false, + "null" to null, + "enum" to PrivacyMode.PUBLIC, + "list" to listOf(1), + "map" to mapOf("k" to "v"), + "array" to intArrayOf(1), + ), + ) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).isEmpty() + } + + // Unsupported values + + @Test + fun `writeTo() - writes an unsupported value by toString`() { + val source = hostArgumentSource(mapOf("opaque" to OpaqueValue())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("opaque"), Scalar("opaque-value")).inOrder() + } + + @Test + fun `writeTo() - reports an unsupported value with its simple type name`() { + val source = hostArgumentSource(mapOf("opaque" to OpaqueValue())) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).containsExactly("OpaqueValue") + } + + @Test + fun `writeTo() - writes an Iterable that isn't a Collection as an unsupported value`() { + val source = hostArgumentSource(mapOf("iterable" to OpaqueIterable())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("iterable"), Scalar("opaque-iterable")).inOrder() + assertThat(unsupportedTypeNames).containsExactly("OpaqueIterable") + } + + @Test + fun `writeTo() - writes a Sequence as an unsupported value`() { + val source = hostArgumentSource(mapOf("sequence" to OpaqueSequence())) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("sequence"), Scalar("opaque-sequence")).inOrder() + assertThat(unsupportedTypeNames).containsExactly("OpaqueSequence") + } + + @Test + fun `writeTo() - reports an unsupported value of an anonymous type with a null type name`() { + val anonymous = + object { + override fun toString(): String = "anonymous" + } + val source = hostArgumentSource(mapOf("anonymous" to anonymous)) + + source.writeTo(sink) + + assertThat(unsupportedTypeNames).containsExactly(null) + } + + @Test + fun `writeTo() - doesn't call an unsupported value's toString() or report it until the sink computes the value`() { + val value = CountingValue() + val sink = RecordingArgumentSink(computesScalars = false) + val source = hostArgumentSource(mapOf("counting" to value)) + + source.writeTo(sink) + + assertThat(sink.events).containsExactly(Key("counting"), UncomputedScalar).inOrder() + assertThat(value.toStringCalls).isEqualTo(0) + assertThat(unsupportedTypeNames).isEmpty() + } + + // Failures + + @Test + fun `writeTo() - stops writing when the sink throws`() { + val failure = DropArguments(ArgumentDropReason.MAX_COUNT, DropArguments.MAX_COUNT_WARNING) + val sink = RecordingArgumentSink(failOnKey = "second", keyFailure = failure) + val source = hostArgumentSource(mapOf("first" to 1, "second" to 2, "third" to 3)) + + val thrown = assertFailsWith { source.writeTo(sink) } + + assertThat(thrown).isSameInstanceAs(failure) + assertThat(sink.events).containsExactly(Key("first"), Scalar(1)).inOrder() + } + + private fun hostArgumentSource(arguments: Map<*, *>): HostArgumentSource = + HostArgumentSource(arguments) { unsupportedTypeNames += it } + + sealed interface Event { + data class Key(val name: String) : Event + + data class Scalar(val value: Any?) : Event + + data class BeginMap(val identity: Any?) : Event + + data class BeginList(val identity: Any?) : Event + + object End : Event { + override fun toString(): String = "End" + } + + /** A computed scalar the sink declined to compute. */ + object UncomputedScalar : Event { + override fun toString(): String = "UncomputedScalar" + } + } + + /** + * Records every call as an [Event], and throws [keyFailure] when asked for the key [failOnKey]. + * With `computesScalars = false`, records each computed scalar without computing it. + */ + private class RecordingArgumentSink( + private val failOnKey: String? = null, + private val keyFailure: RuntimeException? = null, + private val computesScalars: Boolean = true, + ) : ArgumentSink { + + val events = mutableListOf() + + override val failure: DropArguments? = null + + override fun beginMap(identity: Any?) { + events += BeginMap(identity) + } + + override fun beginList(identity: Any?) { + events += BeginList(identity) + } + + override fun key(name: String, describeDuplicate: (() -> String)?) { + if (name == failOnKey && keyFailure != null) throw keyFailure + events += Key(name) + } + + override fun scalar(value: Any?) { + events += Scalar(value) + } + + override fun computedScalar(compute: () -> Any?) { + if (computesScalars) scalar(compute()) else events += UncomputedScalar + } + + override fun end() { + events += End + } + + override fun reject(reason: ArgumentDropReason, warning: String): Nothing = + throw UnsupportedOperationException("HostArgumentSource enforces no limits of its own") + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/NormalizedSentryBackStackEntryTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/NormalizedSentryBackStackEntryTest.kt new file mode 100644 index 00000000000..ccf9e1b7693 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/NormalizedSentryBackStackEntryTest.kt @@ -0,0 +1,113 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY +import io.sentry.compose.navigation3.internal.backstack.NormalizedSentryBackStackEntry.Companion.UNKNOWN_ENTRY_NAME +import org.junit.Test + +class NormalizedSentryBackStackEntryTest { + + @Test + fun `serialize() - includes the reason arguments were dropped`() { + val entry = + NormalizedSentryBackStackEntry( + name = "/HomeScreen", + argumentDropReason = ArgumentDropReason.MAX_COUNT, + ) + + assertThat(entry.serialize()) + .isEqualTo( + mapOf( + "entry" to "/HomeScreen", + "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "max_argument_count_exceeded"), + ), + ) + } + + @Test + fun `serialize() - includes the reason an unnamed entry has no name`() { + val entry = + NormalizedSentryBackStackEntry( + name = UNKNOWN_ENTRY_NAME, + arguments = mapOf("userId" to "123"), + unknownEntryReason = UnknownEntryReason.BLANK_NAME, + ) + + assertThat(entry.serialize()) + .isEqualTo( + mapOf( + "entry" to UNKNOWN_ENTRY_NAME, + "unknown_entry_reason" to "blank_name", + "entry_arguments" to mapOf("userId" to "123"), + ), + ) + } + + @Test + fun `serialize() - omits the unnamed reason for a named entry`() { + val entry = NormalizedSentryBackStackEntry(name = "/HomeScreen") + + assertThat(entry.serialize()).isEqualTo(mapOf("entry" to "/HomeScreen")) + } + + @Test + fun `transactionData() - returns the arguments of an entry with arguments`() { + val entry = NormalizedSentryBackStackEntry("/HomeScreen", mapOf("tab" to "home")) + + assertThat(entry.transactionData()).isEqualTo(mapOf("arguments" to mapOf("tab" to "home"))) + } + + @Test + fun `transactionData() - returns the unnamed reason of an unnamed entry without arguments`() { + val entry = + NormalizedSentryBackStackEntry( + UNKNOWN_ENTRY_NAME, + unknownEntryReason = UnknownEntryReason.UNMAPPED, + ) + + assertThat(entry.transactionData()).isEqualTo(mapOf("unknown_entry_reason" to "unmapped")) + } + + @Test + fun `transactionData() - returns the arguments and unnamed reason of an unnamed entry with arguments`() { + val entry = + NormalizedSentryBackStackEntry( + UNKNOWN_ENTRY_NAME, + arguments = mapOf("userId" to "123"), + unknownEntryReason = UnknownEntryReason.BLANK_NAME, + ) + + assertThat(entry.transactionData()) + .isEqualTo( + mapOf("arguments" to mapOf("userId" to "123"), "unknown_entry_reason" to "blank_name"), + ) + } + + @Test + fun `transactionData() - returns no data for a named entry without arguments`() { + val entry = NormalizedSentryBackStackEntry("/HomeScreen") + + assertThat(entry.transactionData()).isEmpty() + } + + @Test + fun `transactionData() - includes the reason arguments were dropped in the arguments`() { + val entry = + NormalizedSentryBackStackEntry( + "/HomeScreen", + arguments = mapOf("tab" to "home"), + argumentDropReason = ArgumentDropReason.CHARACTER_LIMIT, + ) + + assertThat(entry.transactionData()) + .isEqualTo( + mapOf( + "arguments" to + mapOf( + "tab" to "home", + ARGUMENT_DROP_REASON_KEY to ArgumentDropReason.CHARACTER_LIMIT.serializedValue, + ), + ), + ) + } +} 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 00000000000..ccba9d16797 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/SelfWritingArguments.kt @@ -0,0 +1,15 @@ +package io.sentry.compose.navigation3.internal.backstack + +/** + * Arguments that write themselves with [write], like a built-in mapper'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/TestTexts.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TestTexts.kt new file mode 100644 index 00000000000..4cb99bbf5eb --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TestTexts.kt @@ -0,0 +1,31 @@ +package io.sentry.compose.navigation3.internal.backstack + +/** + * Host app text that reports [length], which may differ from [text]'s, and counts its conversions + * to a `String` in [toStringCalls]. + */ +internal class CountingText(override val length: Int, private val text: String) : CharSequence { + var toStringCalls = 0 + private set + + override fun get(index: Int): Char = text[index] + + override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = + text.subSequence(startIndex, endIndex) + + override fun toString(): String { + toStringCalls++ + return text + } +} + +/** Host app text whose conversion to a `String` throws [error]. */ +internal class FailingText(val error: RuntimeException) : CharSequence { + override val length: Int = 1 + + override fun get(index: Int): Char = 'x' + + override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = "x" + + @Suppress("ExceptionRaisedInUnexpectedLocation") override fun toString(): String = throw error +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt new file mode 100644 index 00000000000..20d01897c3a --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/TreeArgumentWriterTest.kt @@ -0,0 +1,872 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_DEPTH +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.util.UrlUtils +import kotlin.test.assertFailsWith +import org.junit.Test + +@Suppress("LargeClass") +class TreeArgumentWriterTest { + + private val budget = ArgumentBudget() + private val sink = TreeArgumentWriter(budget) + + private val characterLimitDrop = + ArgumentDropReason.CHARACTER_LIMIT to DropArguments.MAX_CHARACTER_WARNING + private val duplicateKeyDrop = + ArgumentDropReason.DUPLICATE_KEY to DropArguments.DUPLICATE_KEY_WARNING + private val maxCountDrop = ArgumentDropReason.MAX_COUNT to DropArguments.MAX_COUNT_WARNING + private val structureDrop = + ArgumentDropReason.INVALID_STRUCTURE to DropArguments.STRUCTURE_WARNING + + private val DropArguments.signal: Pair + get() = reason to warning + + private companion object { + const val SUBSTITUTE = UrlUtils.SENSITIVE_DATA_SUBSTITUTE + } + + // Building the tree + + @Test + fun `argumentsOrThrow() - returns the arguments written as maps and lists`() { + sink.key("id") + sink.scalar("123") + sink.key("filters") + sink.beginMap() + sink.key("tags") + sink.beginList() + sink.scalar("a") + sink.scalar(true) + sink.end() + sink.key("limit") + sink.scalar(null) + sink.end() + sink.key("page") + sink.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo( + mapOf( + "id" to "123", + "filters" to mapOf("tags" to listOf("a", true), "limit" to null), + "page" to 2, + ), + ) + } + + @Test + fun `argumentsOrThrow() - keeps arguments in the order they were written`() { + sink.key("b") + sink.scalar(1) + sink.key("a") + sink.scalar(2) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments.keys).containsExactly("b", "a").inOrder() + } + + @Test + fun `argumentsOrThrow() - returns an empty map when nothing was written`() { + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEmpty() + } + + // Scalars + + @Test + fun `scalar() - records CharSequence and Char values as Strings`() { + sink.key("text") + sink.scalar(StringBuilder("hello")) + sink.key("char") + sink.scalar('x') + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("text" to "hello", "char" to "x")) + assertThat(arguments["text"]).isInstanceOf(String::class.java) + assertThat(arguments["char"]).isInstanceOf(String::class.java) + } + + @Test + fun `scalar() - writes text exactly as long as the remaining characters`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(2)) + limitedSink.key("") + + limitedSink.scalar("ab") + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to "ab")) + } + + @Test + fun `scalar() - spends characters for a CharSequence value`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar(StringBuilder("ab")) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - drops for the character limit without converting a CharSequence that's too long`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + limitedSink.key("") + val text = CountingText(length = 2, text = "ab") + + val drop = assertFailsWith { limitedSink.scalar(text) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + assertThat(text.toStringCalls).isEqualTo(0) + } + + @Test + fun `scalar() - drops for the character limit when a CharSequence is longer than its reported length`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + limitedSink.key("") + + val drop = + assertFailsWith { limitedSink.scalar(CountingText(length = 1, text = "ab")) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - propagates the exception a CharSequence's toString() throws`() { + val error = IllegalArgumentException("unreadable") + sink.key("text") + + val thrown = assertFailsWith { sink.scalar(FailingText(error)) } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(sink.failure).isNull() + } + + @Test + fun `scalar() - adds nothing for a CharSequence whose toString() throws, so its key can take a value`() { + sink.key("text") + assertFailsWith { + sink.scalar(FailingText(IllegalArgumentException("unreadable"))) + } + + sink.scalar("replacement") + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("text" to "replacement")) + } + + @Test + fun `scalar() - spends characters for a Char value`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(0)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar('x') } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - records non-finite Double and Float values as strings`() { + sink.key("double") + sink.scalar(Double.NEGATIVE_INFINITY) + sink.key("float") + sink.scalar(Float.NaN) + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("double" to "-Infinity", "float" to "NaN")) + } + + @Test + fun `scalar() - spends characters for a non-finite number string`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining("NaN".length - 1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.scalar(Double.NaN) } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `scalar() - doesn't spend characters for a finite number`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(0)) + limitedSink.key("") + + limitedSink.scalar(123.456) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to 123.456)) + } + + @Test + fun `scalar() - doesn't spend characters for a boolean or null`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(0)) + limitedSink.key("") + limitedSink.beginList() + + limitedSink.scalar(true) + limitedSink.scalar(null) + limitedSink.end() + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("" to listOf(true, null))) + } + + @Test + fun `scalar() - throws IllegalArgumentException for an unsupported type`() { + sink.key("opaque") + + assertFailsWith { sink.scalar(Any()) } + } + + @Test + fun `scalar() - throws IllegalStateException for a map value written without a key`() { + assertFailsWith { sink.scalar(1) } + } + + // Computed scalars + + @Test + fun `computedScalar() - writes the computed value as scalar() would`() { + sink.key("text") + sink.computedScalar { StringBuilder("hello") } + sink.key("page") + sink.computedScalar { 2 } + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("text" to "hello", "page" to 2)) + assertThat(arguments["text"]).isInstanceOf(String::class.java) + } + + @Test + fun `computedScalar() - spends characters for computed text`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + limitedSink.key("") + + val drop = assertFailsWith { limitedSink.computedScalar { "ab" } } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `computedScalar() - drops the arguments without computing the value when the value budget is spent`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + limitedSink.key("a") + var computations = 0 + + val drop = assertFailsWith { limitedSink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - drops the arguments for invalid structure without computing a value nested too deeply`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + var computations = 0 + + val drop = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(structureDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - drops the arguments for a duplicate key without computing the value`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + var computations = 0 + + val drop = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + assertThat(computations).isEqualTo(0) + } + + @Test + fun `computedScalar() - drops the arguments for a duplicate key when computing the value would throw`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + + val drop = + assertFailsWith { + sink.computedScalar { throw IllegalStateException("host toString() failed") } + } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `computedScalar() - rethrows an earlier drop without computing the value`() { + val drop = exhaustValues() + var computations = 0 + + val thrown = assertFailsWith { sink.computedScalar { computations++ } } + + assertThat(thrown).isSameInstanceAs(drop) + assertThat(computations).isEqualTo(0) + } + + // Keys + + @Test + fun `key() - accepts a key exactly as long as the remaining characters`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(2)) + + limitedSink.key("ab") + limitedSink.scalar(null) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("ab" to null)) + } + + @Test + fun `key() - spends the characters of the key`() { + val limitedSink = TreeArgumentWriter(budgetWithCharactersRemaining(1)) + + val drop = assertFailsWith { limitedSink.key("ab") } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `key() - doesn't spend a value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + + limitedSink.key("a") + + val drop = assertFailsWith { limitedSink.scalar(1) } + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + // Containers + + @Test + fun `beginMap() - spends one value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + limitedSink.key("map") + + val drop = assertFailsWith { limitedSink.beginMap() } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `beginList() - spends one value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(0)) + limitedSink.key("list") + + val drop = assertFailsWith { limitedSink.beginList() } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `the root map doesn't spend a value`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(1)) + limitedSink.key("id") + + limitedSink.scalar(1) + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("id" to 1)) + } + + @Test + fun `end() - throws IllegalStateException when no map or list is open`() { + assertFailsWith { sink.end() } + } + + @Test + fun `end() - throws IllegalStateException after every opened map and list was ended`() { + sink.key("list") + sink.beginList() + sink.end() + + assertFailsWith { sink.end() } + } + + // Depth + + @Test + fun `a scalar at the maximum depth is written`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.scalar("leaf") + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("nested" to nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf"))) + } + + @Test + fun `a scalar past the maximum depth drops the arguments for invalid structure`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + + val drop = assertFailsWith { sink.scalar("leaf") } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container at the maximum depth is written`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.beginMap() + sink.end() + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("nested" to nestedInLists(MAX_ARGUMENT_DEPTH - 1, emptyMap()))) + } + + @Test + fun `a container past the maximum depth drops the arguments for invalid structure`() { + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH) + + val drop = assertFailsWith { sink.beginMap() } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `depth counts only containers that are still open`() { + sink.key("closed") + openLists(MAX_ARGUMENT_DEPTH - 1) + repeat(MAX_ARGUMENT_DEPTH - 1) { sink.end() } + sink.key("nested") + openLists(MAX_ARGUMENT_DEPTH - 1) + + sink.scalar("leaf") + + assertThat(sink.argumentsOrThrow()["nested"]) + .isEqualTo(nestedInLists(MAX_ARGUMENT_DEPTH - 1, "leaf")) + } + + // Cycles + + @Test + fun `a container nested in a container with the same identity drops the arguments for invalid structure`() { + val list = mutableListOf() + sink.key("cyclic") + sink.beginList(identity = list) + + val drop = assertFailsWith { sink.beginList(identity = list) } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container with the root identity drops the arguments for invalid structure`() { + val root = mutableMapOf() + val rootedSink = TreeArgumentWriter(budget, rootIdentity = root) + rootedSink.key("self") + + val drop = assertFailsWith { rootedSink.beginMap(identity = root) } + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `a container identical to the root is written when no root identity is given`() { + val root = mutableMapOf() + sink.key("self") + + sink.beginMap(identity = root) + sink.end() + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("self" to emptyMap())) + } + + @Test + fun `sibling containers with the same identity are both written`() { + val shared = listOf("a") + sink.key("first") + sink.beginList(identity = shared) + sink.scalar("a") + sink.end() + sink.key("second") + + sink.beginList(identity = shared) + sink.scalar("a") + sink.end() + + assertThat(sink.argumentsOrThrow()) + .isEqualTo(mapOf("first" to listOf("a"), "second" to listOf("a"))) + } + + @Test + fun `nested containers without an identity are never treated as a cycle`() { + sink.key("nested") + sink.beginList(identity = null) + + sink.beginList(identity = null) + sink.end() + sink.end() + + assertThat(sink.argumentsOrThrow()).isEqualTo(mapOf("nested" to listOf(emptyList()))) + } + + // Duplicate keys + + @Test + fun `a scalar under a key already in its map drops the arguments for a duplicate key`() { + sink.key("id") + sink.scalar(1) + sink.key("id") + + val drop = assertFailsWith { sink.scalar(2) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a duplicate key drops the arguments with the warning its describeDuplicate returns`() { + sink.key("id") + sink.scalar(1) + sink.key("id") { "described duplicate" } + + val drop = assertFailsWith { sink.scalar(2) } + + assertThat(drop.signal).isEqualTo(ArgumentDropReason.DUPLICATE_KEY to "described duplicate") + } + + @Test + fun `key() - doesn't call describeDuplicate for a key that isn't taken`() { + var calls = 0 + sink.key("id") { + calls++ + "described duplicate" + } + sink.scalar(1) + sink.key("other") + sink.scalar(2) + + assertThat(calls).isEqualTo(0) + } + + @Test + fun `a map under a key already in its map drops the arguments for a duplicate key when the map begins`() { + sink.key("filters") + sink.scalar(null) + sink.key("filters") + + val drop = assertFailsWith { sink.beginMap() } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a list under a key already in its map drops the arguments for a duplicate key when the list begins`() { + sink.key("tags") + sink.beginList() + sink.end() + sink.key("tags") + + val drop = assertFailsWith { sink.beginList() } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `the same key in a nested map and its parent map is written to both`() { + sink.key("id") + sink.beginMap() + sink.key("id") + sink.scalar(1) + sink.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments).isEqualTo(mapOf("id" to mapOf("id" to 1))) + } + + @Test + fun `the same key in sibling maps is written to both`() { + sink.key("first") + sink.beginMap() + sink.key("id") + sink.scalar(1) + sink.end() + sink.key("second") + sink.beginMap() + sink.key("id") + sink.scalar(2) + sink.end() + + val arguments = sink.argumentsOrThrow() + + assertThat(arguments) + .isEqualTo(mapOf("first" to mapOf("id" to 1), "second" to mapOf("id" to 2))) + } + + @Test + fun `a scalar equal to the one already under its key drops the arguments for a duplicate key`() { + sink.key("id") + sink.scalar('1') + sink.key("id") + + val drop = assertFailsWith { sink.scalar("1") } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a duplicate key drops the arguments for a duplicate key before spending the value budget`() { + val sink = TreeArgumentWriter(budgetWithValuesRemaining(1)) + sink.key(SUBSTITUTE) + sink.scalar(SUBSTITUTE) + sink.key(SUBSTITUTE) + + val drop = assertFailsWith { sink.scalar(SUBSTITUTE) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + // Value budget + + @Test + fun `values exactly filling the remaining value budget are written`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(2)) + limitedSink.key("list") + limitedSink.beginList() + + limitedSink.scalar(1) + limitedSink.end() + + assertThat(limitedSink.argumentsOrThrow()).isEqualTo(mapOf("list" to listOf(1))) + } + + // Shared budget + + @Test + fun `sinks built on one budget share the value budget`() { + val first = TreeArgumentWriter(budget) + val second = TreeArgumentWriter(budget) + writeScalars(first, count = MAX_ARGUMENT_VALUES - 1) + writeScalars(second, count = 1) + second.key("overflow") + + val drop = assertFailsWith { second.scalar(1) } + + assertThat(drop.signal).isEqualTo(maxCountDrop) + } + + @Test + fun `sinks built on one budget share the character budget`() { + val first = TreeArgumentWriter(budget) + val second = TreeArgumentWriter(budget) + first.key("x".repeat(MAX_ARGUMENT_CHARACTERS - 1)) + first.scalar(null) + second.key("y") + + val drop = assertFailsWith { second.scalar("z") } + + assertThat(drop.signal).isEqualTo(characterLimitDrop) + } + + @Test + fun `a duplicate key doesn't spend a value of the shared budget`() { + val sharedBudget = budgetWithValuesRemaining(2) + val first = TreeArgumentWriter(sharedBudget) + val second = TreeArgumentWriter(sharedBudget) + first.key("id") + first.scalar(1) + first.key("id") + assertFailsWith { first.scalar(2) } + second.key("id") + + second.scalar(3) + + assertThat(second.argumentsOrThrow()).isEqualTo(mapOf("id" to 3)) + } + + @Test + fun `a duplicate key drops the arguments for a duplicate key when the shared budget has no values left`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(1)) + limitedSink.key("id") + limitedSink.scalar(1) + limitedSink.key("id") + + val drop = assertFailsWith { limitedSink.scalar(2) } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + @Test + fun `a duplicate key for a container drops the arguments for the duplicate key with no values left`() { + val limitedSink = TreeArgumentWriter(budgetWithValuesRemaining(1)) + limitedSink.key("filters") + limitedSink.scalar(null) + limitedSink.key("filters") + + val drop = assertFailsWith { limitedSink.beginMap() } + + assertThat(drop.signal).isEqualTo(duplicateKeyDrop) + } + + // Sticky failure + + @Test + fun `every write after the arguments are dropped rethrows the same DropArguments`() { + val drop = exhaustValues() + + assertThat(assertFailsWith { sink.key("a") }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.scalar(1) }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginMap() }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginList() }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.end() }).isSameInstanceAs(drop) + } + + @Test + fun `argumentsOrThrow() - rethrows the DropArguments a source caught and swallowed`() { + val caught = exhaustValues() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(caught) + } + + // Recorded failure + + @Test + fun `failure - is null while every write is within the limits`() { + sink.key("id") + sink.scalar("123") + + assertThat(sink.failure).isNull() + } + + @Test + fun `failure - is the DropArguments thrown by the write that broke a limit`() { + val drop = exhaustValues() + + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `failure - stays the first DropArguments after later writes throw`() { + val drop = exhaustValues() + assertFailsWith { sink.key("after") } + assertFailsWith { sink.scalar("x".repeat(MAX_ARGUMENT_CHARACTERS)) } + + val failure = sink.failure + + assertThat(failure).isSameInstanceAs(drop) + } + + @Test + fun `failure - stays null after a write throws for an unsupported value`() { + sink.key("opaque") + assertFailsWith { sink.scalar(Any()) } + + val failure = sink.failure + + assertThat(failure).isNull() + } + + // Limits a source enforces itself + + @Test + fun `reject() - throws DropArguments with the given reason and warning`() { + val drop = rejectStructure() + + assertThat(drop.signal).isEqualTo(structureDrop) + } + + @Test + fun `reject() - records the DropArguments it throws as the failure`() { + val drop = rejectStructure() + + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArguments when a write already broke a limit`() { + val writeDrop = exhaustValues() + + val drop = rejectStructure() + + assertThat(drop).isSameInstanceAs(writeDrop) + assertThat(sink.failure).isSameInstanceAs(writeDrop) + } + + @Test + fun `reject() - throws and keeps the earlier DropArguments when a limit was already rejected`() { + val firstDrop = rejectStructure() + + val drop = + assertFailsWith { + sink.reject(ArgumentDropReason.MAX_COUNT, DropArguments.MAX_COUNT_WARNING) + } + + assertThat(drop).isSameInstanceAs(firstDrop) + assertThat(sink.failure).isSameInstanceAs(firstDrop) + } + + @Test + fun `every write after a rejected limit rethrows the rejected DropArguments`() { + val drop = rejectStructure() + + assertThat(assertFailsWith { sink.key("a") }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.scalar(1) }).isSameInstanceAs(drop) + assertThat(assertFailsWith { sink.beginMap() }).isSameInstanceAs(drop) + assertThat(sink.failure).isSameInstanceAs(drop) + } + + @Test + fun `argumentsOrThrow() - rethrows the rejected DropArguments a source caught and swallowed`() { + sink.key("id") + sink.scalar("123") + val rejected = rejectStructure() + + val drop = assertFailsWith { sink.argumentsOrThrow() } + + assertThat(drop).isSameInstanceAs(rejected) + } + + // DropArguments + + @Test + fun `DropArguments - has no stack trace`() { + val drop = exhaustValues() + + assertThat(drop.stackTrace).isEmpty() + } + + /** Opens [count] nested lists, so the next value has a depth of `count + 1`. */ + private fun openLists(count: Int) { + repeat(count) { sink.beginList() } + } + + private fun writeScalars(target: ArgumentSink, count: Int) { + repeat(count) { + target.key("k$it") + target.scalar(it) + } + } + + /** Writes one value more than the value budget allows and returns the resulting drop. */ + private fun exhaustValues(): DropArguments = + assertFailsWith { writeScalars(sink, count = MAX_ARGUMENT_VALUES + 1) } + + /** Rejects the entry for invalid structure, as a source would, and returns the resulting drop. */ + private fun rejectStructure(): DropArguments = + assertFailsWith { + sink.reject(ArgumentDropReason.INVALID_STRUCTURE, DropArguments.STRUCTURE_WARNING) + } + + private fun nestedInLists(levels: Int, leaf: Any?): Any? { + var nested = leaf + repeat(levels) { nested = listOf(nested) } + return nested + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt new file mode 100644 index 00000000000..9e3597ad6f8 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnavailableBackStackEntryMapperTest.kt @@ -0,0 +1,62 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoMoreInteractions + +class UnavailableBackStackEntryMapperTest { + + private data object Home + + private data class Detail(val id: String) + + private val logger = mock() + + @Test + fun `maps every back stack entry to null`() { + val mapper = UnavailableBackStackEntryMapper(logger = { logger }) + + val mapped = listOf(Home, Detail("1"), "home").map(mapper::map) + + assertThat(mapped).containsExactly(null, null, null) + } + + @Test + fun `reports the kotlinx serialization version as the reason for every back stack entry`() { + val mapper = UnavailableBackStackEntryMapper(logger = { logger }) + + val reasons = + listOf(Home, Detail("1"), Home).map { entry -> + UnknownEntryReasonReports.collect { mapper.map(entry) }.second + } + + assertThat(reasons) + .containsExactly( + UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION, + UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION, + UnknownEntryReason.KOTLINX_SERIALIZATION_VERSION, + ) + } + + @Test + fun `logs a warning once per back stack entry type`() { + val mapper = UnavailableBackStackEntryMapper(logger = { logger }) + + repeat(3) { + mapper.map(Home) + mapper.map(Detail("$it")) + } + + verify(logger, times(1)).log(eq(SentryLevel.WARNING), any(), eq(Home::class.java.name)) + verify(logger, times(1)) + .log(eq(SentryLevel.WARNING), any(), eq(Detail::class.java.name)) + verifyNoMoreInteractions(logger) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnknownEntryReasonReportsTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnknownEntryReasonReportsTest.kt new file mode 100644 index 00000000000..c3ddd2db8ab --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/UnknownEntryReasonReportsTest.kt @@ -0,0 +1,96 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import kotlin.concurrent.thread +import kotlin.test.assertFailsWith +import org.junit.Test + +class UnknownEntryReasonReportsTest { + + @Test + fun `collect() - returns the block's result without a reason when nothing is reported`() { + val collected = UnknownEntryReasonReports.collect { "result" } + + assertThat(collected).isEqualTo("result" to null) + } + + @Test + fun `collect() - returns the block's result with the reason reported while it ran`() { + val collected = UnknownEntryReasonReports.collect { + UnknownEntryReasonReports.report(UnknownEntryReason.NOT_SERIALIZABLE) + null + } + + assertThat(collected).isEqualTo(null to UnknownEntryReason.NOT_SERIALIZABLE) + } + + @Test + fun `collect() - returns the last reason reported when the block reports several`() { + val collected = UnknownEntryReasonReports.collect { + UnknownEntryReasonReports.report(UnknownEntryReason.NOT_SERIALIZABLE) + UnknownEntryReasonReports.report(UnknownEntryReason.GENERIC_TYPE) + null + } + + assertThat(collected.second).isEqualTo(UnknownEntryReason.GENERIC_TYPE) + } + + @Test + fun `collect() - ignores a reason reported before it was called`() { + UnknownEntryReasonReports.report(UnknownEntryReason.NOT_SERIALIZABLE) + + val collected = UnknownEntryReasonReports.collect { null } + + assertThat(collected.second).isNull() + } + + @Test + fun `collect() - does not keep the reason reported in its block after it returns`() { + val collected = UnknownEntryReasonReports.collect { + UnknownEntryReasonReports.collect { + UnknownEntryReasonReports.report(UnknownEntryReason.NOT_SERIALIZABLE) + null + } + null + } + + assertThat(collected.second).isNull() + } + + @Test + fun `collect() - does not keep the reason reported in its block after the block throws`() { + val collected = UnknownEntryReasonReports.collect { + runCatching { + UnknownEntryReasonReports.collect { + UnknownEntryReasonReports.report(UnknownEntryReason.NOT_SERIALIZABLE) + error("boom") + } + } + null + } + + assertThat(collected.second).isNull() + } + + @Test + fun `collect() - rethrows the exception thrown by the block unchanged`() { + val exception = IllegalStateException("boom") + + val thrown = + assertFailsWith { + UnknownEntryReasonReports.collect { throw exception } + } + + assertThat(thrown).isSameInstanceAs(exception) + } + + @Test + fun `collect() - ignores a reason reported on another thread while the block runs`() { + val collected = UnknownEntryReasonReports.collect { + thread { UnknownEntryReasonReports.report(UnknownEntryReason.NOT_SERIALIZABLE) }.join() + null + } + + assertThat(collected.second).isNull() + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt new file mode 100644 index 00000000000..292800f03cd --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperNamingTest.kt @@ -0,0 +1,939 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.INCOMPATIBLE_KOTLINX_ADVICE +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.LOOK_UP_FAILED +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.SERIALIZER_NOT_FOUND +import java.lang.annotation.AnnotationFormatError +import java.lang.reflect.InvocationTargetException +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.test.assertFailsWith +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.MetaSerializable +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argThat +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.verifyNoMoreInteractions + +@OptIn(ExperimentalSerializationApi::class) +@MetaSerializable +@Target(AnnotationTarget.CLASS) +private annotation class MetaSerializableRoute + +@MetaSerializableRoute private data class MetaSerializableEntry(val id: String) + +class KotlinxBackStackEntryMapperNamingTest { + + @Serializable data class WithoutSerialName(val id: String) + + @Serializable + enum class Tab { + FEED, + @SerialName("tab.search") SEARCH, + } + + @Serializable(with = CustomNameSerializer::class) + @SerialName("IgnoredSerialName") + internal class CustomSerialized + + internal object CustomNameSerializer : NamingOnlySerializer() { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + } + + @Serializable + enum class TabWithBodies { + FEED { + override val icon = "feed" + }, + SEARCH { + override val icon = "search" + }; + + abstract val icon: String + } + + data class NotSerializable(val id: String) + + enum class UnannotatedTab { + FEED, + } + + @Serializable data class Generic(val value: T) + + @Serializable @SerialName("PrivateHome") private data object PrivateHome + + // A class whose serializer's initializer threw can't be initialized again for the rest of the + // JVM's life: later lookups throw a NoClassDefFoundError instead. So each of these pairs is used + // by exactly one test, and that test only sees the initializer's own error on its first run in a + // JVM. + + /** Used by exactly one test, as its serializer can't be initialized. */ + @Serializable(with = UninitializableSerializerA::class) internal class UninitializableSerializedA + + internal object UninitializableSerializerA : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer A init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.A", PrimitiveKind.STRING) + } + + /** Used by exactly one test, as its serializer can't be initialized. */ + @Serializable(with = UninitializableSerializerB::class) internal class UninitializableSerializedB + + internal object UninitializableSerializerB : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer B init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.B", PrimitiveKind.STRING) + } + + /** Used by exactly one test, as its serializer can't be initialized. */ + @Serializable(with = UninitializableSerializerC::class) private object PrivateUninitializable + + private object UninitializableSerializerC : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer C init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable.C", PrimitiveKind.STRING) + } + + /** + * Used by exactly one test. Unlike an exception, a fatal error from the initializer isn't + * wrapped, but the serializer still can't be initialized again. + */ + @Serializable(with = FatallyUninitializableSerializer::class) + internal class FatallyUninitializableSerialized + + internal object FatallyUninitializableSerializer : + NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) throw OutOfMemoryError("serializer init failed fatally") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("fatallyUninitializable", PrimitiveKind.STRING) + } + + /** + * A serializer class, unlike an object, is constructed on each lookup, so one construction can + * fail while later ones succeed. + */ + @Serializable(with = FatalOnceSerializer::class) internal class FatalOnceSerialized + + /** + * Fails its next construction fatally once a test sets [failNextConstruction], rather than its + * first construction in the JVM, so that the test passes when run again in the same JVM. + */ + internal class FatalOnceSerializer : NamingOnlySerializer() { + init { + if (failNextConstruction.getAndSet(false)) { + throw OutOfMemoryError("serializer construction failed fatally") + } + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("fatalOnce", PrimitiveKind.STRING) + + companion object { + val failNextConstruction = AtomicBoolean() + } + } + + @Serializable(with = DescriptorThrowsIllegalStateSerializer::class) + internal class DescriptorThrowsIllegalState + + internal object DescriptorThrowsIllegalStateSerializer : + NamingOnlySerializer() { + val error = IllegalStateException("descriptor failed") + + override val descriptor: SerialDescriptor + get() = throw error + } + + @Serializable(with = DescriptorThrowsNoClassDefFoundErrorSerializer::class) + internal class DescriptorThrowsNoClassDefFoundError + + internal object DescriptorThrowsNoClassDefFoundErrorSerializer : + NamingOnlySerializer() { + val error = NoClassDefFoundError("com/example/MissingDescriptorClass") + + override val descriptor: SerialDescriptor + get() = throw error + } + + // Naming + + @Test + fun `names entries after their SerialName`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Search("shoes"))) + + assertThat(mapped) + .containsExactly(SentryBackStackEntry("Detail"), SentryBackStackEntry("Search")) + .inOrder() + } + + @Test + fun `names entries without @SerialName after their fully qualified class name`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(WithoutSerialName("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.WithoutSerialName")) + } + + @Test + fun `names constants of @Serializable enums after their enum, ignoring the constants' @SerialName`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Tab.FEED), mapper.map(Tab.SEARCH)) + + assertThat(mapped) + .containsExactly( + SentryBackStackEntry("$TEST_CLASS.Tab"), + SentryBackStackEntry("$TEST_CLASS.Tab"), + ) + } + + @Test + fun `names constants of @Serializable enums that have bodies after their enum`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { if (it == TabWithBodies::class.java) TabWithBodies.serializer() else null } + val mapper = fixture.mapper + + val mapped = mapper.map(TabWithBodies.SEARCH) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("$TEST_CLASS.TabWithBodies")) + } + + @Test + fun `names entries of a class with a custom serializer after its descriptor, ignoring the class's @SerialName`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(CustomSerialized()) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("custom.Name")) + } + + @Test + fun `names entries of a private @Serializable object after its SerialName`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(PrivateHome) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("PrivateHome")) + verifyNoInteractions(fixture.logger) + } + + @Test + fun `returns null for entries that aren't @Serializable even if the lookup has a serializer`() { + // kotlinx.serialization has serializers for built-in types and enums that aren't @Serializable. + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { String.serializer() } + val mapper = fixture.mapper + + val mapped = + listOf( + mapper.map("home"), + mapper.map(42), + mapper.map(UnannotatedTab.FEED), + mapper.map(NotSerializable("1")), + ) + + assertThat(mapped).containsExactly(null, null, null, null) + } + + @Test + fun `returns null for entries of a class marked with a @MetaSerializable annotation`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = mapper.map(MetaSerializableEntry("1")) + + assertThat(mapped).isNull() + } + + // Name lookup caching and logging + + @Test + fun `looks up each @Serializable type once, including failed lookups`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { if (it == Search::class.java) null else fixture.serializers[it] } + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Home) + mapper.map(Detail("$it")) + mapper.map(Search("$it")) + } + + assertThat(fixture.lookedUpTypes) + .containsExactly(Home::class.java, Detail::class.java, Search::class.java) + } + + @Test + fun `doesn't look up generic @Serializable types`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { mapper.map(Generic("$it")) } + + assertThat(fixture.lookedUpTypes).isEmpty() + } + + @Test + fun `doesn't look up types that aren't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(NotSerializable("$it")) + mapper.map("home") + mapper.map(42) + mapper.map(UnannotatedTab.FEED) + } + + assertThat(fixture.lookedUpTypes).isEmpty() + } + + @Test + fun `looks up an enum that has bodies once for all its constants`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + mapper.map(TabWithBodies.FEED) + mapper.map(TabWithBodies.SEARCH) + + assertThat(fixture.lookedUpTypes).containsExactly(TabWithBodies::class.java) + } + + @Test + fun `logs a warning once per type that isn't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(NotSerializable("$it")) + mapper.map("home") + mapper.map(UnannotatedTab.FEED) + mapper.map(Home) + } + + verifyNotSerializableLoggedOnce(fixture, NotSerializable::class.java) + verifyNotSerializableLoggedOnce(fixture, String::class.java) + verifyNotSerializableLoggedOnce(fixture, UnannotatedTab::class.java) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `logs a warning once per @Serializable type whose serializer can't be found`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { if (it == Detail::class.java) null else fixture.serializers[it] } + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Detail("$it")) + mapper.map(Home) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + isNull(), + any(), + eq(Detail::class.java.name), + eq(SERIALIZER_NOT_FOUND), + ) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `logs a warning once per generic @Serializable type`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + repeat(3) { + mapper.map(Generic("$it")) + mapper.map(Home) + } + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + argThat { contains(GENERIC_TYPE) }, + eq(Generic::class.java.name), + ) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `advises using a custom mapper when a generic @Serializable type can't be named`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + mapper.map(Generic("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log(eq(SentryLevel.WARNING), message.capture(), eq(Generic::class.java.name)) + assertThat(message.firstValue).contains("Use a custom BackStackEntryMapper") + } + + @Test + fun `advises making the type @Serializable when a type that isn't @Serializable can't be named`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + mapper.map(NotSerializable("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log(eq(SentryLevel.WARNING), message.capture(), eq(NotSerializable::class.java.name)) + assertThat(message.firstValue).contains("Add @Serializable") + } + + @Test + fun `advises seeing the docs when a @Serializable type's serializer can't be found`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { null } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + isNull(), + message.capture(), + eq(Detail::class.java.name), + eq(SERIALIZER_NOT_FOUND), + ) + assertThat(message.firstValue).contains("See BackStackEntryMapper.SerialName's documentation") + assertThat(message.firstValue).doesNotContain("Add @Serializable") + } + + @Test + fun `advises seeing the attached error without compatibility advice when a type's name lookup throws an exception`() { + val error = IllegalStateException("lookup failed") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + eq(error), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_FAILED), + ) + assertThat(message.firstValue).contains("See the attached error") + assertThat(message.firstValue).doesNotContain(INCOMPATIBLE_KOTLINX_ADVICE) + } + + @Test + fun `advises checking kotlinx serialization compatibility when a type's name lookup throws a LinkageError`() { + val error = NoSuchMethodError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + mapper.map(Detail("1")) + + val message = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + eq(error), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_FAILED), + ) + assertThat(message.firstValue).contains("See the attached error") + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + } + + // @Serializable annotation checks that throw + + @Test + fun `returns null and logs the error with compatibility advice once for a type whose annotation check throws a LinkageError`() { + val error = NoClassDefFoundError("com/example/MissingAnnotation") + val fixture = KotlinxMapperFixture.create(isAnnotatedSerializable = { throw error }) + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + val message = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + eq(error), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_FAILED), + ) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `returns null and logs the error without compatibility advice once for a type whose annotation check throws an exception`() { + val error = AnnotationFormatError("malformed annotation") + val fixture = KotlinxMapperFixture.create(isAnnotatedSerializable = { throw error }) + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + val message = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + eq(error), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_FAILED), + ) + assertThat(message.firstValue).doesNotContain(INCOMPATIBLE_KOTLINX_ADVICE) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `doesn't check or look up a type again after its annotation check throws`() { + val checkedTypes = mutableListOf>() + val fixture = + KotlinxMapperFixture.create( + isAnnotatedSerializable = { + checkedTypes += it + throw NoClassDefFoundError() + }, + ) + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(checkedTypes).containsExactly(Detail::class.java) + assertThat(fixture.lookedUpTypes).isEmpty() + } + + @Test + fun `keeps naming other types after a type's annotation check throws`() { + val fixture = + KotlinxMapperFixture.create( + isAnnotatedSerializable = { + if (it == Detail::class.java) throw AnnotationFormatError("malformed annotation") + true + }, + ) + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home)) + + assertThat(mapped).containsExactly(null, SentryBackStackEntry("Home")).inOrder() + } + + @Test + fun `propagates fatal errors an annotation check throws`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create(isAnnotatedSerializable = { throw error }) + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer lookup errors that only affect one type + + @Test + fun `returns null and logs the error once for a type whose name lookup throws a LinkageError`() { + val error = NoSuchMethodError("kotlinx.serialization.KSerializer.getDescriptor()") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `returns null and logs the error once for a type whose name lookup throws ReflectiveOperationException`() { + val error = NoSuchMethodException("serializer") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `returns null and logs the error once for a type whose name lookup throws an unchecked exception`() { + val error = TypeNotPresentException("com.example.RemovedSerializer", null) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `doesn't look up a type again after its name lookup throws`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw NoSuchMethodError() } + val mapper = fixture.mapper + + repeat(3) { mapper.map(Detail("$it")) } + + assertThat(fixture.lookedUpTypes).containsExactly(Detail::class.java) + } + + @Test + fun `keeps naming other types after a type's name lookup throws`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + if (it == Detail::class.java) throw NoSuchMethodError() else fixture.serializers[it] + } + val mapper = fixture.mapper + + val mapped = listOf(mapper.map(Detail("1")), mapper.map(Home), mapper.map(Search("shoes"))) + + assertThat(mapped) + .containsExactly(null, SentryBackStackEntry("Home"), SentryBackStackEntry("Search")) + .inOrder() + } + + @Test + fun `restores the interrupt status when a type's name lookup throws InterruptedException`() { + val error = InterruptedException() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + try { + assertThat(mapper.map(Detail("1"))).isNull() + assertThat(Thread.currentThread().isInterrupted).isTrue() + verifyLookUpErrorLoggedOnce(fixture, error) + } finally { + Thread.interrupted() + } + } + + @Test + fun `propagates fatal errors a name lookup throws`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer lookup errors wrapped in an InvocationTargetException + + @Test + fun `returns null and logs the cause once for a type whose name lookup throws a wrapped exception`() { + val cause = IllegalStateException("serializer() failed") + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(cause) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, cause) + } + + @Test + fun `returns null and logs the cause once, with compatibility advice, for a type whose name lookup throws a wrapped LinkageError`() { + // An ExceptionInInitializerError, which a serializer object's failing initializer causes, is a + // LinkageError. + val cause = ExceptionInInitializerError(IllegalStateException("serializer init failed")) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(cause) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + val message = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + eq(cause), + message.capture(), + eq(Detail::class.java.name), + eq(LOOK_UP_FAILED), + ) + assertThat(message.firstValue).contains(INCOMPATIBLE_KOTLINX_ADVICE) + verifyNoMoreInteractions(fixture.logger) + } + + @Test + fun `returns null and logs the InvocationTargetException once when a name lookup throws one without a cause`() { + val error = InvocationTargetException(null) + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw error } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(Detail("$it")) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce(fixture, error) + } + + @Test + fun `restores the interrupt status when a type's name lookup throws a wrapped InterruptedException`() { + val error = InterruptedException() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(error) } + val mapper = fixture.mapper + + try { + assertThat(mapper.map(Detail("1"))).isNull() + assertThat(Thread.currentThread().isInterrupted).isTrue() + verifyLookUpErrorLoggedOnce(fixture, error) + } finally { + Thread.interrupted() + } + } + + @Test + fun `propagates fatal errors a name lookup throws wrapped in an InvocationTargetException`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw InvocationTargetException(error) } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer descriptors that throw + + @Test + fun `returns null and logs the error once for a type whose serializer's descriptor throws an exception`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { DescriptorThrowsIllegalStateSerializer } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(DescriptorThrowsIllegalState()) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce( + fixture, + DescriptorThrowsIllegalStateSerializer.error, + DescriptorThrowsIllegalState::class.java, + ) + } + + @Test + fun `returns null and logs the error once for a type whose serializer's descriptor throws NoClassDefFoundError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { DescriptorThrowsNoClassDefFoundErrorSerializer } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(DescriptorThrowsNoClassDefFoundError()) } + + assertThat(mapped).containsExactly(null, null, null) + verifyLookUpErrorLoggedOnce( + fixture, + DescriptorThrowsNoClassDefFoundErrorSerializer.error, + DescriptorThrowsNoClassDefFoundError::class.java, + ) + } + + @Test + fun `propagates fatal errors thrown by a serializer's descriptor`() { + val error = OutOfMemoryError() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { + object : NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = throw error + } + } + val mapper = fixture.mapper + + val thrown = assertFailsWith { mapper.map(Detail("1")) } + + assertThat(thrown).isSameInstanceAs(error) + } + + // Serializer descriptors whose shape throws + + @Test + fun `names an entry after its SerialName without reading its descriptor's shape`() { + val serializer = ShapeThrowingDetailSerializer() + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { serializer } + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(serializer.shapeReads).isEqualTo(0) + } + + // Integration: serializer initializers that throw through real reflection + // + // Unlike the tests above, these look up serializers with the mapper's default lookup, + // reflectiveSerializerOrNull, either directly or wrapped to record each lookup, so its real + // reflection throws the errors the mapper must handle. + + @Test + fun `returns null without looking up again for a type whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create() + // Wraps the default lookup, rather than using it directly, so that lookedUpTypes records each + // lookup. + fixture.lookUp = { reflectiveSerializerOrNull(it) } + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(UninitializableSerializedA()) } + + assertThat(mapped).containsExactly(null, null, null) + assertThat(fixture.lookedUpTypes).containsExactly(UninitializableSerializedA::class.java) + } + + @Test + fun `logs the initializer's error once for a type whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + repeat(3) { mapper.map(UninitializableSerializedB()) } + + val logged = loggedLookUpError(fixture, UninitializableSerializedB::class.java) + assertThat(logged).isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(logged).hasCauseThat().isInstanceOf(IllegalStateException::class.java) + assertThat(logged).hasCauseThat().hasMessageThat().isEqualTo("serializer B init failed") + } + + @Test + fun `logs the initializer's error once for a private object whose serializer's initializer throws`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val mapped = List(3) { mapper.map(PrivateUninitializable) } + + assertThat(mapped).containsExactly(null, null, null) + val logged = loggedLookUpError(fixture, PrivateUninitializable::class.java) + assertThat(logged).isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(logged).hasCauseThat().isInstanceOf(IllegalStateException::class.java) + assertThat(logged).hasCauseThat().hasMessageThat().isEqualTo("serializer C init failed") + } + + @Test + fun `propagates a fatal error from a type's serializer initializer`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + + val thrown = + assertFailsWith { mapper.map(FatallyUninitializableSerialized()) } + + assertThat(thrown).hasMessageThat().isEqualTo("serializer init failed fatally") + } + + @Test + fun `names a type after its serializer lookup previously threw a fatal error`() { + val fixture = KotlinxMapperFixture.create(useDefaultLookUp = true) + val mapper = fixture.mapper + FatalOnceSerializer.failNextConstruction.set(true) + assertFailsWith { mapper.map(FatalOnceSerialized()) } + + val mapped = mapper.map(FatalOnceSerialized()) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("fatalOnce")) + } + + /** Verifies that the look-up failure for [type] was logged once, with [error] itself. */ + private fun verifyLookUpErrorLoggedOnce( + fixture: KotlinxMapperFixture, + error: Throwable, + type: Class<*> = Detail::class.java, + ) { + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + eq(error), + any(), + eq(type.name), + eq(LOOK_UP_FAILED), + ) + } + + /** Returns the error attached to the look-up failure logged, once, for [type]. */ + private fun loggedLookUpError( + fixture: KotlinxMapperFixture, + type: Class<*> = Detail::class.java, + ): Throwable { + val logged = argumentCaptor() + verify(fixture.logger) + .log( + eq(SentryLevel.WARNING), + logged.capture(), + any(), + eq(type.name), + eq(LOOK_UP_FAILED), + ) + return logged.firstValue + } + + private fun verifyNotSerializableLoggedOnce(fixture: KotlinxMapperFixture, type: Class<*>) { + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.WARNING), + argThat { contains(NOT_SERIALIZABLE) }, + eq(type.name), + ) + } + + private companion object { + val TEST_CLASS: String = KotlinxBackStackEntryMapperNamingTest::class.java.name + + const val NOT_SERIALIZABLE = "because the type is not @Serializable" + + const val GENERIC_TYPE = "because the type has type parameters" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt new file mode 100644 index 00000000000..e2e678dd9ca --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperProbeTest.kt @@ -0,0 +1,127 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryIntegrationPackageStorage +import io.sentry.SentryLevel +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.kotlinx.FakeCompatibilityProbe.Inconclusive +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxBackStackEntryMapper.Companion.NAME_LOOKUP_CAPABILITY +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_SERIALIZER_NOT_FOUND +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxMapperDiagnostics.Companion.PROBE_THREW +import kotlin.test.assertFailsWith +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.mockito.kotlin.argThat +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.isNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions + +/** How [KotlinxBackStackEntryMapper] acts on what its [KotlinxCompatibilityProbe] finds. */ +class KotlinxBackStackEntryMapperProbeTest { + + @Before + fun clearIntegrations() { + SentryIntegrationPackageStorage.getInstance().clearStorage() + } + + @After + fun clearIntegrationsAfterTest() { + SentryIntegrationPackageStorage.getInstance().clearStorage() + } + + // Name lookup check + + @Test + fun `logs nothing when created for a kotlinx serialization version the name lookup check finds compatible`() { + val fixture = KotlinxMapperFixture.create(probe = FakeCompatibilityProbe()) + + fixture.mapper + + verifyNoInteractions(fixture.logger) + } + + @Test + fun `throws the probe's LinkageError when created for a kotlinx serialization version that can't support name lookups`() { + val error = NoSuchMethodError("serializerOrNull") + val probe = FakeCompatibilityProbe(nameLookupError = error) + + val thrown = + assertFailsWith { + KotlinxBackStackEntryMapper(logger = { mock() }, probe = probe) + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `doesn't log when created for a kotlinx serialization version that can't support name lookups`() { + // BuiltInBackStackEntryMappers logs the error it catches, so the mapper doesn't log it too. + val logger = mock() + val probe = FakeCompatibilityProbe(nameLookupError = NoSuchMethodError()) + + assertFailsWith { + KotlinxBackStackEntryMapper(logger = { logger }, probe = probe) + } + + verifyNoInteractions(logger) + } + + @Test + fun `names entries when the name lookup check is inconclusive`() { + val probe = + FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(IllegalStateException())) + val fixture = KotlinxMapperFixture.create(probe = probe) + val mapper = fixture.mapper + + val mapped = mapper.map(Detail("1")) + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + } + + @Test + fun `logs at debug level with the error when the name lookup check throws inconclusively`() { + val error = IllegalStateException("check failed") + val probe = FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(error)) + + val fixture = KotlinxMapperFixture.create(probe = probe) + + val message = argumentCaptor() + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.DEBUG), + eq(error), + message.capture(), + eq(NAME_LOOKUP_CAPABILITY), + eq(PROBE_THREW), + ) + assertThat(message.firstValue).startsWith(INCONCLUSIVE_PROBE) + } + + @Test + fun `logs at debug level when the name lookup check can't find a probe type's serializer`() { + val probe = FakeCompatibilityProbe(nameLookupInconclusive = Inconclusive(error = null)) + + val fixture = KotlinxMapperFixture.create(probe = probe) + + verify(fixture.logger, times(1)) + .log( + eq(SentryLevel.DEBUG), + isNull(), + argThat { startsWith(INCONCLUSIVE_PROBE) }, + eq(NAME_LOOKUP_CAPABILITY), + eq(PROBE_SERIALIZER_NOT_FOUND), + ) + } + + private companion object { + const val NAV3_INTEGRATION_PREFIX = "ComposeNavigation3" + + const val INCONCLUSIVE_PROBE = "Nav3 couldn't verify kotlinx.serialization support for %s" + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperUnknownEntryReasonTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperUnknownEntryReasonTest.kt new file mode 100644 index 00000000000..716a572e13b --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxBackStackEntryMapperUnknownEntryReasonTest.kt @@ -0,0 +1,182 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.SentryBackStackEntry +import io.sentry.compose.navigation3.internal.backstack.UnknownEntryReason +import io.sentry.compose.navigation3.internal.backstack.UnknownEntryReasonReports +import java.lang.annotation.AnnotationFormatError +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Test + +class KotlinxBackStackEntryMapperUnknownEntryReasonTest { + + data class NotSerializable(val id: String) + + @Serializable data class Generic(val value: T) + + private val throwingDescriptorSerializer = + object : NamingOnlySerializer() { + override val descriptor: SerialDescriptor + get() = error("descriptor failed") + } + + @Test + fun `reports no reason for an entry it names`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isEqualTo(SentryBackStackEntry("Detail")) + assertThat(reason).isNull() + } + + @Test + fun `reports not serializable for an entry whose type isn't @Serializable`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(NotSerializable("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.NOT_SERIALIZABLE) + } + + @Test + fun `reports generic type for an entry whose @Serializable type has type parameters`() { + val fixture = KotlinxMapperFixture.create() + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Generic("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.GENERIC_TYPE) + } + + @Test + fun `reports serializer not found for an entry whose serializer lookup finds none`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { null } + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_NOT_FOUND) + } + + @Test + fun `reports serializer lookup threw for an entry whose serializer lookup throws`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw IllegalStateException("lookup failed") } + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_LOOKUP_THREW) + } + + @Test + fun `reports serializer lookup threw for an entry whose serializer lookup throws a LinkageError`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw NoSuchMethodError() } + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_LOOKUP_THREW) + } + + @Test + fun `reports serializer lookup threw for an entry whose serializer's descriptor throws`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throwingDescriptorSerializer } + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_LOOKUP_THREW) + } + + @Test + fun `reports serializer lookup threw for an entry whose annotation check throws an exception`() { + val fixture = + KotlinxMapperFixture.create( + isAnnotatedSerializable = { throw AnnotationFormatError("malformed annotation") }, + ) + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_LOOKUP_THREW) + } + + @Test + fun `reports serializer lookup threw for an entry whose annotation check throws a LinkageError`() { + val fixture = + KotlinxMapperFixture.create( + isAnnotatedSerializable = { throw NoClassDefFoundError("com/example/MissingAnnotation") }, + ) + val mapper = fixture.mapper + + val (mapped, reason) = UnknownEntryReasonReports.collect { mapper.map(Detail("1")) } + + assertThat(mapped).isNull() + assertThat(reason).isEqualTo(UnknownEntryReason.SERIALIZER_LOOKUP_THREW) + } + + // Later entries of a type that can't be named + + @Test + fun `reports the reason again for every later entry of a type that can't be named`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { if (it == Detail::class.java) null else fixture.serializers[it] } + val mapper = fixture.mapper + + val entries = + listOf( + Detail("1"), + NotSerializable("1"), + Generic("1"), + Detail("2"), + NotSerializable("2"), + Generic("2"), + ) + + val reasons = entries.map { entry -> + UnknownEntryReasonReports.collect { mapper.map(entry) }.second + } + + assertThat(reasons) + .containsExactly( + UnknownEntryReason.SERIALIZER_NOT_FOUND, + UnknownEntryReason.NOT_SERIALIZABLE, + UnknownEntryReason.GENERIC_TYPE, + UnknownEntryReason.SERIALIZER_NOT_FOUND, + UnknownEntryReason.NOT_SERIALIZABLE, + UnknownEntryReason.GENERIC_TYPE, + ) + .inOrder() + } + + @Test + fun `reports the reason again for every later entry of a type whose serializer lookup threw`() { + val fixture = KotlinxMapperFixture.create() + fixture.lookUp = { throw IllegalStateException("lookup failed") } + val mapper = fixture.mapper + + val reasons = List(3) { UnknownEntryReasonReports.collect { mapper.map(Detail("$it")) }.second } + + assertThat(reasons) + .containsExactly( + UnknownEntryReason.SERIALIZER_LOOKUP_THREW, + UnknownEntryReason.SERIALIZER_LOOKUP_THREW, + UnknownEntryReason.SERIALIZER_LOOKUP_THREW, + ) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt new file mode 100644 index 00000000000..97308d4461b --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxCompatibilityProbeTest.kt @@ -0,0 +1,128 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.Companion.ProbeClass +import io.sentry.compose.navigation3.internal.backstack.kotlinx.KotlinxCompatibilityProbe.Companion.ProbeObject +import kotlin.test.assertFailsWith +import org.junit.Test + +/** + * Runs the default probe against the kotlinx.serialization version on the test classpath, which CI + * also sets to the latest stable release and any newer release candidate with + * `-Pnav3TestKotlinxVersion`. + */ +class KotlinxCompatibilityProbeTest { + + // nameLookupLinkageError() + + @Test + fun `nameLookupLinkageError() - returns null without an inconclusive result for a compatible kotlinx serialization version`() { + val inconclusive = mutableListOf() + + val error = KotlinxCompatibilityProbe.nameLookupLinkageError { inconclusive += it } + + assertThat(error).isNull() + assertThat(inconclusive).isEmpty() + } + + @Test + fun `nameLookupLinkageError() - returns the LinkageError a probe type's serializer lookup throws`() { + val error = NoSuchMethodError("serializerOrNull") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } + + assertThat(returned).isSameInstanceAs(error) + assertThat(inconclusive).isEmpty() + } + + @Test + fun `nameLookupLinkageError() - reports a non-fatal exception as inconclusive and returns null`() { + val error = IllegalStateException("lookup failed") + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) { inconclusive += it } + + assertThat(returned).isNull() + assertThat(inconclusive).containsExactly(error) + } + + @Test + fun `nameLookupLinkageError() - propagates a fatal error that isn't a LinkageError`() { + val error = OutOfMemoryError() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw error }) {} + } + + assertThat(thrown).isSameInstanceAs(error) + } + + @Test + fun `nameLookupLinkageError() - reports a missing probe serializer as inconclusive without an error`() { + val inconclusive = mutableListOf() + + val returned = + KotlinxCompatibilityProbe.nameLookupLinkageError( + { type -> if (type == ProbeObject::class.java) null else reflectiveSerializerOrNull(type) }, + ) { + inconclusive += it + } + + assertThat(returned).isNull() + assertThat(inconclusive).containsExactly(null) + } + + @Test + fun `nameLookupLinkageError() - doesn't report an exception onInconclusive throws for a missing probe serializer back to onInconclusive`() { + val error = IllegalStateException("callback failed") + val inconclusive = mutableListOf() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ null }) { + inconclusive += it + throw error + } + } + + assertThat(thrown).isSameInstanceAs(error) + assertThat(inconclusive).containsExactly(null) + } + + @Test + fun `nameLookupLinkageError() - doesn't report an exception onInconclusive throws for a lookup exception back to onInconclusive`() { + val lookupError = IllegalStateException("lookup failed") + val callbackError = IllegalArgumentException("callback failed") + val inconclusive = mutableListOf() + + val thrown = + assertFailsWith { + KotlinxCompatibilityProbe.nameLookupLinkageError({ throw lookupError }) { + inconclusive += it + throw callbackError + } + } + + assertThat(thrown).isSameInstanceAs(callbackError) + assertThat(inconclusive).containsExactly(lookupError) + } + + // Probe types + + @Test + fun `the serializer lookup names the probe's types`() { + // A probe type the lookup couldn't find would make the check pass without looking up a name. + val names = + listOf(ProbeClass::class.java, ProbeObject::class.java).map { + reflectiveSerializerOrNull(it)?.descriptor?.serialName + } + + assertThat(names) + .containsExactly(ProbeClass::class.qualifiedName, ProbeObject::class.qualifiedName) + .inOrder() + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt new file mode 100644 index 00000000000..9fb1c9d9656 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxMapperFixture.kt @@ -0,0 +1,155 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import io.sentry.ILogger +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.encoding.encodeStructure +import org.mockito.AdditionalAnswers.delegatesTo +import org.mockito.Mockito +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +/** + * Delegates to [delegate], recording each serialized value and throwing [error], if set, for the + * values [failsFor] accepts. + */ +internal class RecordingSerializer(private val delegate: KSerializer) : + KSerializer by delegate { + val serialized = mutableListOf() + var error: Throwable? = null + var failsFor: (T) -> Boolean = { true } + + override fun serialize(encoder: Encoder, value: T) { + serialized += value + error?.takeIf { failsFor(value) }?.let { throw it } + delegate.serialize(encoder, value) + } +} + +/** + * Serializes [Detail] with a descriptor whose shape, its `elementsCount` and `kind`, throws + * [elementsCountError] and [kindError] when set. Counts every read of the shape in [shapeReads]. + * Encoding reads the descriptor's `kind`, so it throws [kindError] too. + */ +@OptIn(ExperimentalSerializationApi::class) +internal class ShapeThrowingDetailSerializer( + private val elementsCountError: Throwable? = null, + private val kindError: Throwable? = null, +) : KSerializer { + var shapeReads = 0 + + private val delegate = Detail.serializer().descriptor + + override val descriptor: SerialDescriptor = + Mockito.mock(SerialDescriptor::class.java, delegatesTo(delegate)).apply { + doAnswer { + shapeReads++ + elementsCountError?.let { error -> throw error } + delegate.elementsCount + } + .whenever(this) + .elementsCount + doAnswer { + shapeReads++ + kindError?.let { error -> throw error } + delegate.kind + } + .whenever(this) + .kind + } + + override fun serialize(encoder: Encoder, value: Detail) { + encoder.encodeStructure(descriptor) { encodeStringElement(descriptor, 0, value.id) } + } + + override fun deserialize(decoder: Decoder): Detail = throw UnsupportedOperationException() +} + +/** + * A controllable [KotlinxCompatibilityProbe] that reports compatibility by default. Set + * [nameLookupError] to fail the check, or [nameLookupInconclusive] to report it inconclusive. + */ +internal class FakeCompatibilityProbe( + private val nameLookupError: LinkageError? = null, + private val nameLookupInconclusive: Inconclusive? = null, +) : KotlinxCompatibilityProbe { + + override fun nameLookupLinkageError(onInconclusive: (Throwable?) -> Unit): LinkageError? { + nameLookupError?.let { + return it + } + nameLookupInconclusive?.let { onInconclusive(it.error) } + return null + } + + /** Why the name check is inconclusive: [error], or `null` if a probe serializer wasn't found. */ + class Inconclusive(val error: Throwable?) +} + +/** + * A [KotlinxBackStackEntryMapper] whose serializer lookup returns [serializers] by default. The + * mapper only looks up `@Serializable` types, so [lookUp] never sees any others. Its compatibility + * [probe] finds the app's kotlinx.serialization version compatible by default. + * + * With `useDefaultLookUp = true`, the mapper uses its real serializer lookup, so [lookUp] and + * [lookedUpTypes] are unused. With an `isAnnotatedSerializable` check, the mapper uses it instead + * of reading each type's `@Serializable` annotation. + */ +internal class KotlinxMapperFixture +private constructor( + useDefaultLookUp: Boolean, + val probe: KotlinxCompatibilityProbe, + isAnnotatedSerializable: ((Class<*>) -> Boolean)?, +) { + val logger = mock() + + val detailSerializer = RecordingSerializer(Detail.serializer()) + val searchSerializer = RecordingSerializer(Search.serializer()) + val serializers: Map, KSerializer<*>> = + mapOf( + Home::class.java to Home.serializer(), + Detail::class.java to detailSerializer, + Search::class.java to searchSerializer, + WithContextual::class.java to WithContextual.serializer(), + ) + + val lookedUpTypes = mutableListOf>() + var lookUp: (Class<*>) -> KSerializer<*>? = { serializers[it] } + + val mapper: KotlinxBackStackEntryMapper + + init { + val lookUpSerializer: (Class<*>) -> KSerializer<*>? = + if (useDefaultLookUp) { + ::reflectiveSerializerOrNull + } else { + { + lookedUpTypes += it + lookUp(it) + } + } + mapper = + if (isAnnotatedSerializable == null) { + KotlinxBackStackEntryMapper(lookUpSerializer, { logger }, probe) + } else { + KotlinxBackStackEntryMapper( + lookUpSerializer, + { logger }, + probe, + isAnnotatedSerializable, + ) + } + } + + companion object { + fun create( + useDefaultLookUp: Boolean = false, + probe: KotlinxCompatibilityProbe = FakeCompatibilityProbe(), + isAnnotatedSerializable: ((Class<*>) -> Boolean)? = null, + ) = KotlinxMapperFixture(useDefaultLookUp, probe, isAnnotatedSerializable) + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt new file mode 100644 index 00000000000..f5d66331353 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxSerializerLookupTest.kt @@ -0,0 +1,360 @@ +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import com.google.common.truth.Truth.assertThat +import java.lang.reflect.InvocationTargetException +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import org.junit.Assert.assertThrows +import org.junit.Test + +class KotlinxSerializerLookupTest { + + @Serializable + @SerialName("Route") + sealed interface Route { + @Serializable @SerialName("route.settings") data object Settings : Route + } + + @Serializable + @SerialName("Tab") + enum class Tab { + FEED, + } + + @Serializable + @SerialName("TabWithBodies") + enum class TabWithBodies { + FEED { + override val icon = "feed" + }; + + abstract val icon: String + } + + @Serializable(with = CustomSerializer::class) internal data class CustomSerialized(val id: String) + + internal object CustomSerializer : NamingOnlySerializer() { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("custom.Name", PrimitiveKind.STRING) + } + + @Serializable @SerialName("PrivateObject") private data object PrivateObject + + @Serializable @SerialName("PrivateClass") private data class PrivateClass(val id: String) + + data class NotSerializable(val id: String) + + /** + * Looks like a private object to kotlinx.serialization, as it has a private static `INSTANCE` + * field of its own type, but lacks the `serializer()` method the compiler plugin generates. + */ + class InaccessibleInstanceWithoutSerializer private constructor() { + private companion object { + @Suppress("unused") private val INSTANCE = InaccessibleInstanceWithoutSerializer() + } + } + + enum class UnannotatedTab { + FEED, + } + + @Serializable data class Generic(val value: T) + + // A class whose serializer's initializer threw can't be initialized again for the rest of the + // JVM's life, so each test that triggers one gets its own pair, separate from other suites'. + + @Serializable(with = UninitializableSerializer::class) internal class Uninitializable + + internal object UninitializableSerializer : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("uninitializable", PrimitiveKind.STRING) + } + + @Serializable(with = IncompatiblyUninitializableSerializer::class) + internal class IncompatiblyUninitializable + + internal object IncompatiblyUninitializableSerializer : + NamingOnlySerializer() { + init { + // As for FatallyUninitializableSerializer, the error isn't wrapped in an + // ExceptionInInitializerError. + if (System.nanoTime() != 0L) throw NoSuchMethodError("serializer init failed to link") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("incompatible", PrimitiveKind.STRING) + } + + @Serializable(with = PrivateUninitializableSerializer::class) + private object PrivateUninitializable + + private object PrivateUninitializableSerializer : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("private serializer init failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("private.uninitializable", PrimitiveKind.STRING) + } + + @Serializable(with = FatallyUninitializableSerializer::class) private object PrivateFatal + + private object FatallyUninitializableSerializer : NamingOnlySerializer() { + init { + // Unlike an exception, an error thrown by an initializer isn't wrapped in an + // ExceptionInInitializerError. + if (System.nanoTime() != 0L) throw OutOfMemoryError("serializer init failed fatally") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("fatal", PrimitiveKind.STRING) + } + + @Serializable(with = PublicFatallyUninitializableSerializer::class) + internal class FatallyUninitializable + + internal object PublicFatallyUninitializableSerializer : + NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) throw OutOfMemoryError("class serializer init failed fatally") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("fatal.class", PrimitiveKind.STRING) + } + + // A serializer class, unlike an object, is constructed by the type's serializer() method, so an + // exception its constructor throws reaches reflection without an ExceptionInInitializerError. + + @Serializable(with = FailingConstructionSerializer::class) internal class FailingConstruction + + internal class FailingConstructionSerializer : NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) error("serializer construction failed") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("failingConstruction", PrimitiveKind.STRING) + } + + @Serializable(with = InterruptedConstructionSerializer::class) + internal class InterruptedConstruction + + internal class InterruptedConstructionSerializer : + NamingOnlySerializer() { + init { + if (System.nanoTime() != 0L) throw InterruptedException("serializer construction interrupted") + } + + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("interruptedConstruction", PrimitiveKind.STRING) + } + + // @Serializable types + + @Test + fun `returns the serializer of a @Serializable class`() { + val serializer = reflectiveSerializerOrNull(Detail::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Detail") + } + + @Test + fun `returns the serializer of a @Serializable object`() { + val serializer = reflectiveSerializerOrNull(Home::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Home") + } + + @Test + fun `returns the subtype's own serializer for a @Serializable sealed subtype`() { + val serializer = reflectiveSerializerOrNull(Route.Settings::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("route.settings") + } + + @Test + fun `returns the serializer of a @Serializable enum`() { + val serializer = reflectiveSerializerOrNull(Tab::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("Tab") + } + + @Test + fun `returns the custom serializer of a class that is @Serializable with a custom serializer`() { + val serializer = reflectiveSerializerOrNull(CustomSerialized::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("custom.Name") + } + + @Test + fun `returns the serializer of a private @Serializable object`() { + val serializer = reflectiveSerializerOrNull(PrivateObject::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateObject") + } + + @Test + fun `returns the serializer of a private @Serializable class`() { + val serializer = reflectiveSerializerOrNull(PrivateClass::class.java) + + assertThat(serializer?.descriptor?.serialName).isEqualTo("PrivateClass") + } + + // Types that aren't @Serializable but that kotlinx.serialization can serialize + + @Test + fun `returns kotlinx serialization's serializers for built-in types`() { + val types = listOf(String::class.java, Integer::class.java) + + val serialNames = types.map { reflectiveSerializerOrNull(it)?.descriptor?.serialName } + + assertThat(serialNames).containsExactly("kotlin.String", "kotlin.Int").inOrder() + } + + @Test + fun `returns kotlinx serialization's enum serializer for an enum that isn't @Serializable`() { + val serializer = reflectiveSerializerOrNull(UnannotatedTab::class.java) + + assertThat(serializer?.descriptor?.serialName) + .isEqualTo(UnannotatedTab::class.java.canonicalName) + } + + // Types without a serializer to return + + @Test + fun `returns null for a class that isn't @Serializable`() { + val serializer = reflectiveSerializerOrNull(NotSerializable::class.java) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for the class of a @Serializable enum's constant that has a body`() { + val serializer = reflectiveSerializerOrNull(TabWithBodies.FEED.javaClass) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for a generic @Serializable class`() { + val serializer = reflectiveSerializerOrNull(Generic::class.java) + + assertThat(serializer).isNull() + } + + @Test + fun `returns null for a generic built-in collection type`() { + val serializer = reflectiveSerializerOrNull(ArrayList::class.java) + + assertThat(serializer).isNull() + } + + // Serializer initializers that throw + + @Test + fun `throws a class's serializer initializer error wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(Uninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .isEqualTo("serializer init failed") + } + + @Test + fun `throws a class's serializer initializer NoSuchMethodError wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(IncompatiblyUninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(NoSuchMethodError::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer init failed to link") + } + + @Test + fun `throws a private object's serializer initializer error wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(PrivateUninitializable::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(ExceptionInInitializerError::class.java) + assertThat(thrown) + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .isEqualTo("private serializer init failed") + } + + @Test + fun `throws an exception from a class's serializer construction wrapped in an InvocationTargetException`() { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(FailingConstruction::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(IllegalStateException::class.java) + assertThat(thrown).hasCauseThat().hasMessageThat().isEqualTo("serializer construction failed") + } + + @Test + fun `restores the interrupt status when a class's serializer construction is interrupted`() { + try { + val thrown = + assertThrows(InvocationTargetException::class.java) { + reflectiveSerializerOrNull(InterruptedConstruction::class.java) + } + + assertThat(thrown).hasCauseThat().isInstanceOf(InterruptedException::class.java) + assertThat(Thread.currentThread().isInterrupted).isTrue() + } finally { + Thread.interrupted() + } + } + + @Test + fun `propagates a class's fatal serializer initializer error unwrapped`() { + val thrown = + assertThrows(OutOfMemoryError::class.java) { + reflectiveSerializerOrNull(FatallyUninitializable::class.java) + } + + assertThat(thrown).hasMessageThat().isEqualTo("class serializer init failed fatally") + } + + @Test + fun `propagates a private object's fatal serializer initializer error unwrapped`() { + val thrown = + assertThrows(OutOfMemoryError::class.java) { + reflectiveSerializerOrNull(PrivateFatal::class.java) + } + + assertThat(thrown).hasMessageThat().isEqualTo("serializer init failed fatally") + } + + // Private object lookups that fail + + @Test + fun `throws the reflection error when a type with an inaccessible INSTANCE field has no serializer method`() { + val thrown = + assertThrows(NoSuchMethodException::class.java) { + reflectiveSerializerOrNull(InaccessibleInstanceWithoutSerializer::class.java) + } + + assertThat(thrown).hasMessageThat().contains("serializer") + } +} 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 new file mode 100644 index 00000000000..c912d881bb2 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/kotlinx/KotlinxTestEntries.kt @@ -0,0 +1,87 @@ +@file:Suppress("MatchingDeclarationName") + +package io.sentry.compose.navigation3.internal.backstack.kotlinx + +import kotlinx.serialization.Contextual +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder + +@Serializable @SerialName("Home") internal data object Home + +@Serializable @SerialName("Detail") internal data class Detail(val id: String) + +@Serializable @SerialName("Search") internal data class Search(val query: String) + +internal class Unregistered(val id: String) + +@Serializable +@SerialName("WithContextual") +internal data class WithContextual(val id: String, @Contextual val other: Unregistered) + +/** A serializer for tests that only read its descriptor, e.g., to name an entry. */ +internal abstract class NamingOnlySerializer : KSerializer { + override fun serialize(encoder: Encoder, value: T) = throw UnsupportedOperationException() + + override fun deserialize(decoder: Decoder): T = throw UnsupportedOperationException() +} + +@Serializable internal data class Box(val value: T) + +/** Wraps [value] in [depth] nested [Box]es, so that [value] sits at [depth]. */ +internal fun boxed( + depth: Int, + value: T, + serializer: KSerializer, +): Pair, Any> { + var boxedSerializer: KSerializer<*> = serializer + var boxedValue: Any? = value + repeat(depth) { + @Suppress("UNCHECKED_CAST") + boxedSerializer = Box.serializer(boxedSerializer as KSerializer) + boxedValue = Box(boxedValue) + } + @Suppress("UNCHECKED_CAST") + return boxedSerializer as KSerializer to boxedValue!! +} + +/** The arguments the encoder produces for [boxed] when within its limits. */ +internal fun boxedArguments(depth: Int, value: Any?): Map { + var arguments: Any? = value + repeat(depth) { arguments = mapOf("value" to arguments) } + @Suppress("UNCHECKED_CAST") + return arguments as Map +} + +internal class Link(val id: String) { + var next: Link? = null +} + +/** + * Encodes a link as the id of the last link in its chain, encoding each next link in place of its + * own, so the recursion never begins a structure. + */ +internal object LinkSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("test.Link", PrimitiveKind.STRING) + + override fun serialize(encoder: Encoder, value: Link) { + val next = value.next + if (next != null) encoder.encodeSerializableValue(this, next) + else encoder.encodeString(value.id) + } + + override fun deserialize(decoder: Decoder): Link = Link(decoder.decodeString()) +} + +/** Chains [length] [Link]s, the last of which has the id `leaf`. */ +internal fun linked(length: Int): Link { + var link = Link("leaf") + repeat(length - 1) { index -> link = Link("link-$index").apply { next = link } } + return link +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequestTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequestTest.kt index 6e2f5419cd2..b23f0d79dfd 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequestTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/lifecycle/NavTransactionRequestTest.kt @@ -31,7 +31,7 @@ class NavTransactionRequestTest { val request = NavTransactionRequest.forDestination( name = "/Checkout", - arguments = mapOf("id" to "1"), + data = emptyMap(), contexts = emptyMap(), viewNames = null, options = options, @@ -45,7 +45,45 @@ class NavTransactionRequestTest { assertThat(fixture.startedOptions.map { it.idleTimeout }).containsExactly(200L, 300L).inOrder() assertThat(fixture.startedOptions.map { it.origin }) .containsExactly("auto.navigation.nav3", "auto.navigation.nav3") - verify(fixture.startedTransactions.first()).setData("arguments", mapOf("id" to "1")) + } + + @Test + fun `forDestination() - sets the given data on each transaction`() { + val fixture = Fixture.create() + val request = + NavTransactionRequest.forDestination( + name = "/unknown", + data = mapOf("arguments" to mapOf("id" to "1"), "unknown_entry_reason" to "unmapped"), + contexts = emptyMap(), + viewNames = null, + options = SentryOptions(), + ) + + request.start(fixture.scopes, scope) + request.start(fixture.scopes, scope) + + fixture.startedTransactions.forEach { transaction -> + verify(transaction).setData("arguments", mapOf("id" to "1")) + verify(transaction).setData("unknown_entry_reason", "unmapped") + } + assertThat(fixture.startedTransactions).hasSize(2) + } + + @Test + fun `forDestination() - sets no data on transactions when given empty data`() { + val fixture = Fixture.create() + val request = + NavTransactionRequest.forDestination( + name = "/Checkout", + data = emptyMap(), + contexts = emptyMap(), + viewNames = null, + options = SentryOptions(), + ) + + val transaction = request.start(fixture.scopes, scope)!! + + verify(transaction, never()).setData(any(), any()) } @Test diff --git a/settings.gradle.kts b/settings.gradle.kts index 18340a6c241..652e86912b9 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -38,6 +38,11 @@ dependencyResolutionManagement { mavenCentral() mavenLocal() } + versionCatalogs { + create("matrixLibs") { + from(files("gradle/dependency-matrix.versions.toml")) + } + } } rootProject.name = "sentry-root"