diff --git a/.claude/skills/create-java-pr/SKILL.md b/.claude/skills/create-java-pr/SKILL.md index 52ab0e9bb60..613f0c6f62f 100644 --- a/.claude/skills/create-java-pr/SKILL.md +++ b/.claude/skills/create-java-pr/SKILL.md @@ -112,6 +112,15 @@ default body shape — it is the single source of truth for the sections and che reproduce it from memory. Fill in each section based on the changes being PR'd, drop the HTML comment hints, and check any checklist items that apply. +Before you create the PR, check which repository `gh` targets: + +```bash +gh repo set-default --view +``` + +If it prints anything other than `getsentry/sentry-java`, or nothing, ask the user which repository +to target. Don't let `gh` pick a community fork. + Write the body to `/tmp/pr-body-.md`, with each `/` in the branch name replaced by `-`, not to pr-writer's `/tmp/pr-body.md`: that file outlives sessions and can still hold another PR's body. Only after the write succeeds, pass that file to `gh pr create` in place of pr-writer's: @@ -169,7 +178,7 @@ Add an entry to `CHANGELOG.md` under the `## Unreleased` section. Create the subsection under `## Unreleased` if it does not already exist. -**When rebasing:** A rebase onto `main` can land your branch after a release was cut, where the `## Unreleased` heading your entry lived under has since been renamed to that version number. If that happens, move your new entry into an `## Unreleased` section at the top of `CHANGELOG.md` (create the section if it no longer exists) so it is not left under an already-released version. +**When rebasing or merging `main`:** Your branch can land after a release was cut, where the `## Unreleased` heading your entry lived under has since been renamed to that version number. A merge does this without a conflict, sometimes with a duplicate subsection heading, so check the `## ` headings, not only the diff. If that happens, move your new entry into an `## Unreleased` section at the top of `CHANGELOG.md` (create the section if it no longer exists) so it is not left under an already-released version. #### Entry format diff --git a/.claude/skills/test/SKILL.md b/.claude/skills/test/SKILL.md index 5e19619b1b2..97622bfcbe3 100644 --- a/.claude/skills/test/SKILL.md +++ b/.claude/skills/test/SKILL.md @@ -57,14 +57,23 @@ If the user picks a specific method, use `--tests="*ClassName.methodName"` as th With a test class filter: ```bash -./gradlew '::' --tests="**" --info +./gradlew '::' --tests="**" ``` -Without a filter: +Without a filter, only when the user asks for the whole module (CI runs full suites): ```bash -./gradlew '::' --info +./gradlew '::' ``` +When you choose the tests yourself, filter to the classes or packages the change touches, plus the +tests of direct callers. Pass `--tests` once per pattern: +```bash +./gradlew '::' --tests="io.sentry.foo.*" --tests="*BarTest*" +``` + +Don't add `--rerun` or `--no-build-cache` by default. An `UP-TO-DATE` test task already passed on the +same inputs. Use them only for a named doubt, such as a suspected flaky test. + ## Step 3b: Run an Integration Test Suite The suite's task is named after its source set directory: `src/integrationTestWebflux/...` runs diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c2eaf195f60..2d57e1b73dc 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -19,6 +19,12 @@ updates: - dependency-name: "io.opentelemetry*" # Servlet 3.1 is the minimum supported API and must remain the production compile target. - dependency-name: "javax.servlet:javax.servlet-api" + # Logback 1.2 is the compatibility floor and must remain the production compile target. + - dependency-name: "ch.qos.logback:logback-classic" + # Spring GraphQL 1.0 is the Spring 5 and Spring Boot 2 compatibility line. + - dependency-name: "org.springframework.graphql:spring-graphql" + # Ktor 3.0 is the compatibility floor; the default suite already tests the latest version. + - dependency-name: "io.ktor:ktor-bom" # DGS 5+ needs Spring Boot 3; the sample is on Spring Boot 2. - dependency-name: "com.netflix.graphql.dgs*" commit-message: diff --git a/.github/workflows/agp-matrix.yml b/.github/workflows/agp-matrix.yml index 0ec83565a0b..46f015433bf 100644 --- a/.github/workflows/agp-matrix.yml +++ b/.github/workflows/agp-matrix.yml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - agp: [ '9.0.0', '9.4.0', '9.5.1' ] + agp: [ '9.0.0', '9.4.0', '9.5.2' ] integrations: [ true, false ] name: AGP Matrix Release - AGP ${{ matrix.agp }} - Integrations ${{ matrix.integrations }} @@ -25,7 +25,7 @@ jobs: VERSION_AGP: ${{ matrix.agp }} APPLY_SENTRY_INTEGRATIONS: ${{ matrix.integrations }} # Upload replay snapshots from one cell only. Forks don't have access to the upload secret. - UPLOAD_REPLAY_SNAPSHOTS: ${{ matrix.agp == '9.5.1' && matrix.integrations && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + UPLOAD_REPLAY_SNAPSHOTS: ${{ matrix.agp == '9.5.2' && matrix.integrations && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} steps: - name: Checkout Repo diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index ff10d0fad90..cf9e1d717b3 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -29,7 +29,7 @@ jobs: uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 - name: Initialize CodeQL - uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # pin@v2 + uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # pin@v2 with: languages: 'java' @@ -38,4 +38,4 @@ jobs: ./gradlew buildForCodeQL --no-build-cache - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # pin@v2 + uses: github/codeql-action/analyze@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # pin@v2 diff --git a/.github/workflows/integration-tests-macrobenchmark.yml b/.github/workflows/integration-tests-macrobenchmark.yml deleted file mode 100644 index 444147d3164..00000000000 --- a/.github/workflows/integration-tests-macrobenchmark.yml +++ /dev/null @@ -1,65 +0,0 @@ -name: 'Integration Tests - Macrobenchmark' -# Runs the sentry-samples-android macrobenchmark cold-start benchmark on a Sauce Labs real -# device and recovers timeToInitialDisplay from the device log. -# -on: - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - macrobenchmark: - name: Macrobenchmark - runs-on: ubuntu-latest - - # we copy the secret to the env variable in order to access it in the workflow - env: - SAUCE_USERNAME: ${{ secrets.SAUCE_USERNAME }} - - steps: - - name: Git checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: 'Set up Java: 17' - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 - with: - distribution: 'temurin' - java-version: '21' - - - name: Setup Gradle - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 - - - name: Assemble target app and Macrobenchmark apk - if: env.SAUCE_USERNAME != null - run: ./gradlew -p sentry-android-integration-tests :sentry-samples-android:assembleRelease :sentry-uitest-android-macrobenchmark:assembleBenchmark - - - name: Run Macrobenchmark in SauceLab - uses: saucelabs/saucectl-run-action@283660aa934c02723c497efa151d582a3acc5801 # pin@v3 - if: env.SAUCE_USERNAME != null - env: - GITHUB_TOKEN: ${{ github.token }} - with: - sauce-username: ${{ secrets.SAUCE_USERNAME }} - sauce-access-key: ${{ secrets.SAUCE_ACCESS_KEY }} - config-file: .sauce/sentry-uitest-android-macrobenchmark.yml - - # Runs even when the suite fails: a failed benchmark still logs whatever it managed to - # measure, and the parser's own error explains what was missing. - - name: Recover benchmark results from the device log - if: ${{ !cancelled() && env.SAUCE_USERNAME != null }} - run: | - # Without pipefail the step passes on `tee`'s exit code, so a failed recovery - # would report success while silently producing no results. - set -o pipefail - python3 scripts/parse-macrobenchmark-log.py ./artifacts \ - --json-out ./artifacts/benchmarkData.json | tee -a "$GITHUB_STEP_SUMMARY" - - - name: Upload Sauce artifacts - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - if: ${{ !cancelled() }} - with: - name: macrobenchmark-results - path: ./artifacts/ - if-no-files-found: warn diff --git a/.github/workflows/pr-classifiers.yml b/.github/workflows/pr-classifiers.yml index 4b03d38e9e1..9f9fbee5e03 100644 --- a/.github/workflows/pr-classifiers.yml +++ b/.github/workflows/pr-classifiers.yml @@ -31,7 +31,7 @@ jobs: # is the classifiers repository, at a pinned commit. - name: Get a token for the classifiers repository id: app - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 with: client-id: ${{ vars.CLASSIFIERS_APP_CLIENT_ID }} private-key: ${{ secrets.CLASSIFIERS_APP_KEY }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6c0db20e7b6..ab2e514eb63 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -23,7 +23,7 @@ jobs: steps: - name: Get auth token id: token - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 with: app-id: ${{ vars.SENTRY_RELEASE_BOT_CLIENT_ID }} private-key: ${{ secrets.SENTRY_RELEASE_BOT_PRIVATE_KEY }} @@ -33,7 +33,7 @@ jobs: # Needs to be set, otherwise git describe --tags will fail with: No names found, cannot describe anything fetch-depth: 0 - name: Prepare release - uses: getsentry/craft@0da9309228741a4c300d3c87ed7dcafa8f703525 # 3.12.0 + uses: getsentry/craft@b2a6fa4904f37b46f34b82330e0f3bf02a40f681 # 3.13.0 env: GITHUB_TOKEN: ${{ steps.token.outputs.token }} with: diff --git a/.github/workflows/compose-ui-matrix.yml b/.github/workflows/replay-dependency-matrix.yml similarity index 63% rename from .github/workflows/compose-ui-matrix.yml rename to .github/workflows/replay-dependency-matrix.yml index 6f1ac6f216d..51f1e1e04a1 100644 --- a/.github/workflows/compose-ui-matrix.yml +++ b/.github/workflows/replay-dependency-matrix.yml @@ -1,4 +1,4 @@ -name: Compose UI Matrix +name: Session Replay Dependency Matrix on: push: @@ -11,17 +11,27 @@ concurrency: cancel-in-progress: true jobs: - compose-ui-matrix: + replay-dependency-matrix: timeout-minutes: 30 runs-on: ubuntu-latest - name: Compose UI Matrix + name: ${{ matrix.name }} Matrix + strategy: + fail-fast: false + matrix: + include: + # Runs every version in gradle/compose-ui-versions.json + - name: Compose UI + task: composeUiTest + # Runs every version in gradle/coil3-versions.json + - name: Coil 3 + task: coil3Test steps: - name: Checkout Repo uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Java Version - uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: 'temurin' java-version: '21' @@ -29,15 +39,15 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 - # Runs every version in gradle/compose-ui-versions.json; --continue reports each failing one. + # --continue reports each failing version. - name: Run Session Replay unit tests - run: ./gradlew :sentry-android-replay:composeUiTest --continue + run: ./gradlew :sentry-android-replay:${{ matrix.task }} --continue - name: Upload test results if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - name: test-results-compose-ui + name: test-results-${{ matrix.task }} path: | sentry-android-replay/build/reports/* sentry-android-replay/build/test-results/**/*.xml @@ -46,7 +56,7 @@ jobs: uses: phoenix-actions/test-reporting@7317eea6e13c47348dd0bb318669485157c518d6 # pin@v16 if: always() with: - name: JUnit Compose UI + name: JUnit ${{ matrix.name }} path: | sentry-android-replay/build/test-results/**/*.xml reporter: java-junit diff --git a/.sauce/sentry-uitest-android-macrobenchmark.yml b/.sauce/sentry-uitest-android-macrobenchmark.yml deleted file mode 100644 index be7c133d26c..00000000000 --- a/.sauce/sentry-uitest-android-macrobenchmark.yml +++ /dev/null @@ -1,35 +0,0 @@ -apiVersion: v1alpha -kind: espresso -sauce: - region: us-west-1 - concurrency: 1 - metadata: - build: sentry-uitest-android-macrobenchmark-$GITHUB_REF-$GITHUB_SHA - tags: - - benchmarks - - android - - macrobenchmark - -defaults: - timeout: 40m - -espresso: - app: ./sentry-android-integration-tests/sentry-samples-android/build/outputs/apk/release/sentry-samples-android-release.apk - testApp: ./sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/build/outputs/apk/benchmark/sentry-uitest-android-macrobenchmark-benchmark.apk - -suites: - - - name: "Macrobenchmark startup (api 35)" - # No test orchestrator and no clearPackageData: Macrobenchmark manages its own process - # restarts and AOT compilation, and StartupMode.COLD intentionally keeps app data and - # permissions (it force-stops rather than `pm clear`). - devices: - - id: Google_Pixel_9_Pro_XL_15_real_sjc1 # Google Pixel 9 Pro XL - api 35 (15) - high end - -artifacts: - download: - when: always - match: - - junit.xml - - "*.log" - directory: ./artifacts/ diff --git a/AGENTS.md b/AGENTS.md index b9d0788a2d4..2e2dd26784a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,10 @@ Rules can be combined — a tracing scope issue may need both `scopes` and `open There is no rule for Android profiling yet; read the `sentry-android-core` profiling code directly and fetch related rules such as `options`, `offline`, or `api` as needed. +## Code Review + +When reviewing a pull request, follow [`REVIEWS.md`](REVIEWS.md). + ## Project Overview This is the Sentry Java/Android SDK - a comprehensive error monitoring and performance tracking SDK for Java and Android applications. The repository contains multiple modules for different integrations and platforms. @@ -80,8 +84,9 @@ resolves the per-module test task, including integration test suites, for you. 3. **Use todo tracking**: Work through todo items, marking them as complete as you go 4. **High-level communication**: Give high-level explanations of changes made, not step-by-step descriptions 5. **Simplicity first**: Make every task and code change as simple as possible. Avoid massive or complex changes. Impact as little code as possible. -6. **Format and regenerate**: Once done, format code and regenerate .api files: `make format api` -7. **Propose commit**: As final step, git stage relevant files and propose (but not execute) a single git commit command. This applies to implementation work; when the task is to open a PR, the `create-java-pr` skill takes over from here and does commit, push, and open it. +6. **Don't code for impossible states**: Before you add state tracking or heuristics around a framework object, find out its real lifecycle. +7. **Format and regenerate**: Once done, format code and regenerate .api files: `make format api` +8. **Propose commit**: As final step, git stage relevant files and propose (but not execute) a single git commit command. This applies to implementation work; when the task is to open a PR, the `create-java-pr` skill takes over from here and does commit, push, and open it. ## Repository Skills @@ -133,6 +138,21 @@ The repository is organized into multiple modules: - **Formatting**: Enforced via Spotless - **API Compatibility**: Binary compatibility is enforced. `.api` files are generated, never hand-edited +### Comments + +The default is no comment. Add one only when it gives a reason that the code, the names, and the +class Javadoc don't, in one short sentence: a rationale, a gotcha, the meaning of a magic number, +why an empty catch is safe, or a comment this file requires (for example on a broad catch). + +- Don't describe what the next line does, in production code or in tests. +- Don't repeat what a method Javadoc already describes. +- Existing narrating comments are not a pattern to copy. + +**Javadoc of an interface, callback, or model class describes only the type itself**, in general +terms. Requirements on the implementer are fine ("Must be fast, no I/O."). Don't name who calls it, +when, or on which thread: a type can't promise how others use it. A thread contract belongs on the +methods of the component that owns the thread. + ### Exception Handling The following section applies only in cases where the spec (sentry-docs) do not define an exception @@ -211,7 +231,10 @@ Two more rules that catch most of the rest: - **Read mutable shared state once per operation.** Re-reading the same field for several decisions in one pass lets it change mid-pass, so the results disagree with each other. -Prefer `AutoClosableReentrantLock` over `synchronized`, matching the rest of the codebase. +**Which lock to use depends on the module.** In JVM and shared modules, including `sentry` core, +use `AutoClosableReentrantLock`: `synchronized` pins virtual threads on JDK 21–23. In Android-only +modules (`sentry-android-*`), use `synchronized`, since Android has no virtual threads. Don't rewrite +existing locks only to switch between the two. ### Measuring Time @@ -281,7 +304,13 @@ gh pr view --json url -q '.url' User-facing changes get an entry under the `## Unreleased` section of `CHANGELOG.md`. The `create-java-pr` skill is the source of truth for the full changelog and PR workflow, including -subsection selection and the rebase caveat when a release renames `## Unreleased`. +subsection selection and the rebase and merge caveat when a release renames `## Unreleased`. + +### After Merging `main` or Resolving Conflicts + +Before you commit the merge, format and regenerate (workflow rule 7) and check the changelog entry +(the `create-java-pr` rebase and merge caveat). Then compile and run the tests of the modules you +changed: `main` adds build checks over time, so code that passed before the merge can fail after it. ## Useful Resources diff --git a/CHANGELOG.md b/CHANGELOG.md index 512b8ff293d..6753c06d4bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -131,18 +131,40 @@ ### Fixes -- 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)) -- Profiling: No longer crash on API 35+ devices whose framework can't load `ProfilingManager`. Perfetto profiling is turned off on those devices instead ([#6742](https://github.com/getsentry/sentry-java/pull/6742)) - Set Apollo 3, 4, and 5 HTTP spans to `CANCELLED` instead of `INTERNAL_ERROR` when the request is cancelled ([#6284](https://github.com/getsentry/sentry-java/pull/6284)) - Preserve independent Netty read and write timeout events when exception singletons are reused. These exceptions now bypass event deduplication by default, so applications with multiple capture integrations may report the same timeout more than once. Use `SentryOptions.setIgnoredErrorsForDeduplication(...)` or `ignored-errors-for-deduplication` to customize or clear the default exclusions. ([#6465](https://github.com/getsentry/sentry-java/pull/6465)) - Prevent changes to reused tracing options from affecting spans and transactions after creation ([#6417](https://github.com/getsentry/sentry-java/pull/6417)) - Avoid duplicate serialization debug logs when calculating serialized object sizes ([#6255](https://github.com/getsentry/sentry-java/pull/6255)) - `Contexts.setProfile(null)` now removes the profile context instead of throwing ([#6684](https://github.com/getsentry/sentry-java/pull/6684)) +### Dependencies + +- Bump OpenTelemetry ([#6691](https://github.com/getsentry/sentry-java/pull/6691)) + - `opentelemetry` to `1.68.0` (was `1.67.0`) + - `opentelemetry-alpha` to `1.68.0-alpha` (was `1.67.0-alpha`) + - `opentelemetry-instrumentation` to `2.34.0` (was `2.33.1`) + - `opentelemetry-instrumentation-alpha` to `2.34.0-alpha` (was `2.33.1-alpha`) + - `opentelemetry-semconv` to `1.45.0` (was `1.44.0`) + - `opentelemetry-semconv-alpha` to `1.45.0-alpha` (was `1.44.0-alpha`) + ### Internal - Measure the 30 second performance-collection budget on a monotonic ticker, so that a device time change no longer ends collection early or extends it past the budget ([#6101](https://github.com/getsentry/sentry-java/pull/6101)) +## 8.66.0 + +### 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)) +- Profiling: No longer crash on API 35+ devices whose framework can't load `ProfilingManager`. Perfetto profiling is turned off on those devices instead ([#6742](https://github.com/getsentry/sentry-java/pull/6742)) +- Android: Out-of-process crash reporting now supports Android 5.0 (API level 21) and later, previously required Android 11 (API level 30) ([#6614](https://github.com/getsentry/sentry-java/pull/6614)) +- Android profiling: Uploading a Perfetto profile chunk now keeps the trace in memory once instead of up to three times, lowering peak memory use for traces up to 50 MB ([#6743](https://github.com/getsentry/sentry-java/pull/6743)) +- Stop a transaction's CPU and memory collection 30 seconds after it starts even when the device's wall clock changes in between ([#6739](https://github.com/getsentry/sentry-java/pull/6739)) + +### Dependencies + +- 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 ### Fixes diff --git a/.cursor/BUGBOT.md b/REVIEWS.md similarity index 93% rename from .cursor/BUGBOT.md rename to REVIEWS.md index 9e063579e90..17cb3aefff6 100644 --- a/.cursor/BUGBOT.md +++ b/REVIEWS.md @@ -1,9 +1,9 @@ -# PR Review Guidelines for Cursor Bugbot +# PR Review Guidelines -You are reviewing a pull request for the Sentry Java/Android SDK. +Applies to any agent reviewing a pull request for the Sentry Java/Android SDK. -Read [`AGENTS.md`](../AGENTS.md) for build commands and contributing rules, and the matching -rule file in [`.cursor/rules/`](rules) for the area the diff touches (`api`, `options`, `scopes`, +Read [`AGENTS.md`](AGENTS.md) for build commands and contributing rules, and the matching +rule file in [`.cursor/rules/`](.cursor/rules) for the area the diff touches (`api`, `options`, `scopes`, `offline`, `opentelemetry`, ...). ## Critical @@ -105,7 +105,9 @@ rule file in [`.cursor/rules/`](rules) for the area the diff touches (`api`, `op plain field read is a data race, not merely a stale value. - Read mutable shared state once per operation. Re-reading the same field for several decisions in one pass lets it change mid-pass, so the results disagree with each other. -- Prefer the `synchronized` keyword. Existing code that uses `AutoClosableReentrantLock` is legacy. +- In JVM and shared modules, including `sentry` core, use `AutoClosableReentrantLock`, not + `synchronized`, which pins virtual threads on JDK 21–23. In Android-only modules + (`sentry-android-*`), use `synchronized`. Don't flag existing locks that predate this rule. - New classes have a clear and defined threading and concurrency model as part of the javadoc if needed. diff --git a/gradle.properties b/gradle.properties index 0bf3bbd07da..d828ff257a3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -19,7 +19,7 @@ android.newDsl=false android.disableAgpUpgradePrompt=true # Release information -versionName=8.65.1 +versionName=8.66.0 # Override the SDK name on native crashes on Android sentryAndroidSdkName=sentry.native.android diff --git a/gradle/coil3-versions.json b/gradle/coil3-versions.json new file mode 100644 index 00000000000..8d19840db5e --- /dev/null +++ b/gradle/coil3-versions.json @@ -0,0 +1,5 @@ +[ + "3.0.4", + "3.1.0", + "3.6.3" +] diff --git a/gradle/compose-ui-versions.json b/gradle/compose-ui-versions.json index bf26c2bfb6a..7ab078e925f 100644 --- a/gradle/compose-ui-versions.json +++ b/gradle/compose-ui-versions.json @@ -1,5 +1,5 @@ [ - { "version": "1.8.3", "pin": { "androidx.compose.material3": "1.3.2" } }, + { "version": "1.8.3", "pin": { "androidx.compose.material3": "1.3.2", "io.coil-kt.coil3": "3.3.0" } }, "1.13.0", "1.14.0-alpha01" ] diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ca99b0167a6..955b740dbac 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -16,7 +16,7 @@ dokka = "2.3.0" espresso = "3.7.0" feign = "13.18" gummyBears = "0.16.0" -jackson = "2.18.3" +jackson = "2.22.4" jetbrainsCompose = "1.6.11" kotlin = "2.4.21" ksp = "2.3.14" @@ -28,19 +28,19 @@ nopen = "1.0.1" # see https://developer.android.com/jetpack/androidx/releases/compose-kotlin okhttp = "5.5.1" openfeature = "1.18.2" -otel = "1.67.0" -otelAlpha = "1.67.0-alpha" -otelInstrumentation = "2.33.1" -otelInstrumentationAlpha = "2.33.1-alpha" +otel = "1.68.0" +otelAlpha = "1.68.0-alpha" +otelInstrumentation = "2.34.0" +otelInstrumentationAlpha = "2.34.0-alpha" # check https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/main/dependencyManagement/build.gradle.kts#L49 for release version above to find a compatible version -otelSemanticConventions = "1.44.0" -otelSemanticConventionsAlpha = "1.44.0-alpha" +otelSemanticConventions = "1.45.0" +otelSemanticConventionsAlpha = "1.45.0-alpha" retrofit = "3.0.0" room2 = "2.8.5" room3 = "3.0.3" -sagp = "6.13.0" +sagp = "6.27.0" # The AGP matrix job overrides this with the VERSION_AGP env var, through each build's settings. -agp = "9.5.1" +agp = "9.5.2" # The R8 bundled with AGP 9.0 and 9.2 crashes on androidx.core at minSdk 24, so builds that override # AGP (the AGP matrix) put the R8 that ships with the default AGP on their buildscript classpath. r8 = "9.5.29" @@ -50,7 +50,7 @@ slf4j = "1.7.30" spotless = "8.11.0" springboot2 = "2.7.18" springboot3 = "3.5.0" -springboot4 = "4.1.0" +springboot4 = "4.2.0" springKafka2 = "2.8.11" springKafka3 = "3.3.5" sqldelight = "2.4.1" @@ -84,7 +84,7 @@ springboot3 = { id = "org.springframework.boot", version.ref = "springboot3" } springboot4 = { id = "org.springframework.boot", version.ref = "springboot4" } spring-dependency-management = { id = "io.spring.dependency-management", version = "1.1.7" } sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" } -gretty = { id = "org.gretty", version = "4.0.0" } +gretty = { id = "org.gretty", version = "5.1.0" } animalsniffer = { id = "ru.vyarus.animalsniffer", version.ref = "animalsniffer" } sentry = { id = "io.sentry.android.gradle", version.ref = "sagp"} shadow = { id = "com.gradleup.shadow", version = "9.6.1" } @@ -142,9 +142,10 @@ async-profiler-jfr-converter = { module = "tools.profiler:jfr-converter", versio caffeine = { module = "com.github.ben-manes.caffeine:caffeine" } caffeine-jcache = { module = "com.github.ben-manes.caffeine:jcache", version = "3.3.1" } coil-compose = { module = "io.coil-kt:coil-compose", version = "2.7.0" } +coil3-compose = { module = "io.coil-kt.coil3:coil-compose", version = "3.4.0" } commons-compress = {module = "org.apache.commons:commons-compress", version = "1.28.0"} android-r8 = { module = "com.android.tools:r8", version.ref = "r8" } -context-propagation = { module = "io.micrometer:context-propagation", version = "1.1.0" } +context-propagation = { module = "io.micrometer:context-propagation", version = "1.2.1" } errorprone-core = { module = "com.google.errorprone:error_prone_core", version = "2.52.0" } feign-core = { module = "io.github.openfeign:feign-core", version.ref = "feign" } feign-gson = { module = "io.github.openfeign:feign-gson", version.ref = "feign" } @@ -201,7 +202,7 @@ reactor-core = { module = "io.projectreactor:reactor-core", version = "3.5.3" } retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" } retrofit-gson = { module = "com.squareup.retrofit2:converter-gson", version.ref = "retrofit" } sentry-native-ndk = { module = "io.sentry:sentry-native-ndk", version = "0.17.6" } -sentry-native-ndk-outproc = { module = "io.sentry:sentry-native-ndk-outproc", version = "1.0.0-beta.1" } +sentry-native-ndk-outproc = { module = "io.sentry:sentry-native-ndk-outproc", version = "1.0.0-beta.2" } servlet-api = { module = "javax.servlet:javax.servlet-api", version = "3.1.0" } servlet4-api = { module = "javax.servlet:javax.servlet-api", version = "4.0.1" } servlet-jakarta-api = { module = "jakarta.servlet:jakarta.servlet-api", version = "6.1.0" } diff --git a/gradle/spring-boot-versions.json b/gradle/spring-boot-versions.json index 8cf4c6848ba..837abb74a98 100644 --- a/gradle/spring-boot-versions.json +++ b/gradle/spring-boot-versions.json @@ -1,5 +1,5 @@ { "boot2": ["2.7.0", "2.7.18"], "boot3": ["3.4.13", "3.5.13"], - "boot4": ["4.0.0", "4.0.5", "4.1.0"] + "boot4": ["4.0.0", "4.0.5", "4.1.0", "4.2.0"] } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 04d7959523b..d0d1a39c1f5 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.2-bin.zip networkTimeout=10000 retries=0 retryBackOffMs=500 diff --git a/scripts/parse-macrobenchmark-log.py b/scripts/parse-macrobenchmark-log.py deleted file mode 100755 index 280970dbea8..00000000000 --- a/scripts/parse-macrobenchmark-log.py +++ /dev/null @@ -1,142 +0,0 @@ -#!/usr/bin/env python3 -"""Recover Macrobenchmark results from a Sauce Labs device log. - -Sauce Labs cannot pull arbitrary files off a real device, so -SentryStartupBenchmark echoes its `-benchmarkData.json` into logcat as -numbered chunks. This reassembles those chunks and prints a Markdown summary. - -Usage: - parse-macrobenchmark-log.py [--json-out benchmarkData.json] -""" - -import argparse -import json -import re -import sys -from pathlib import Path - -# Must match SentryStartupBenchmark.LOG_TAG and its "[index/total]" chunk prefix. -CHUNK_RE = re.compile(r"SentryBenchmarkData\s*:\s*\[(\d+)/(\d+)\](.*)$") - - -def log_messages(log_file): - """Yields the message text of every log entry. - - Sauce hands back device.log as JSON lines -- {"tag", "message", "level", ...} -- which - means the payload arrives with its quotes escaped, so it has to be decoded rather than - regexed out of the raw line. Plain-text lines are passed through unchanged so the same - parser works on `adb logcat` output from a local run. - """ - # Sauce device logs occasionally carry undecodable bytes; don't die on them. - for line in log_file.read_text(errors="replace").splitlines(): - line = line.strip() - if line.startswith("{"): - try: - yield json.loads(line).get("message", "") - continue - except json.JSONDecodeError: - pass - yield line - - -def collect_chunks(log_file): - """Returns one log's chunk texts keyed by index, plus the expected total.""" - chunks, total = {}, None - for message in log_messages(log_file): - match = CHUNK_RE.search(message) - if match: - index, total = int(match.group(1)), int(match.group(2)) - chunks[index] = match.group(3) - return chunks, total - - -def reassemble(chunks, total): - missing = [i for i in range(1, total + 1) if i not in chunks] - if missing: - sys.exit(f"Incomplete benchmark data: missing chunk(s) {missing} of {total}") - return "".join(chunks[i] for i in range(1, total + 1)) - - -def format_summary(data): - context = data["context"] - build = context["build"] - lines = [ - "## Macrobenchmark results", - "", - f"**Device:** {build['brand']} {build['model']} " - f"(api {build['version']['sdk']}, {context['cpuCoreCount']} cores) · " - f"**compilation:** {context['compilationMode']} · " - f"**CPU clocks locked:** {context['cpuLocked']}", - "", - ] - - if not context["cpuLocked"]: - lines += [ - "> CPU clocks are unlocked on this device, so run-to-run spread is wide. " - "Treat these numbers as a trend, not a regression gate.", - "", - ] - - table = [ - "| Benchmark | Metric | min | median | max | CoV | iterations |", - "|---|---|--:|--:|--:|--:|--:|", - ] - details = [] - for benchmark in data["benchmarks"]: - name = f"{benchmark['className'].rsplit('.', 1)[-1]}.{benchmark['name']}" - for metric, result in sorted(benchmark["metrics"].items()): - table.append( - f"| `{name}` | {metric} " - f"| {result['minimum']:.1f} | {result['median']:.1f} | {result['maximum']:.1f} " - f"| {result['coefficientOfVariation'] * 100:.1f}% | {len(result['runs'])} |" - ) - runs = ", ".join(f"{run:.1f}" for run in result["runs"]) - details += [ - "", - f"
{metric} per iteration", - "", - runs, - "", - "
", - ] - - return "\n".join(lines + table + details) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("artifacts_dir", type=Path, help="directory of downloaded Sauce artifacts") - parser.add_argument("--json-out", type=Path, help="where to write the recovered benchmarkData.json") - args = parser.parse_args() - - log_files = sorted(args.artifacts_dir.rglob("*.log")) - if not log_files: - sys.exit(f"No *.log files under {args.artifacts_dir}") - - # Keyed by file so chunks from two devices can never be merged into one bogus document. - per_log = {log: collect_chunks(log) for log in log_files} - with_chunks = {log: result for log, (result, total) in per_log.items() if total} - if not with_chunks: - sys.exit( - "No SentryBenchmarkData chunks in the device log. The benchmark most likely " - "failed before reporting — check junit.xml and the log for Macrobenchmark errors." - ) - if len(with_chunks) > 1: - sys.exit( - "Chunks from more than one run: " - + ", ".join(str(log) for log in with_chunks) - + ". This parser reports a single device." - ) - log_file = next(iter(with_chunks)) - chunks, total = per_log[log_file] - - data = json.loads(reassemble(chunks, total)) - - if args.json_out: - args.json_out.write_text(json.dumps(data, indent=2)) - - print(format_summary(data)) - - -if __name__ == "__main__": - main() diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java index bffbf75b980..957337df748 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroid.java @@ -20,7 +20,10 @@ import io.sentry.android.fragment.FragmentLifecycleIntegration; import io.sentry.android.timber.SentryTimberIntegration; import io.sentry.util.AutoClosableReentrantLock; +import io.sentry.util.FileUtils; import io.sentry.util.LoadClass; +import java.io.File; +import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @@ -279,13 +282,30 @@ private static void deduplicateIntegrations( } } - // the crash service only runs on API 30+ @SuppressLint("NewApi") private static boolean isNdkCrashServiceProcess() { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + if (!new LoadClass() + .isClassAvailable(NdkIntegration.SENTRY_NDK_OUTPROC_CLASS_NAME, (ILogger) null)) { return false; } - final @Nullable String processName = Application.getProcessName(); + final @Nullable String processName = + Build.VERSION.SDK_INT >= Build.VERSION_CODES.P + ? Application.getProcessName() + : readProcessName(); return processName != null && processName.endsWith(NDK_CRASH_SERVICE_PROCESS_SUFFIX); } + + // argv[0] of an app process is its process name + private static @Nullable String readProcessName() { + try { + final @Nullable String cmdline = FileUtils.readText(new File("/proc/self/cmdline")); + if (cmdline == null) { + return null; + } + final int end = cmdline.indexOf('\0'); + return end >= 0 ? cmdline.substring(0, end) : cmdline; + } catch (IOException e) { + return null; + } + } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt index dc2472e6a6d..87e9c352b60 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidTest.kt @@ -50,6 +50,7 @@ import io.sentry.protocol.Contexts import io.sentry.spotlight.SpotlightIntegration import io.sentry.test.applyTestOptions import io.sentry.transport.NoOpEnvelopeCache +import io.sentry.util.LoadClass import io.sentry.util.StringUtils import java.io.ByteArrayOutputStream import java.io.File @@ -73,6 +74,7 @@ import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -627,12 +629,35 @@ class SentryAndroidTest { ShadowApplication.setProcessName("${context.packageName}.sentry_ndk_crash") var configured = false - fixture.initSut { configured = true } + Mockito.mockConstruction(LoadClass::class.java) { loadClass, _ -> + whenever( + loadClass.isClassAvailable( + eq(NdkIntegration.SENTRY_NDK_OUTPROC_CLASS_NAME), + anyOrNull(), + ), + ) + .thenReturn(true) + } + .use { fixture.initSut { configured = true } } assertFalse(configured) assertFalse(Sentry.isEnabled()) } + @Test + @Config(sdk = [30]) + fun `init runs in a process named like the NDK crash service without outproc`() { + ShadowApplication.setProcessName("${context.packageName}.sentry_ndk_crash") + var configured = false + + fixture.initSut { + it.dsn = "https://key@sentry.io/123" + configured = true + } + + assertTrue(configured) + } + private fun prefillScopeCache(options: SentryOptions, cacheDir: String) { val scopeDir = File(cacheDir, SCOPE_CACHE).also { it.mkdirs() } val queueFile = QueueFile.Builder(File(scopeDir, BREADCRUMBS_FILENAME)).build() diff --git a/sentry-android-integration-tests/README.md b/sentry-android-integration-tests/README.md index ccd987af8cd..1a7d7951302 100644 --- a/sentry-android-integration-tests/README.md +++ b/sentry-android-integration-tests/README.md @@ -7,7 +7,7 @@ This directory is a separate Gradle build that includes the SDK build, so run it symlinks to the SDK build's, so both builds use the same Gradle, JDK and settings. * [Sample app](./sentry-samples-android) -* [Macrobenchmark](./sentry-uitest-android-macrobenchmark) - cold start of the sample app, run locally or within SauceLabs (see /.sauce/*.yml) +* [Macrobenchmark](./sentry-uitest-android-macrobenchmark) - cold start of the sample app, run locally on a connected device * [Espresso-based UI tests](./sentry-uitest-android) - run on an emulator in the AGP matrix workflow * [Maestro-based critical UI tests](./sentry-uitest-android-critical) - run by the UI Tests Critical workflow * [App size test](./test-app-size) - built by the SDK Size Analysis workflow diff --git a/sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/README.md b/sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/README.md index 84886e1a3e0..3994a287e04 100644 --- a/sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/README.md +++ b/sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/README.md @@ -34,35 +34,7 @@ Connect a device, then: Results print to the console and are written to `build/outputs/connected_android_test_additional_output/.../*-benchmarkData.json`. -## Running on Sauce Labs - -The `Integration Tests - Macrobenchmark` workflow (manual trigger) runs the same benchmark on a -Sauce Labs real device. It reports numbers only — it is not a PR gate, because cloud devices run -with unlocked CPU clocks and the run-to-run spread swamps most SDK-init changes. - -Getting the numbers *back off* the device is the awkward part, so if you are changing this, know -what has already been ruled out: - -- **`artifacts.download.match` in `.sauce/*.yml` cannot reach the device.** It filters a - hardcoded list of assets Sauce hosts for the job (`device.log`, `junit.xml`, `video.mp4`, - `network.har`, `crash.json`, `screenshots.zip`); nothing enumerates device storage. A - `*-benchmarkData.json` pattern there matches nothing. -- **Macrobenchmark's own reporting channels don't survive.** The readable summary goes into the - instrumentation status bundle, which only Studio and AGP consume, and `benchmarkData.json` is - written to the app's external media dir, which Sauce never pulls. -- **The Real Device Access API can pull device files, but not on our account.** It offers - `pullFile` and `executeShellCommand`, and `GET /rdc/v2/devices/status` even lists the whole - public fleet — but `POST /sessions` answers `deviceClasses=[PRIVATE_DEVICE]` and there is no - parameter to request a public device. It would need leased private devices. That route would - also return the per-iteration perfetto traces, so it is worth revisiting if we ever get them. - -So `SentryStartupBenchmark` echoes its own `benchmarkData.json` into logcat in chunks, which -reaches CI inside `device.log`, and `scripts/parse-macrobenchmark-log.py` reassembles it and -writes a `timeToInitialDisplay` table to the job summary. Note this recovers the metrics only — -the perfetto traces are megabytes each and cannot go through logcat, so sub-millisecond work -still needs a local device. - -### Device hygiene (do this for trustworthy numbers) +## Device hygiene (do this for trustworthy numbers) - **Wake and unlock the device first** — the launch check fails with "Unable to confirm activity launch completion" on a dozing/locked screen diff --git a/sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/src/main/java/io/sentry/uitest/android/macrobenchmark/SentryStartupBenchmark.kt b/sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/src/main/java/io/sentry/uitest/android/macrobenchmark/SentryStartupBenchmark.kt index 824a2a0628f..5c1b0fcd3a1 100644 --- a/sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/src/main/java/io/sentry/uitest/android/macrobenchmark/SentryStartupBenchmark.kt +++ b/sentry-android-integration-tests/sentry-uitest-android-macrobenchmark/src/main/java/io/sentry/uitest/android/macrobenchmark/SentryStartupBenchmark.kt @@ -1,6 +1,5 @@ package io.sentry.uitest.android.macrobenchmark -import android.util.Log import androidx.benchmark.macro.CompilationMode import androidx.benchmark.macro.ExperimentalMetricApi import androidx.benchmark.macro.StartupMode @@ -8,9 +7,6 @@ import androidx.benchmark.macro.StartupTimingMetric import androidx.benchmark.macro.TraceSectionMetric import androidx.benchmark.macro.junit4.MacrobenchmarkRule import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.platform.app.InstrumentationRegistry -import java.io.File -import org.junit.AfterClass import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -47,59 +43,10 @@ class SentryStartupBenchmark { startActivityAndWait() } - // Not private: @AfterClass needs a public static method. companion object { private const val TARGET_PACKAGE = "io.sentry.samples.android" // Matches the android.os.Trace section name in SentryAndroid.init. private const val INIT_TRACE_SECTION = "SentryAndroid.init" - - private const val BENCHMARK_DATA_SUFFIX = "-benchmarkData.json" - - /** Kept in sync with `scripts/parse-macrobenchmark-log.py`. */ - private const val LOG_TAG = "SentryBenchmarkData" - - /** Well under logcat's ~4 KB per-message cap, so a chunk is never silently truncated. */ - private const val CHUNK_LENGTH = 2000 - - /** - * Echoes the benchmark results into logcat so CI can recover them. - * - * Macrobenchmark reports its numbers two ways, and on Sauce Labs neither one arrives: the - * human-readable summary goes into the instrumentation status bundle (which only Studio and AGP - * read), and `-benchmarkData.json` is written to the app's external media dir, which Sauce - * cannot pull — it only returns assets it produces itself, and logcat is one of them. - * - * Safe to run at this point because `ResultWriter` writes the file synchronously as each result - * is appended; only its *reporting* is deferred to the end of the run. Locally this is just - * extra logcat noise — Gradle still copies the real file into the build directory. - */ - @JvmStatic - @AfterClass - fun logBenchmarkDataToLogcat() { - val benchmarkData = findBenchmarkData() - if (benchmarkData == null) { - Log.w(LOG_TAG, "No *$BENCHMARK_DATA_SUFFIX found, cannot report results to CI") - return - } - - // Dropping the indentation makes the JSON compact enough to survive as a few logcat - // messages. Only structural whitespace is affected: JSON forbids raw newlines inside - // strings, so no value can span lines or start with the indentation being trimmed. - val compactJson = benchmarkData.readText().lineSequence().joinToString("") { it.trimStart() } - val chunks = compactJson.chunked(CHUNK_LENGTH) - chunks.forEachIndexed { index, chunk -> - Log.i(LOG_TAG, "[${index + 1}/${chunks.size}]$chunk") - } - } - - private fun findBenchmarkData(): File? { - val context = InstrumentationRegistry.getInstrumentation().targetContext - // This is where Macrobenchmark writes to for some reason. - @Suppress("DEPRECATION") val mediaDirs = context.externalMediaDirs.toList() - return (mediaDirs + context.externalCacheDir).filterNotNull().firstNotNullOfOrNull { dir -> - dir.listFiles()?.firstOrNull { it.name.endsWith(BENCHMARK_DATA_SUFFIX) } - } - } } } diff --git a/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts b/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts index f954486de93..a4a9784deec 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts +++ b/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts @@ -105,6 +105,9 @@ dependencies { implementation(libs.androidx.activity.compose) implementation(libs.androidx.compose.foundation) implementation(libs.androidx.compose.material3) + implementation(libs.coil3.compose) + // Compose UI 1.10+ lets R8 rename modifier elements, so the replay masking keep rules get tested + implementation(libs.androidx.compose.ui.replay) implementation(libs.androidx.constraintlayout) implementation(libs.androidx.core) implementation(libs.androidx.recyclerview) diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/ReplayTest.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/ReplayTest.kt index f7203549c4c..fb69f742593 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/ReplayTest.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/ReplayTest.kt @@ -1,10 +1,18 @@ package io.sentry.uitest.android +import android.graphics.Bitmap import androidx.lifecycle.Lifecycle import androidx.test.core.app.launchActivity import io.sentry.SentryOptions +import io.sentry.SentryReplayOptions +import io.sentry.TypeCheckHint +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue import leakcanary.LeakAssertions import leakcanary.LeakCanary import org.awaitility.kotlin.await @@ -81,4 +89,52 @@ class ReplayTest : BaseUiTest() { LeakAssertions.assertNoLeaks() } + + @Test + fun composeCoilImageIsMasked() { + val frame = AtomicReference() + val frameReceived = CountDownLatch(1) + + val activityScenario = launchActivity() + activityScenario.moveToState(Lifecycle.State.RESUMED) + // an image that hasn't loaded yet is empty, and would look masked + assertTrue(ComposeActivity.imageLoaded.await(10, TimeUnit.SECONDS), "Coil image didn't load") + + initSentry { + it.sessionReplay.sessionSampleRate = 1.0 + it.sessionReplay.frameObserver = SentryReplayOptions.ReplayFrameObserver { hint, _, _ -> + val bitmap = hint.getAs(TypeCheckHint.REPLAY_FRAME_BITMAP, Bitmap::class.java) + if (bitmap != null && frame.compareAndSet(null, bitmap)) { + frameReceived.countDown() + } else { + bitmap?.recycle() + } + } + } + assertTrue(frameReceived.await(10, TimeUnit.SECONDS), "Expected a replay frame") + + var rootWidth = 0 + var rootHeight = 0 + activityScenario.onActivity { + rootWidth = it.window.decorView.width + rootHeight = it.window.decorView.height + } + val bitmap = frame.get() + val scaleX = bitmap.width / rootWidth.toFloat() + val scaleY = bitmap.height / rootHeight.toFloat() + val bounds = ComposeActivity.imageBounds + // the inner half of the image, away from the edges of the scaled mask + val colors = mutableSetOf() + for (i in 1..9) { + for (j in 1..9) { + val x = (bounds.left + bounds.width * (0.25f + i * 0.05f)) * scaleX + val y = (bounds.top + bounds.height * (0.25f + j * 0.05f)) * scaleY + colors += bitmap.getPixel(x.toInt(), y.toInt()) + } + } + bitmap.recycle() + activityScenario.moveToState(Lifecycle.State.DESTROYED) + + assertEquals(1, colors.size, "Coil image isn't masked in the replay frame") + } } diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/ComposeActivity.kt b/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/ComposeActivity.kt index fd0ff09f4bc..9f105abe4fd 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/ComposeActivity.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/ComposeActivity.kt @@ -13,18 +13,38 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp +import androidx.core.graphics.createBitmap +import androidx.core.graphics.set +import coil3.compose.AsyncImage +import java.util.concurrent.CountDownLatch class ComposeActivity : AppCompatActivity() { companion object { private const val ITEM_COUNT: Int = 100 + + @Volatile var imageLoaded = CountDownLatch(1) + @Volatile var imageBounds = Rect.Zero } + // two colors, so a replay frame shows whether the image is masked: a mask is one color + private val image = + createBitmap(2, 1).apply { + this[0, 0] = android.graphics.Color.BLACK + this[1, 0] = android.graphics.Color.WHITE + } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + imageLoaded = CountDownLatch(1) setContent { MaterialTheme { @@ -42,6 +62,18 @@ class ComposeActivity : AppCompatActivity() { .testTag("button_login"), ) { Text("Login") + // at the top, away from the center that the UI tests tap + AsyncImage( + model = image, + contentDescription = null, + contentScale = ContentScale.FillBounds, + onSuccess = { imageLoaded.countDown() }, + modifier = + Modifier.align(Alignment.TopCenter) + .padding(top = 48.dp) + .size(96.dp) + .onGloballyPositioned { imageBounds = it.boundsInWindow() }, + ) } } items(ITEM_COUNT) { diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index 7ab50359b06..8de025ab0b7 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -80,6 +80,7 @@ dependencies { testImplementation(libs.androidx.test.ext.junit) testImplementation(libs.androidx.viewpager2) testImplementation(libs.google.truth) + testImplementation(libs.kotlin.test.junit) testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) testImplementation(libs.roboelectric) 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 aa012117158..b977c6fccc9 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 @@ -91,7 +91,8 @@ public class SentryBackStackEntry( * - [CharSequence] * - [Char] * - [Boolean] - * - any [Number] (`NaN` and infinite values are sent as strings) + * - any [Number] (`NaN` and infinite values are sent as the strings `"NaN"`, `"Infinity"`, and + * `"-Infinity"`, which JSON can represent) * - enums (via [Enum.name]) * - `null` * @@ -109,9 +110,9 @@ public class SentryBackStackEntry( * All non-supported argument types are stringified via `toString()`, as are map keys. * * No arguments will be recorded for a back stack entry if [map] throws or returns `null`, or if its - * arguments are cyclic, too deeply nested, too large, or contain map keys that stringify to the - * same string. 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. + * 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** * 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 0a70af1ac31..e15194da1c2 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 @@ -1,5 +1,6 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.compose.runtime.snapshots.Snapshot import io.sentry.ILogger import io.sentry.SentryLevel.WARNING import io.sentry.compose.navigation3.BackStackEntryMapper @@ -26,7 +27,7 @@ import java.util.IdentityHashMap * **Threading policy** * * This class performs work synchronously on the calling thread. The host app's - * [BackStackEntryMapper] is invoked on that same thread and should remain small, non-blocking, and + * `BackStackEntryMapper` is invoked on that same thread and should remain small, non-blocking, and * safe for the caller's threading context. */ internal class BackStackConverter( @@ -86,7 +87,12 @@ internal class BackStackConverter( } val sanitizedArguments = - info.arguments?.let(sanitizer::sanitizeEntry) ?: SanitizedArguments(emptyMap()) + info.arguments?.let { arguments -> + // Argument conversion may read Compose state through host app code. Suppress read + // observation so changes to that state don't trigger recomposition solely b/c our + // telemetry code read it. + Snapshot.withoutReadObservation { sanitizer.sanitizeEntry(arguments) } + } ?: SanitizedArguments(emptyMap()) val formattedName = NormalizedSentryBackStackEntry.formatName(info.name) return if (formattedName.isBlank()) { @@ -303,18 +309,19 @@ internal class BackStackConverter( override fun fillInStackTrace(): Throwable = this } - private companion object { + companion object { - private const val MAX_CHARACTER_WARNING = - "Nav3 arguments exceeded the maximum total character count for one backstack update. Skipping " + - "arguments for this and older captured entries." + const val MAX_CHARACTER_WARNING = + "Nav3 back stack update exceeded the argument character limit. Dropping arguments for " + + "this and older entries." - private const val MAX_COUNT_WARNING = - "Nav3 arguments exceeded the maximum total count for one backstack update. Skipping arguments for " + - "this and older captured entries." + const val MAX_COUNT_WARNING = + "Nav3 back stack update exceeded the argument value limit. Dropping arguments for this " + + "and older entries." - private const val STRUCTURE_WARNING = - "Nav3 argument sanitization failed (possibly a cyclic or deeply nested structure). Skipping arguments." + const val STRUCTURE_WARNING = + "Nav3 argument sanitization failed (possibly cyclic or too deeply nested). Dropping this " + + "entry's arguments." } } @@ -332,8 +339,7 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper returned a blank name while processing this back stack update. " + - "Using $UNKNOWN_ENTRY_NAME instead.", + "Nav3 backStackEntryMapper returned a blank name. Using $UNKNOWN_ENTRY_NAME.", ) hasLoggedInvalidNameWarning = true } @@ -345,8 +351,7 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper threw while resolving an entry. " + - "Using $UNKNOWN_ENTRY_NAME without arguments instead.", + "Nav3 backStackEntryMapper threw. Using $UNKNOWN_ENTRY_NAME without arguments.", throwable, ) hasLoggedMapperFailureWarning = true @@ -359,10 +364,8 @@ internal class BackStackConverter( logger.log( WARNING, - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this back " + - "stack update. Falling back to toString(). Use String, CharSequence, Char, Number, " + - "Boolean, Enum, Map, Collection, object Array, and primitive array values for reliable " + - "results.", + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper.", typeName, ) hasLoggedUnsupportedValueWarning = true 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 8cf28a3a3fd..988000c6b67 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 @@ -1,7 +1,10 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.lifecycle.LifecycleEventObserver import io.sentry.Breadcrumb import io.sentry.Hint +import io.sentry.IScope +import io.sentry.IScopes import io.sentry.SentryIntegrationPackageStorage import io.sentry.SentryLevel.INFO import io.sentry.SentryOptions @@ -16,6 +19,9 @@ 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 import io.sentry.compose.navigation3.internal.lifecycle.NAVIGATION_OP +import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator +import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo +import io.sentry.compose.navigation3.internal.lifecycle.NavScopes import io.sentry.compose.navigation3.internal.lifecycle.NavTransactionRequest import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion import java.lang.ref.WeakReference @@ -379,3 +385,70 @@ private class NavBreadcrumbs(private val scopes: INavScopes) { scopes.addBreadcrumb(breadcrumb, hint) } } + +/** + * A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with those of + * other `BackStackObserver`s. + * + * Coordination is achieved via [NavScopes]. + * + * **Usage** + * + * Call [attach] before the first [onBackStackChanged], and call [dispose] when observation ends. + * + * Instances targeting the same [IScope] must be created with the same [NavLeaseCoordinator]. + * + * **Thread safety** + * + * This class is ***not*** thread-safe. Invocations should be confined to the same thread as the + * [LifecycleEventObserver] callbacks through which the [NavLeaseCoordinator] observes the attached + * lifecycle. + */ +internal class CoordinatedBackStackObserver( + scopes: IScopes, + options: SentryNavOptions, + entryMapper: ForwardingBackStackEntryMapper, + coordinator: NavLeaseCoordinator, +) { + + private val navScopes = NavScopes(scopes, coordinator) + private val observer = BackStackObserver(navScopes, options, entryMapper) + + fun attach(rootInfo: NavRootInfo) { + navScopes.attach(rootInfo) + } + + fun onBackStackChanged(backStack: List) { + navScopes.onBackStackUpdate() + observer.onBackStackChanged(backStack) + } + + fun dispose() { + // Call disposal on both the observer and navScopes in case their (currently overlapping) + // implementations drift over time. + observer.dispose() + navScopes.dispose() + } +} + +/** + * The [NavLeaseCoordinator] shared by default by all [CoordinatedBackStackObserver]s. + * + * **Lifetime** + * + * The default coordinator lives as long as the process, since lease state follows nav root + * lifecycles rather than the SDK's. Closing and re-initializing the SDK doesn't require a reset + * because: + * + * - `SentryNavEffect` resolves the current scopes on every call; + * + * - while the SDK is closed, bookkeeping continues without a scope; and + * + * - unpublishing compares by reference, so values published to an earlier scope don't affect the + * current one. + * + * Limitation: A nav transaction that's still running when the SDK is closed and re-initialized can + * be bound to the new scope the next time it's published, although its client has been closed. + * Spans then attach to it, and are lost, until it times out or the next navigation finishes it. + */ +internal val defaultNavLeaseCoordinator: NavLeaseCoordinator = NavLeaseCoordinator() diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt deleted file mode 100644 index a7d30a998f3..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/CoordinatedBackStackObserver.kt +++ /dev/null @@ -1,76 +0,0 @@ -package io.sentry.compose.navigation3.internal.backstack - -import androidx.lifecycle.LifecycleEventObserver -import io.sentry.IScope -import io.sentry.IScopes -import io.sentry.compose.navigation3.SentryNavOptions -import io.sentry.compose.navigation3.internal.lifecycle.NavLeaseCoordinator -import io.sentry.compose.navigation3.internal.lifecycle.NavRootInfo -import io.sentry.compose.navigation3.internal.lifecycle.NavScopes - -/** - * A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with those of - * other `BackStackObserver`s. - * - * Coordination is achieved via [NavScopes]. - * - * **Usage** - * - * Call [attach] before the first [onBackStackChanged], and call [dispose] when observation ends. - * - * Instances targeting the same [IScope] must be created with the same [NavLeaseCoordinator]. - * - * **Thread safety** - * - * This class is ***not*** thread-safe. Invocations should be confined to the same thread as the - * [LifecycleEventObserver] callbacks through which the [NavLeaseCoordinator] observes the attached - * lifecycle. - */ -internal class CoordinatedBackStackObserver( - scopes: IScopes, - options: SentryNavOptions, - entryMapper: ForwardingBackStackEntryMapper, - coordinator: NavLeaseCoordinator, -) { - - private val navScopes = NavScopes(scopes, coordinator) - private val observer = BackStackObserver(navScopes, options, entryMapper) - - fun attach(rootInfo: NavRootInfo) { - navScopes.attach(rootInfo) - } - - fun onBackStackChanged(backStack: List) { - navScopes.onBackStackUpdate() - observer.onBackStackChanged(backStack) - } - - fun dispose() { - // Call disposal on both the observer and navScopes in case their (currently overlapping) - // implementations drift over time. - observer.dispose() - navScopes.dispose() - } -} - -/** - * The [NavLeaseCoordinator] shared by default by all [CoordinatedBackStackObserver]s. - * - * **Lifetime** - * - * The default coordinator lives as long as the process, since lease state follows nav root - * lifecycles rather than the SDK's. Closing and re-initializing the SDK doesn't require a reset - * because: - * - * - `SentryNavEffect` resolves the current scopes on every call; - * - * - while the SDK is closed, bookkeeping continues without a scope; and - * - * - unpublishing compares by reference, so values published to an earlier scope don't affect the - * current one. - * - * Limitation: A nav transaction that's still running when the SDK is closed and re-initialized can - * be bound to the new scope the next time it's published, although its client has been closed. - * Spans then attach to it, and are lost, until it times out or the next navigation finishes it. - */ -internal val defaultNavLeaseCoordinator: NavLeaseCoordinator = NavLeaseCoordinator() diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md new file mode 100644 index 00000000000..bc8bb10067e --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/backstack/README.md @@ -0,0 +1,22 @@ +# `io.sentry.compose.navigation3.internal.backstack` + +This package converts a host app's back stack into Sentry navigation data: screen names, navigation +breadcrumbs, transactions, and the captured back stack. + +## Mapping and sanitization + +The host app's `BackStackEntryMapper` supplies each entry's name and optional arguments in a +`SentryBackStackEntry`. Properties are the fields and values on the host's back stack entry; +arguments are the values the mapper chooses to expose as `SentryBackStackEntry.arguments`. + +Arguments are the mapper's output before sanitization. `BackStackConverter` normalizes entry names +and sanitizes arguments before they are recorded. Sanitization can stringify values or drop an +entry's arguments when they are invalid or exceed the limits in `ArgumentConstraints`. +The value and character budgets are shared across the entries captured in one back stack update. + +## Observation and coordination + +`BackStackObserver` detects changes and records navigation data for one back stack. +`CoordinatedBackStackObserver` connects that observer to `NavScopes`, which coordinates access to +shared scope state with other navigation roots. The lifecycle and ownership rules live in the +[sibling lifecycle package](../lifecycle/README.md). diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md index c7fe450590d..d4161499e1d 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/README.md @@ -7,6 +7,11 @@ This package is meant to encapsulate knowledge about the possibility of multiple raises. Addressing those concerns is complicated. Confining them here makes them easier to reason about and easier to swap for alternative logic should we someday need to. +## Dependencies + +This package may ***not*** depend on any other `io.sentry.compose.navigation3` package, Compose, or +`androidx.navigation3`. It may use Android framework and AndroidX Lifecycle APIs directly. + ## Limitations Support for multiple `SentryNavEffect`s is restricted to the scenarios documented in the diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt index 34801621011..ae1750f00dc 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/internal/lifecycle/StagedNavData.kt @@ -93,7 +93,9 @@ internal class StagedNavData { * Clears the screen and nav context this instance published, unless something else has replaced * them in [realScope] since. */ + @Suppress("AvoidReferentialEquality") fun clearPublishedStateFrom(realScope: IScope) { + // Identity tracks the screen we published; equal but distinct host replacements must survive. if (publishedScreen != null && realScope.screen === publishedScreen) { realScope.screen = null } 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 new file mode 100644 index 00000000000..2ba320a31e8 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/PackageBoundariesTest.kt @@ -0,0 +1,103 @@ +package io.sentry.compose.navigation3 + +import com.google.common.truth.Truth.assertThat +import java.io.File +import org.junit.Test + +/** Enforces the lifecycle package's dependency boundary. */ +class PackageBoundariesTest { + + private val sources: List = + File(SOURCE_ROOT) + .walkTopDown() + .filter { it.isFile && it.extension == "kt" } + .map(SourceFile::parse) + .toList() + + @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) } + + val violations = lifecycleSources.importsMatching { + (it.isIn(ROOT) && !it.isIn(LIFECYCLE)) || + it.isIn("androidx.navigation3") || + (it.isIn("androidx") && "compose" in it.split('.')) + } + + assertThat(lifecycleSources).isNotEmpty() + assertThat(violations).isEmpty() + } + + // Check that the import reader finds the declarations the rules inspect. + + @Test + fun `reads the package and the targets of plain, aliased, and wildcard imports`() { + val file = File.createTempFile("Parsed", ".kt").apply { deleteOnExit() } + file.writeText( + """ + |@file:Suppress("unused") + | + |package com.example.feature + | + |import com.example.Plain + |import com.example.wildcard.* + |import com.example.Original as Alias + | + |class Parsed + """ + .trimMargin(), + ) + + val parsed = SourceFile.parse(file) + + assertThat(parsed.packageName).isEqualTo("com.example.feature") + assertThat(parsed.imports) + .containsExactly("com.example.Plain", "com.example.wildcard", "com.example.Original") + .inOrder() + } + + @Test + fun `reads imports from the module's Kotlin sources`() { + val imports = sources.flatMap { it.imports } + + assertThat(imports).contains("androidx.lifecycle.LifecycleOwner") + } + + /** A source file's location, package, and import targets. */ + private class SourceFile( + val path: String, + val packageName: String, + val imports: List, + ) { + companion object { + private val PACKAGE = Regex("""^package\s+([\w.]+)""") + private val IMPORT = Regex("""^import\s+([\w.]+?)(?:\.\*)?(?:\s+as\s+\w+)?\s*;?\s*$""") + + fun parse(file: File): SourceFile { + val lines = file.readLines().map(String::trim) + return SourceFile( + path = file.invariantSeparatorsPath, + packageName = + lines.firstNotNullOfOrNull { PACKAGE.find(it)?.groupValues?.get(1) }.orEmpty(), + imports = lines.mapNotNull { IMPORT.find(it)?.groupValues?.get(1) }, + ) + } + } + } + + private companion object { + const val SOURCE_ROOT = "src/main/kotlin" + const val ROOT = "io.sentry.compose.navigation3" + const val LIFECYCLE = "$ROOT.internal.lifecycle" + + /** Whether this name is [packageName] or lies inside it. */ + fun String.isIn(packageName: String): Boolean = + this == packageName || startsWith("$packageName.") + + /** Each import matching [isForbidden], as `path: name`. */ + fun List.importsMatching(isForbidden: (String) -> Boolean): List = + flatMap { file -> + file.imports.filter(isForbidden).map { "${file.path}: $it" } + } + } +} 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 new file mode 100644 index 00000000000..d9f0f76864a --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ArgumentSanitizerTest.kt @@ -0,0 +1,239 @@ +package io.sentry.compose.navigation3.internal.backstack + +import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger +import io.sentry.SentryLevel.WARNING +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_CHARACTERS +import io.sentry.compose.navigation3.internal.backstack.ArgumentConstraints.MAX_ARGUMENT_VALUES +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.ArgumentSanitizer +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.SanitizedArguments +import io.sentry.compose.navigation3.internal.backstack.BackStackConverter.WarningState +import kotlin.test.assertFailsWith +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify + +class ArgumentSanitizerTest { + + private class OpaqueValue { + override fun toString(): String = "opaque-value" + } + + private class ThrowingValue(val failure: IllegalStateException = IllegalStateException("boom")) { + @Suppress("ExceptionRaisedInUnexpectedLocation") override fun toString(): String = throw failure + } + + private val logger = mock() + private val sanitizer = ArgumentSanitizer(logger, WarningState()) + + private val laterArguments = mapOf("id" to "123") + + private companion object { + private const val UNSUPPORTED_VALUE_WARNING = + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper." + } + + // Plain maps + + @Test + fun `sanitizeEntry() - returns the arguments of a plain map as written`() { + val arguments = + mapOf("id" to "123", "filters" to mapOf("tags" to listOf("a", "b")), "page" to 2) + + val sanitized = sanitizer.sanitizeEntry(arguments) + + assertThat(sanitized).isEqualTo(SanitizedArguments(arguments)) + } + + @Test + fun `sanitizeEntry() - returns empty arguments without a drop reason for an empty map`() { + val sanitized = sanitizer.sanitizeEntry(emptyMap()) + + assertThat(sanitized).isEqualTo(SanitizedArguments(emptyMap(), dropReason = null)) + } + + // Unsupported values + + @Test + fun `sanitizeEntry() - logs the unsupported value warning with the value type`() { + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) + + verify(logger).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue")) + } + + @Test + fun `the unsupported value warning is logged once across entries sanitized by one sanitizer`() { + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue(), "alsoOpaque" to OpaqueValue())) + sanitizer.sanitizeEntry(mapOf("opaque" to OpaqueValue())) + + verify(logger, times(1)).log(eq(WARNING), eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue")) + } + + // Dropped arguments + + @Test + fun `sanitizeEntry() - drops arguments over the value budget and logs the value budget warning`() { + // The list and its elements are one value more than the budget. + 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)) + } + + @Test + fun `sanitizeEntry() - drops arguments over the character budget and logs the character budget warning`() { + // The key and the value are one character more than the budget. + val sanitized = sanitizer.sanitizeEntry(mapOf("v" to "x".repeat(MAX_ARGUMENT_CHARACTERS))) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.MAX_CHARACTER_WARNING)) + } + + @Test + fun `an entry whose own map contains itself is dropped without writing its contents again`() { + // The entry's own map is the cycle check's root, so "self" is rejected as soon as it begins, + // once the 30 scalars and "self" have spent 31 values. Otherwise its contents would be written + // once more before the cycle is found, spending another 31 values of the shared budget. + val selfContaining = mutableMapOf() + repeat(30) { selfContaining["k$it"] = it } + selfContaining["self"] = selfContaining + // A list and its elements, which spend exactly the values left. + val rest = mapOf("values" to List(MAX_ARGUMENT_VALUES - 31 - 1) { it }) + + val dropped = sanitizer.sanitizeEntry(selfContaining) + val later = sanitizer.sanitizeEntry(rest) + + assertThat(dropped) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.INVALID_STRUCTURE)) + assertThat(later).isEqualTo(SanitizedArguments(rest)) + } + + // Budgets shared across entries + + @Test + fun `entries sanitized by one sanitizer share the value budget`() { + // Each of the first two entries uses half of the value budget: a list and its elements. + val half = MAX_ARGUMENT_VALUES / 2 + val first = sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + val second = sanitizer.sanitizeEntry(mapOf("values" to List(half - 1) { it })) + val third = sanitizer.sanitizeEntry(mapOf("one" to 1)) + + assertThat(first.dropReason).isNull() + assertThat(second.dropReason).isNull() + assertThat(third).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.MAX_COUNT)) + } + + @Test + fun `entries sanitized by one sanitizer share the character budget`() { + // Each of the first two entries uses half of the character budget: a key and its value. + val half = MAX_ARGUMENT_CHARACTERS / 2 + val first = sanitizer.sanitizeEntry(mapOf("a" to "x".repeat(half - 1))) + val second = sanitizer.sanitizeEntry(mapOf("b" to "x".repeat(half - 1))) + val third = sanitizer.sanitizeEntry(mapOf("c" to null)) + + assertThat(first.dropReason).isNull() + assertThat(second.dropReason).isNull() + assertThat(third).isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.CHARACTER_LIMIT)) + } + + // Failures + + @Test + fun `sanitizeEntry() - drops arguments for a sanitization failure when a value throws`() { + val sanitized = sanitizer.sanitizeEntry(mapOf("ok" to 1, "throwing" to ThrowingValue())) + + assertThat(sanitized) + .isEqualTo(SanitizedArguments(emptyMap(), ArgumentDropReason.SANITIZATION_FAILED)) + } + + @Test + fun `sanitizeEntry() - logs the structure warning with the exception when a value throws`() { + val throwing = ThrowingValue() + + sanitizer.sanitizeEntry(mapOf("throwing" to throwing)) + + verify(logger).log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), eq(throwing.failure)) + } + + @Test + fun `sanitizeEntry() - rethrows fatal errors thrown during sanitization`() { + val fatal = + object { + override fun toString(): String = throw StackOverflowError("fatal") + } + + assertFailsWith { + sanitizer.sanitizeEntry(mapOf("fatal" to fatal)) + } + verify(logger, never()) + .log(eq(WARNING), eq(ArgumentSanitizer.STRUCTURE_WARNING), any()) + } + + @Test + fun `a container from an entry that failed sanitization isn't treated as a cycle in later entries`() { + val holder = mutableListOf(ThrowingValue()) + sanitizer.sanitizeEntry(mapOf("holder" to holder)) + holder.clear() + + val sanitized = sanitizer.sanitizeEntry(mapOf("holder" to holder)) + + assertThat(sanitized).isEqualTo(SanitizedArguments(mapOf("holder" to emptyList()))) + } + + // Later entries after a drop + + @Test + fun `entries after the value budget is exhausted are dropped without another warning`() { + sanitizer.sanitizeEntry(mapOf("values" to List(MAX_ARGUMENT_VALUES) { it })) + + 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)) + } + + @Test + fun `entries after the character budget is exhausted are dropped without another warning`() { + sanitizer.sanitizeEntry(mapOf("v" to "x".repeat(MAX_ARGUMENT_CHARACTERS))) + + 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)) + } + + @Test + fun `an entry dropped for invalid structure doesn't drop later entries`() { + val cyclic = mutableListOf() + cyclic.add(cyclic) + sanitizer.sanitizeEntry(mapOf("cyclic" to cyclic)) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } + + @Test + fun `an entry dropped for a duplicate map key doesn't drop later entries`() { + sanitizer.sanitizeEntry(mapOf("nested" to mapOf(1 to "a", "1" to "b"))) + + 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())) + + val later = sanitizer.sanitizeEntry(laterArguments) + + assertThat(later).isEqualTo(SanitizedArguments(laterArguments)) + } +} 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 93ed4ceb604..3bc0608591d 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,18 +1,26 @@ package io.sentry.compose.navigation3.internal.backstack +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat import io.sentry.ILogger +import io.sentry.JsonSerializer 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.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 import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.never import org.mockito.kotlin.times import org.mockito.kotlin.verify @@ -33,6 +41,16 @@ class BackStackConverterTest { private val logger = mock() + private companion object { + const val BLANK_NAME_WARNING = + "Nav3 backStackEntryMapper returned a blank name. Using /unknown." + const val MAPPER_FAILURE_WARNING = + "Nav3 backStackEntryMapper threw. Using /unknown without arguments." + const val UNSUPPORTED_VALUE_WARNING = + "Nav3 argument type %s is unsupported. Using toString(). Return scalars, enums, maps, " + + "collections, or arrays from BackStackEntryMapper." + } + private val defaultEntryMapper = BackStackEntryMapper { entry -> SentryBackStackEntry(entry::class.simpleName ?: "") @@ -95,7 +113,7 @@ class BackStackConverterTest { } @Test - fun `convert preserves input order when top entry is first`() { + fun `convert with KEEP_FIRST returns entries in back stack order`() { val sut = getSut() val routes = @@ -114,20 +132,20 @@ class BackStackConverterTest { } @Test - fun `convert preserves input order when top entry is last`() { + fun `convert with KEEP_LAST returns entries in back stack order`() { val sut = getSut() val routes = sut.convert( - listOf(HomeScreen(), ProfileScreen("123"), SettingsScreen("privacy")), - RetentionPolicy.KEEP_FIRST, + listOf(SettingsScreen("privacy"), ProfileScreen("123"), HomeScreen()), + RetentionPolicy.KEEP_LAST, ) assertThat(routes) .containsExactly( - NormalizedSentryBackStackEntry("/HomeScreen"), - NormalizedSentryBackStackEntry("/ProfileScreen"), NormalizedSentryBackStackEntry("/SettingsScreen"), + NormalizedSentryBackStackEntry("/ProfileScreen"), + NormalizedSentryBackStackEntry("/HomeScreen"), ) .inOrder() } @@ -320,13 +338,19 @@ class BackStackConverterTest { verify(logger) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper returned a blank name while processing this back stack update. " + - "Using /unknown instead.", - ), + eq(BLANK_NAME_WARNING), ) } + @Test + fun `convert logs the blank name warning once per back stack update`() { + val sut = getSut(entryMapper = { SentryBackStackEntry(" ") }) + + sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) + + verify(logger, times(1)).log(eq(WARNING), eq(BLANK_NAME_WARNING)) + } + @Test fun `convert returns unknown name without arguments if mapper returns null`() { val sut = getSut(entryMapper = { null }) @@ -349,13 +373,28 @@ class BackStackConverterTest { verify(logger) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper threw while resolving an entry. Using /unknown without arguments instead.", - ), - org.mockito.kotlin.any(), + eq(MAPPER_FAILURE_WARNING), + any(), ) } + @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) + + verify(logger, times(1)).log(eq(WARNING), eq(MAPPER_FAILURE_WARNING), any()) + } + + @Test + 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 arguments in proper serializable form`() { val text = StringBuilder("hello") @@ -471,18 +510,31 @@ class BackStackConverterTest { verify(logger, times(1)) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this " + - "back stack update. Falling back to toString(). Use String, CharSequence, Char, " + - "Number, Boolean, Enum, Map, Collection, object Array, and primitive array values " + - "for reliable results.", - ), + eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue"), ) } @Test - fun `unsupported value warning can recur with a fresh update state`() { + fun `convert hides state reads during argument sanitization from snapshot observation`() { + val arguments = mutableStateMapOf("state" to "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 { override fun toString(): String = "opaque-value" } @@ -497,12 +549,7 @@ class BackStackConverterTest { verify(logger, times(1)) .log( eq(WARNING), - eq( - "Nav3 backStackEntryMapper returned unsupported argument value of type %s while processing this " + - "back stack update. Falling back to toString(). Use String, CharSequence, Char, " + - "Number, Boolean, Enum, Map, Collection, object Array, and primitive array values " + - "for reliable results.", - ), + eq(UNSUPPORTED_VALUE_WARNING), eq("OpaqueValue"), ) } @@ -555,6 +602,18 @@ class BackStackConverterTest { assertThat(entry.argumentDropReason).isEqualTo(ArgumentDropReason.CHARACTER_LIMIT) } + @Test + fun `convert starts each back stack update with a fresh argument budget`() { + val sut = + getSut(entryMapper = { entry -> entryInfo(entry, mapOf("values" to List(150) { it })) }) + + sut.convert(HomeScreen()) + val entry = sut.convert(HomeScreen()) + + assertThat(entry.arguments).isEqualTo(mapOf("values" to List(150) { it })) + assertThat(entry.argumentDropReason).isNull() + } + @Test fun `convert reports sanitization failures`() { class ThrowingValue { @@ -627,6 +686,31 @@ class BackStackConverterTest { .inOrder() } + @Test + fun `converted entries with non-finite number arguments serialize to valid JSON through Sentry's JSON serializer`() { + val sut = + getSut( + entryMapper = { entry -> + entryInfo( + entry, + mapOf( + "price" to Double.NaN, + "limits" to floatArrayOf(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), + ), + ) + }, + ) + val serializedEntry = sut.convert(HomeScreen()).serialize() + val json = StringWriter() + + JsonSerializer(SentryOptions()).serialize(serializedEntry, json) + + assertThat(json.toString()) + .isEqualTo( + """{"entry":"/HomeScreen","entry_arguments":{"price":"NaN","limits":["Infinity","-Infinity"]}}""", + ) + } + @Test fun `serialize includes the reason arguments were dropped`() { val entry = diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt index 6f56285b496..d0546d7adea 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/internal/backstack/ForwardingBackStackEntryMapperTest.kt @@ -40,6 +40,19 @@ class ForwardingBackStackEntryMapperTest { assertThat(mapped?.arguments).isNull() } + @Test + fun `map() - forwards to the mapper current when map is called`() { + var mapper = BackStackEntryMapper { SentryBackStackEntry("first") } + val sut = ForwardingBackStackEntryMapper { mapper } + val first = sut.map(HomeScreen()) + mapper = BackStackEntryMapper { SentryBackStackEntry("second") } + + val second = sut.map(HomeScreen()) + + assertThat(first).isEqualTo(SentryBackStackEntry("first")) + assertThat(second).isEqualTo(SentryBackStackEntry("second")) + } + @Test fun `mapper forwards null results`() { val sut = ForwardingBackStackEntryMapper { BackStackEntryMapper { null } } diff --git a/sentry-android-ndk-outproc/README.md b/sentry-android-ndk-outproc/README.md index fefcd96da8d..7ad125367e7 100644 --- a/sentry-android-ndk-outproc/README.md +++ b/sentry-android-ndk-outproc/README.md @@ -16,6 +16,3 @@ configurations.configureEach { ``` Otherwise, the build fails because it contains both native backends. - -The crash service needs API 30+. On older versions, native crash reporting is -disabled. diff --git a/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java index 985e3b1af5e..0a08e8345f8 100644 --- a/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java +++ b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java @@ -17,6 +17,7 @@ import android.os.RemoteException; import io.sentry.DateUtils; import io.sentry.ILogger; +import io.sentry.ISentryExecutorService; import io.sentry.SentryEnvelope; import io.sentry.SentryEnvelopeItem; import io.sentry.SentryEvent; @@ -42,8 +43,9 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -58,6 +60,7 @@ public final class SentryNdkCrashService extends Service { private static final @NotNull String MERGED_SUFFIX = ".merged"; private static final long POLL_INTERVAL_MILLIS = 250; private static final long MATCH_TOLERANCE_MILLIS = 30000; + private static final long CONNECT_TIMEOUT_MILLIS = 10000; private final @NotNull IBinder binder = new Binder() { @@ -110,7 +113,7 @@ protected boolean onTransact( } }; - static @Nullable ServiceConnection start( + static @Nullable Connection start( final @NotNull Context context, final @NotNull SentryAndroidOptions options) { // fail before binding, the crash daemon can't attach without the native libraries io.sentry.ndk.SentryNdk.loadNativeLibraries(); @@ -137,7 +140,7 @@ protected boolean onTransact( return null; } - final int shmFd = io.sentry.ndk.SentryNdk.createCrashShm(); + final int shmFd = io.sentry.ndk.SentryNdk.createCrashShm(nativeDatabaseDir.getPath()); if (shmFd < 0) { options.getLogger().log(SentryLevel.DEBUG, "Failed to create NDK crash shared memory."); return null; @@ -150,6 +153,7 @@ protected boolean onTransact( ParcelFileDescriptor readyWrite = null; ParcelFileDescriptor messageWrite = null; ParcelFileDescriptor messageRead = null; + @Nullable ServiceEnds ends = null; try { final ParcelFileDescriptor[] notifyPipe = ParcelFileDescriptor.createPipe(); final ParcelFileDescriptor[] readyPipe = ParcelFileDescriptor.createPipe(); @@ -160,16 +164,20 @@ protected boolean onTransact( final ParcelFileDescriptor[] messageSocket = ParcelFileDescriptor.createSocketPair(); messageWrite = messageSocket[0]; messageRead = messageSocket[1]; + ends = new ServiceEnds(shm.dup(), notifyRead, readyWrite, messageRead); + notifyRead = null; + readyWrite = null; + messageRead = null; final Intent intent = new Intent(context, SentryNdkCrashService.class); - final @Nullable ServiceConnection connection = + final @Nullable Connection connection = configureService( context, intent, options.getLogger(), + options.getTimerExecutorService(), nativeDatabaseDir.getPath(), context.getApplicationInfo().nativeLibraryDir, - shm, Process.myPid(), Process.myTid(), options.isTombstoneEnabled() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S, @@ -177,25 +185,24 @@ protected boolean onTransact( options.getShutdownTimeoutMillis(), new ArrayList<>(options.getInAppIncludes()), new ArrayList<>(options.getInAppExcludes()), - notifyRead, - readyWrite, - messageRead); + ends); + ends = null; if (connection == null) { - options.getLogger().log(SentryLevel.DEBUG, "NDK crash service did not configure."); + options.getLogger().log(SentryLevel.DEBUG, "NDK crash service did not bind."); return null; } + // the daemon attaches once the service connects io.sentry.ndk.SentryNdk.initCrashDaemon( shm.detachFd(), notifyWrite.detachFd(), readyRead.detachFd(), messageWrite.detachFd()); return connection; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - options.getLogger().log(SentryLevel.DEBUG, e, "Failed to start NDK crash service."); - return null; } catch (IOException | SecurityException e) { options.getLogger().log(SentryLevel.DEBUG, e, "Failed to start NDK crash service."); return null; } finally { + if (ends != null) { + ends.close(); + } closeQuietly(shm); closeQuietly(notifyRead); closeQuietly(notifyWrite); @@ -221,13 +228,13 @@ private static void closeQuietly(final @Nullable Closeable closeable) { } } - private static @Nullable ServiceConnection configureService( + private static @Nullable Connection configureService( final @NotNull Context context, final @NotNull Intent intent, final @NotNull ILogger logger, + final @NotNull ISentryExecutorService executorService, final @NotNull String nativeDatabasePath, final @Nullable String nativeLibraryDir, - final @NotNull ParcelFileDescriptor shm, final int appPid, final long appTid, final boolean tombstoneEnabled, @@ -235,25 +242,20 @@ private static void closeQuietly(final @Nullable Closeable closeable) { final long shutdownTimeoutMillis, final @NotNull ArrayList includes, final @NotNull ArrayList excludes, - final @NotNull ParcelFileDescriptor notifyRead, - final @NotNull ParcelFileDescriptor readyWrite, - final @NotNull ParcelFileDescriptor messageRead) - throws InterruptedException { - final CountDownLatch latch = new CountDownLatch(1); - final boolean[] configured = new boolean[] {false}; + final @NotNull ServiceEnds ends) { // a foreground app raises the service process only to visible without BIND_IMPORTANT final int flags = Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT; - final ServiceConnection connection = - new ServiceConnection() { - private boolean connected; + final Connection connection = + new Connection() { + private volatile boolean configured; @Override public void onServiceConnected( final @NotNull ComponentName name, final @NotNull IBinder service) { - if (connected) { - // a restarted service process has no daemon for this app - reattach( + if (!ends.take()) { + // a restarted or late service process has no daemon for this app + if (reattach( service, logger, nativeDatabasePath, @@ -264,16 +266,17 @@ public void onServiceConnected( debug, shutdownTimeoutMillis, includes, - excludes); + excludes)) { + configured = true; + } return; } - connected = true; - configured[0] = + configured = transactConfigure( service, nativeDatabasePath, nativeLibraryDir, - shm, + ends.shm, appPid, appTid, tombstoneEnabled, @@ -281,43 +284,64 @@ public void onServiceConnected( shutdownTimeoutMillis, includes, excludes, - notifyRead, - readyWrite, - messageRead); - latch.countDown(); + ends.notifyRead, + ends.readyWrite, + ends.messageRead); + ends.close(); + if (!configured) { + logger.log(SentryLevel.ERROR, "NDK crash service did not configure."); + } } @Override public void onServiceDisconnected(final @NotNull ComponentName name) { logger.log(SentryLevel.ERROR, "NDK crash service disconnected."); - latch.countDown(); } @Override public void onBindingDied(final @NotNull ComponentName name) { logger.log(SentryLevel.ERROR, "NDK crash service binding died."); - latch.countDown(); // a dead binding does not reconnect, it must be bound again - if (configured[0]) { + if (configured) { context.unbindService(this); bind(context, intent, flags, this); } } + + @Override + public void close() { + if (ends.take()) { + ends.close(); + } + } }; - if (!bind(context, intent, flags, connection)) { - return null; - } - boolean ready = false; + boolean bound = false; try { - ready = latch.await(10000, TimeUnit.MILLISECONDS) && configured[0]; - // stay bound, so the service process keeps the app's importance and is not frozen - return ready ? connection : null; + bound = bind(context, intent, flags, connection); } finally { - if (!ready) { - context.unbindService(connection); + if (!bound) { + ends.close(); } } + if (!bound) { + return null; + } + try { + executorService.schedule( + () -> { + if (ends.take()) { + // without a reader, native sends and the crash handler fail at once + ends.close(); + logger.log(SentryLevel.ERROR, "NDK crash service did not connect in time."); + } + }, + CONNECT_TIMEOUT_MILLIS); + } catch (RejectedExecutionException e) { + logger.log(SentryLevel.DEBUG, e, "Failed to schedule the NDK crash service timeout."); + } + // stay bound, so the service process keeps the app's importance and is not frozen + return connection; } private static boolean bind( @@ -326,13 +350,13 @@ private static boolean bind( final int flags, final @NotNull ServiceConnection connection) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - // deliver callbacks on the binder thread, the caller blocks on the latch + // deliver callbacks on the binder thread instead of the main thread return context.bindService(intent, flags, Runnable::run, connection); } return context.bindService(intent, connection, flags); } - private static void reattach( + private static boolean reattach( final @NotNull IBinder service, final @NotNull ILogger logger, final @NotNull String nativeDatabasePath, @@ -347,7 +371,7 @@ private static void reattach( final int shmFd = io.sentry.ndk.SentryNdk.dupCrashShmFd(); if (shmFd < 0) { logger.log(SentryLevel.ERROR, "NDK crash service restarted, but the app can't reattach."); - return; + return false; } final ParcelFileDescriptor shm = ParcelFileDescriptor.adoptFd(shmFd); @@ -391,8 +415,10 @@ private static void reattach( } else { logger.log(SentryLevel.ERROR, "NDK crash service restarted, failed to reattach the app."); } + return reattached; } catch (IOException | SecurityException e) { logger.log(SentryLevel.ERROR, e, "Failed to reattach to the NDK crash service."); + return false; } finally { closeQuietly(shm); closeQuietly(notifyRead); @@ -810,4 +836,41 @@ private DaemonConfig( this.debug = debug; } } + + // closes the service's ends of the crash IPC unless a connection took them + abstract static class Connection implements ServiceConnection, Closeable { + @Override + public abstract void close(); + } + + // the service's ends of the crash IPC, handed over on the first connection or closed + private static final class ServiceEnds { + private final @NotNull AtomicBoolean taken = new AtomicBoolean(); + private final @NotNull ParcelFileDescriptor shm; + private final @NotNull ParcelFileDescriptor notifyRead; + private final @NotNull ParcelFileDescriptor readyWrite; + private final @NotNull ParcelFileDescriptor messageRead; + + private ServiceEnds( + final @NotNull ParcelFileDescriptor shm, + final @NotNull ParcelFileDescriptor notifyRead, + final @NotNull ParcelFileDescriptor readyWrite, + final @NotNull ParcelFileDescriptor messageRead) { + this.shm = shm; + this.notifyRead = notifyRead; + this.readyWrite = readyWrite; + this.messageRead = messageRead; + } + + private boolean take() { + return taken.compareAndSet(false, true); + } + + private void close() { + closeQuietly(shm); + closeQuietly(notifyRead); + closeQuietly(readyWrite); + closeQuietly(messageRead); + } + } } diff --git a/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java index 0a18bf19660..38c158ce141 100644 --- a/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java +++ b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java @@ -2,8 +2,6 @@ import android.annotation.SuppressLint; import android.content.Context; -import android.content.ServiceConnection; -import android.os.Build; import io.sentry.SentryIntegrationPackageStorage; import io.sentry.android.core.NdkHandlerStrategy; import io.sentry.android.core.SentryAndroidOptions; @@ -29,7 +27,7 @@ public final class SentryNdkOutproc { @SuppressLint("StaticFieldLeak") // the application context from NdkIntegration private static @Nullable Context serviceContext; - private static @Nullable ServiceConnection serviceConnection; + private static @Nullable SentryNdkCrashService.Connection serviceConnection; private SentryNdkOutproc() {} @@ -68,8 +66,8 @@ public static void init(@NotNull final SentryAndroidOptions options) { public static void init( @Nullable final Context context, @NotNull final SentryAndroidOptions options) { // no fork/exec fallback, the native crash daemon only runs in the crash service - if (context == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { - throw new IllegalStateException("The NDK crash service needs a context and API 30+"); + if (context == null) { + throw new IllegalStateException("The NDK crash service needs a context"); } addPackage(options.getSdkVersion()); @@ -107,7 +105,7 @@ public static void init( ndkOptions.setEnableAppHangTracking(options.isEnableNdkAppHangTracking()); ndkOptions.setAppHangTimeoutMillis(options.getNdkAppHangTimeoutIntervalMillis()); - final @Nullable ServiceConnection connection = + final @Nullable SentryNdkCrashService.Connection connection = SentryNdkCrashService.start(context, options); if (connection == null) { throw new IllegalStateException("Failed to start the NDK crash service"); @@ -168,11 +166,15 @@ private static void addPackage(final @Nullable SdkVersion sdkVersion) { private static void unbindCrashService() { final @Nullable Context context = serviceContext; - final @Nullable ServiceConnection connection = serviceConnection; + final @Nullable SentryNdkCrashService.Connection connection = serviceConnection; serviceContext = null; serviceConnection = null; if (context != null && connection != null) { - context.unbindService(connection); + try { + context.unbindService(connection); + } finally { + connection.close(); + } } } } diff --git a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt index 61d56f4236b..8169bbc1970 100644 --- a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt @@ -1,7 +1,6 @@ package io.sentry.android.ndk.outproc import android.content.Context -import android.content.ServiceConnection import com.google.common.truth.Truth.assertThat import io.sentry.android.core.SentryAndroidOptions import io.sentry.ndk.NdkOptions @@ -54,12 +53,6 @@ class NativeBackendTest { assertFailsWith { SentryNdkOutproc.init(options()) } } - @Test - @Config(sdk = [29]) - fun `fails below API 30`() { - assertFailsWith { SentryNdkOutproc.init(mock(), options()) } - } - private fun options() = SentryAndroidOptions().apply { dsn = "https://key@sentry.io/proj" @@ -79,8 +72,10 @@ class NativeBackendTest { .`when` { io.sentry.ndk.SentryNdk.init(any()) } .doAnswer { captured = it.arguments[0] as NdkOptions } service - .`when` { SentryNdkCrashService.start(context, options) } - .thenReturn(mock()) + .`when` { + SentryNdkCrashService.start(context, options) + } + .thenReturn(mock()) SentryNdkOutproc.init(context, options) diff --git a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt index 15f47d70780..701fc4d8967 100644 --- a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt @@ -4,6 +4,9 @@ import android.app.ActivityManager import android.app.ApplicationExitInfo import android.content.ComponentName import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.ServiceConnection import android.os.Binder import android.os.Parcel import android.os.ParcelFileDescriptor @@ -15,10 +18,12 @@ import io.sentry.android.core.SentryAndroidOptions import io.sentry.android.core.cache.AndroidEnvelopeCache import io.sentry.ndk.NdkOptions import io.sentry.ndk.SentryNdk.CrashDaemon +import io.sentry.test.DeferredExecutorService import java.io.File import java.io.InputStream import java.util.Date import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executor import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit import java.util.zip.GZIPInputStream @@ -66,13 +71,48 @@ class SentryNdkCrashServiceTest { } @Test - fun `unbinds when the service does not configure`() { + fun `stays bound when the service does not configure`() { configure(false) Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { - assertThat(SentryNdkCrashService.start(app, options)).isNull() + val connection = SentryNdkCrashService.start(app, options) - assertThat(shadowOf(app).boundServiceConnections).isEmpty() - assertThat(shadowOf(app).unboundServiceConnections).hasSize(1) + assertThat(connection).isNotNull() + assertThat(shadowOf(app).boundServiceConnections).containsExactly(connection) + assertThat(shadowOf(app).unboundServiceConnections).isEmpty() + } + } + + @Test + fun `starts before the service connects`() { + val context = UnconnectedContext() + options.timerExecutorService = DeferredExecutorService() + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + val connection = SentryNdkCrashService.start(context, options) + + assertThat(connection).isNotNull() + assertThat(context.connections).containsExactly(connection) + native.verify { io.sentry.ndk.SentryNdk.initCrashDaemon(any(), any(), any(), any()) } + } + } + + @Test + fun `reattaches a service that connects after the timeout`() { + val binder = configure(true) + val context = UnconnectedContext() + val executor = DeferredExecutorService() + options.timerExecutorService = executor + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native.`when` { io.sentry.ndk.SentryNdk.dupCrashShmFd() }.thenReturn(42) + native + .`when` { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) } + .thenReturn(true) + val connection = SentryNdkCrashService.start(context, options)!! + + executor.runAll() + connection.onServiceConnected(component, binder) + + assertThat(binder.transactions).isEqualTo(1) + native.verify { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) } } } @@ -105,6 +145,22 @@ class SentryNdkCrashServiceTest { } } + @Test + fun `close releases the service ends before the service connects`() { + val binder = configure(true) + val context = UnconnectedContext() + options.timerExecutorService = DeferredExecutorService() + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native.`when` { io.sentry.ndk.SentryNdk.dupCrashShmFd() }.thenReturn(-1) + val connection = SentryNdkCrashService.start(context, options)!! + + connection.close() + connection.onServiceConnected(component, binder) + + assertThat(binder.transactions).isEqualTo(0) + } + } + @Test fun `init unbinds when native init fails`() { configure(true) @@ -179,11 +235,32 @@ class SentryNdkCrashServiceTest { } } + @Test + fun `binds again when the binding of a late service died`() { + val binder = configure(true) + val context = UnconnectedContext() + val executor = DeferredExecutorService() + options.timerExecutorService = executor + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native.`when` { io.sentry.ndk.SentryNdk.dupCrashShmFd() }.thenReturn(42) + native + .`when` { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) } + .thenReturn(true) + val connection = SentryNdkCrashService.start(context, options)!! + executor.runAll() + connection.onServiceConnected(component, binder) + + connection.onBindingDied(component) + + assertThat(context.connections).containsExactly(connection, connection) + } + } + @Test fun `init fails without shared memory`() { configure(true) Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> - native.`when` { io.sentry.ndk.SentryNdk.createCrashShm() }.thenReturn(-1) + native.`when` { io.sentry.ndk.SentryNdk.createCrashShm(any()) }.thenReturn(-1) assertFailsWith { SentryNdkOutproc.init(app, options) } @@ -439,6 +516,21 @@ class SentryNdkCrashServiceTest { private fun descriptor(fd: Int): ParcelFileDescriptor = mock { on { detachFd() } doReturn fd } + // binds without connecting, as a service process that is still starting + private inner class UnconnectedContext : ContextWrapper(app) { + val connections = mutableListOf() + + override fun bindService( + service: Intent, + flags: Int, + executor: Executor, + conn: ServiceConnection, + ): Boolean { + connections += conn + return true + } + } + private fun configure(configured: Boolean) = object : Binder() { var transactions = 0 diff --git a/sentry-android-replay/build.gradle.kts b/sentry-android-replay/build.gradle.kts index 756a3c5a339..e13805ffef0 100644 --- a/sentry-android-replay/build.gradle.kts +++ b/sentry-android-replay/build.gradle.kts @@ -98,11 +98,13 @@ dependencies { testImplementation(libs.androidx.compose.foundation.layout) testImplementation(libs.androidx.compose.material3) testImplementation(libs.coil.compose) + testImplementation(libs.coil3.compose) } // Session Replay calls Compose internals, whose mangled JVM names change between Compose versions. -// .github/workflows/compose-ui-matrix.yml runs each version's task. The oldest entry pins material3 -// to a version that runs on that Compose UI, because the catalog's material3 needs a newer one. +// .github/workflows/replay-dependency-matrix.yml runs each version's task. The oldest entry pins +// material3 and Coil 3 to versions that run on that Compose UI, because the catalog's need a newer +// one. dependencyMatrix { matrix( name = "composeUi", @@ -115,6 +117,9 @@ dependencyMatrix { ), versionsFile = "compose-ui-versions.json", ) + // Compose image masking detects Coil's painter modifier by reflection, and Coil 3.1 changed it. + // Coil 2 is a different artifact and package, so it's covered by the default unit tests instead. + matrix(name = "coil3", groups = listOf("io.coil-kt.coil3"), versionsFile = "coil3-versions.json") } tasks.withType().configureEach { diff --git a/sentry-android-replay/detekt-baseline.xml b/sentry-android-replay/detekt-baseline.xml index 9a9534659dd..4b67d369de0 100644 --- a/sentry-android-replay/detekt-baseline.xml +++ b/sentry-android-replay/detekt-baseline.xml @@ -105,7 +105,6 @@ MaxLineLength:ComposeMaskingOptionsTest.kt$ComposeMaskingOptionsTest$"Flaky: Robolectric intermittently reports zero bounds for nodes, causing isVisible=false and making the assertion non-deterministic" NestedBlockDepth:CaptureStrategy.kt$CaptureStrategy.Companion$private fun buildReplay( options: SentryOptions, video: File, currentReplayId: SentryId, segmentTimestamp: Date, segmentId: Int, height: Int, width: Int, frameCount: Int, frameRate: Int, videoDuration: Long, replayType: ReplayType, screenAtStart: String?, breadcrumbs: List<Breadcrumb>, events: Deque<RRWebEvent>, traceIds: List<String>, segmentNames: List<String>, ): ReplaySegment NestedBlockDepth:DefaultReplayBreadcrumbConverter.kt$DefaultReplayBreadcrumbConverter$private fun Breadcrumb.toRRWebSpanEvent(): RRWebSpanEvent - NestedBlockDepth:Nodes.kt$internal fun LayoutNode.findPainter(): Painter? NestedBlockDepth:Nodes.kt$internal fun LayoutNode.findTextColor(): Color? NestedBlockDepth:ReplayGestureConverter.kt$ReplayGestureConverter$fun convert( event: MotionEvent, recorderConfig: ScreenshotRecorderConfig, ): List<RRWebIncrementalSnapshotEvent>? NestedBlockDepth:SimpleVideoEncoder.kt$SimpleVideoEncoder$private fun drainCodec(endOfStream: Boolean) diff --git a/sentry-android-replay/proguard-rules.pro b/sentry-android-replay/proguard-rules.pro index 6ce45c1ef5d..90a78965e89 100644 --- a/sentry-android-replay/proguard-rules.pro +++ b/sentry-android-replay/proguard-rules.pro @@ -8,6 +8,8 @@ -keepclasseswithmembernames class * { androidx.compose.ui.graphics.painter.Painter painter; } +# Elements without a painter member, e.g. Coil 3.1+ ContentPainterElement, are masked by name only +-keepnames class **PainterElement # Rules to detect Text colors and if they have Modifier.fillMaxWidth to later mask them -dontwarn androidx.compose.ui.graphics.ColorProducer -dontwarn androidx.compose.foundation.layout.FillElement diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt index 704260cf311..a32c51174a8 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/util/Nodes.kt @@ -83,19 +83,28 @@ internal class ComposeTextLayout(internal val layout: TextLayoutResult) : TextLa * * That's not going to cover all cases, but probably 90%. * + * Returns null if the node has no such modifier, otherwise whether the image should be masked (see + * [isMaskable]). If the modifier has no readable `painter` member, e.g. Coil 3.1+ keeps the painter + * on its Modifier.Node instead, we can't tell what it draws, so we treat it as maskable. For Coil + * that's the same result as reading it: its painter is always the `AsyncImagePainter` wrapper, + * which [isMaskable] can't tell apart from a remote image. + * * We also add special proguard rules to keep the `Painter` class names and their `painter` member. */ -internal fun LayoutNode.findPainter(): Painter? { +internal fun LayoutNode.isMaskableImage(): Boolean? { val modifierInfos = getModifierInfo() for (index in modifierInfos.indices) { val modifier = modifierInfos[index].modifier if (modifier::class.java.name.contains("Painter")) { - return try { - modifier::class.java.getDeclaredField("painter").apply { isAccessible = true }.get(modifier) - as? Painter - } catch (e: Throwable) { - null - } + // a lookup by name instead of getDeclaredField, which throws on every frame for Coil 3.1+ + val painter = + modifier::class + .java + .declaredFields + .firstOrNull { it.name == "painter" } + ?.apply { isAccessible = true } + ?.get(modifier) as? Painter + return painter?.isMaskable() ?: true } } return null diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt index 9e4615ec36b..288e6df4cd9 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/viewhierarchy/ComposeViewHierarchyNode.kt @@ -24,9 +24,8 @@ import io.sentry.android.replay.SentryReplayModifiers import io.sentry.android.replay.util.ComposeTextLayout import io.sentry.android.replay.util.SentryReplayDebug import io.sentry.android.replay.util.boundsInWindow -import io.sentry.android.replay.util.findPainter import io.sentry.android.replay.util.findTextColor -import io.sentry.android.replay.util.isMaskable +import io.sentry.android.replay.util.isMaskableImage import io.sentry.android.replay.util.toOpaque import io.sentry.android.replay.util.toRect import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode.GenericViewHierarchyNode @@ -228,8 +227,8 @@ internal object ComposeViewHierarchyNode { ) } else -> { - val painter = node.findPainter() - if (painter != null) { + val isMaskableImage = node.isMaskableImage() + if (isMaskableImage != null) { val shouldMask = isVisible && semantics.shouldMask(isImage = true, options) parent?.setImportantForCaptureToAncestors(true) @@ -243,7 +242,7 @@ internal object ComposeViewHierarchyNode { parent = parent, isVisible = isVisible, isImportantForContentCapture = true, - shouldMask = shouldMask && painter.isMaskable(), + shouldMask = shouldMask && isMaskableImage, visibleRect = visibleRect.toRect(), ) } else { diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/viewhierarchy/ComposeMaskingOptionsTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/viewhierarchy/ComposeMaskingOptionsTest.kt index f21a1bc1a15..bb69b894508 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/viewhierarchy/ComposeMaskingOptionsTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/viewhierarchy/ComposeMaskingOptionsTest.kt @@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.material3.TextField @@ -36,6 +37,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.test.ext.junit.runners.AndroidJUnit4 import coil.compose.AsyncImage +import coil3.compose.AsyncImage as Coil3AsyncImage import com.google.common.truth.Truth.assertThat import io.sentry.NoOpLogger import io.sentry.SentryOptions @@ -147,7 +149,7 @@ class ComposeMaskingOptionsTest { val options = SentryOptions().apply { sessionReplay.maskAllImages = true } val imageNodes = activity.get().collectNodesOfType(options) - assertEquals(1, imageNodes.size) // [AsyncImage] + assertEquals(2, imageNodes.size) // [AsyncImage, Coil3AsyncImage] assertTrue(imageNodes.all { it.shouldMask }) } @@ -202,7 +204,7 @@ class ComposeMaskingOptionsTest { val options = SentryOptions().apply { sessionReplay.maskAllImages = false } val imageNodes = activity.get().collectNodesOfType(options) - assertEquals(1, imageNodes.size) // [AsyncImage] + assertEquals(2, imageNodes.size) // [AsyncImage, Coil3AsyncImage] assertTrue(imageNodes.none { it.shouldMask }) } @@ -418,6 +420,12 @@ private class ComposeMaskingOptionsActivity : ComponentActivity() { contentDescription = null, modifier = Modifier.padding(vertical = 16.dp), ) + // Coil 3 loads asynchronously, so without a size the node is empty and invisible + Coil3AsyncImage( + model = Uri.fromFile(File(image.toURI())), + contentDescription = null, + modifier = Modifier.size(10.dp), + ) Text("Random repo", fontSize = fontSizeApplier?.invoke() ?: TextUnit.Unspecified) TextField( modifier = textFieldModifierApplier?.invoke() ?: Modifier, diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OtelSpanUtils.java b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OtelSpanUtils.java index 798f8d7e449..b20dc03a5e6 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OtelSpanUtils.java +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OtelSpanUtils.java @@ -3,6 +3,7 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.semconv.incubating.MessagingIncubatingAttributes; import io.sentry.ISpan; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @@ -10,6 +11,20 @@ @ApiStatus.Internal public final class OtelSpanUtils { + + /** + * OpenTelemetry deprecated {@code messaging.system} in favor of {@code messaging.system.name}. + * Instrumentation may set either, so prefer {@code messaging.system} when both are set. + */ + @SuppressWarnings("deprecation") + static @Nullable String getMessagingSystem(final @NotNull Attributes attributes) { + final @Nullable String messagingSystem = + attributes.get(MessagingIncubatingAttributes.MESSAGING_SYSTEM); + return messagingSystem != null + ? messagingSystem + : attributes.get(MessagingIncubatingAttributes.MESSAGING_SYSTEM_NAME); + } + public static void maybeTransferOtelAttribute( final @NotNull SpanData otelSpan, final @NotNull ISpan sentrySpan, diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySpanExporter.java b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySpanExporter.java index 259fdd942bc..3d843bf0731 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySpanExporter.java +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySpanExporter.java @@ -3,6 +3,7 @@ import static io.sentry.TransactionContext.DEFAULT_TRANSACTION_NAME; import static io.sentry.opentelemetry.InternalSemanticAttributes.IS_REMOTE_PARENT; import static io.sentry.opentelemetry.OtelInternalSpanDetectionUtil.isSentryRequest; +import static io.sentry.opentelemetry.OtelSpanUtils.getMessagingSystem; import static io.sentry.opentelemetry.OtelSpanUtils.maybeTransferOtelAttribute; import io.opentelemetry.api.common.Attributes; @@ -244,6 +245,7 @@ private void createAndFinishSpanForOtelSpan( setOtelSpanKind(spanData, sentryChildSpan); transferSpanDetails(sentrySpanMaybe, sentryChildSpan); setSentrySpanKind(spanData, sentryChildSpan); + transferMessagingSystem(spanData, sentryChildSpan); for (SpanNode childNode : spanNode.getChildren()) { createAndFinishSpanForOtelSpan(childNode, sentryChildSpan, remaining); @@ -367,8 +369,7 @@ private void transferSpanDetails( maybeTransferOtelAttribute(span, sentryTransaction, ThreadIncubatingAttributes.THREAD_ID); maybeTransferOtelAttribute(span, sentryTransaction, ThreadIncubatingAttributes.THREAD_NAME); - maybeTransferOtelAttribute( - span, sentryTransaction, MessagingIncubatingAttributes.MESSAGING_SYSTEM); + transferMessagingSystem(span, sentryTransaction); maybeTransferOtelAttribute( span, sentryTransaction, MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME); maybeTransferOtelAttribute( @@ -387,6 +388,15 @@ private void transferSpanDetails( return sentryTransaction; } + @SuppressWarnings("deprecation") + private static void transferMessagingSystem( + final @NotNull SpanData span, final @NotNull ISpan sentrySpan) { + final @Nullable String messagingSystem = getMessagingSystem(span.getAttributes()); + if (messagingSystem != null) { + sentrySpan.setData(MessagingIncubatingAttributes.MESSAGING_SYSTEM.getKey(), messagingSystem); + } + } + private List findCompletedRootNodes(final @NotNull List grouped) { final @NotNull Predicate isRootPredicate = node -> { diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SpanDescriptionExtractor.java b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SpanDescriptionExtractor.java index 3af3d8f96f0..6326dd2848a 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SpanDescriptionExtractor.java +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SpanDescriptionExtractor.java @@ -24,12 +24,8 @@ public final class SpanDescriptionExtractor { final @NotNull SentryOptions options) { final @NotNull Attributes attributes = otelSpan.getAttributes(); - if (options.isEnableQueueTracing()) { - final @Nullable String messagingSystem = - attributes.get(MessagingIncubatingAttributes.MESSAGING_SYSTEM); - if (messagingSystem != null) { - return descriptionForMessagingSystem(otelSpan); - } + if (options.isEnableQueueTracing() && OtelSpanUtils.getMessagingSystem(attributes) != null) { + return descriptionForMessagingSystem(otelSpan); } final @Nullable String httpMethod = attributes.get(HttpAttributes.HTTP_REQUEST_METHOD); diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySpanExporterMessagingTest.kt b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySpanExporterMessagingTest.kt new file mode 100644 index 00000000000..e6219a99617 --- /dev/null +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySpanExporterMessagingTest.kt @@ -0,0 +1,128 @@ +package io.sentry.opentelemetry + +import com.google.common.truth.Truth.assertThat +import io.opentelemetry.context.Context +import io.opentelemetry.sdk.OpenTelemetrySdk +import io.opentelemetry.sdk.trace.SdkTracerProvider +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor +import io.opentelemetry.semconv.incubating.MessagingIncubatingAttributes +import io.sentry.ISentryClient +import io.sentry.NoOpScopes +import io.sentry.Sentry +import io.sentry.SentryOptions +import io.sentry.protocol.SentryId +import io.sentry.protocol.SentryTransaction +import io.sentry.test.createSentryClientMock +import io.sentry.test.createTestScopes +import java.util.concurrent.TimeUnit +import kotlin.test.AfterTest +import kotlin.test.Test +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.atLeastOnce +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class SentrySpanExporterMessagingTest { + private val options = + SentryOptions().apply { + dsn = "https://key@sentry.io/proj" + tracesSampleRate = 1.0 + } + private val client: ISentryClient = createSentryClientMock() + private val scopes = createTestScopes(options).also { it.bindClient(client) } + private val exporter = SentrySpanExporter(scopes) + + init { + whenever( + client.captureTransaction(anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()), + ) + .thenReturn(SentryId()) + Sentry.setCurrentScopes(scopes) + } + + @AfterTest + fun tearDown() { + Sentry.setCurrentScopes(NoOpScopes.getInstance()) + } + + @Test + fun `normalizes replacement messaging system on roots and children`() { + withOpenTelemetry { openTelemetry -> + val tracer = openTelemetry.getTracer("test") + val root = + tracer + .spanBuilder("root") + .setAttribute(MessagingIncubatingAttributes.MESSAGING_SYSTEM_NAME, "kafka") + .startSpan() + val child = + tracer + .spanBuilder("child") + .setParent(root.storeInContext(Context.root())) + .setAttribute(MessagingIncubatingAttributes.MESSAGING_SYSTEM_NAME, "rabbitmq") + .startSpan() + + child.end() + root.end() + } + + val transaction = capturedTransactions().single() + assertThat(transaction.contexts.trace!!.data["messaging.system"]).isEqualTo("kafka") + assertThat(transaction.spans).hasSize(1) + assertThat(transaction.spans.single().data!!["messaging.system"]).isEqualTo("rabbitmq") + } + + @Suppress("DEPRECATION") + @Test + fun `prefers legacy messaging system on roots and children`() { + withOpenTelemetry { openTelemetry -> + val tracer = openTelemetry.getTracer("test") + val root = + tracer + .spanBuilder("root") + .setAttribute(MessagingIncubatingAttributes.MESSAGING_SYSTEM, "kafka") + .setAttribute(MessagingIncubatingAttributes.MESSAGING_SYSTEM_NAME, "ignored-root") + .startSpan() + val child = + tracer + .spanBuilder("child") + .setParent(root.storeInContext(Context.root())) + .setAttribute(MessagingIncubatingAttributes.MESSAGING_SYSTEM, "rabbitmq") + .setAttribute(MessagingIncubatingAttributes.MESSAGING_SYSTEM_NAME, "ignored-child") + .startSpan() + + child.end() + root.end() + } + + val transaction = capturedTransactions().single() + assertThat(transaction.contexts.trace!!.data["messaging.system"]).isEqualTo("kafka") + assertThat(transaction.spans).hasSize(1) + assertThat(transaction.spans.single().data!!["messaging.system"]).isEqualTo("rabbitmq") + } + + private fun withOpenTelemetry(callback: (OpenTelemetrySdk) -> Unit) { + val provider = + SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build() + val openTelemetry = OpenTelemetrySdk.builder().setTracerProvider(provider).build() + try { + callback(openTelemetry) + provider.forceFlush().join(10, TimeUnit.SECONDS) + } finally { + provider.close() + } + } + + private fun capturedTransactions(): List { + val transaction = argumentCaptor() + verify(client, atLeastOnce()) + .captureTransaction( + transaction.capture(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + ) + return transaction.allValues + } +} diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SpanDescriptionExtractorTest.kt b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SpanDescriptionExtractorTest.kt index 4290b0cf7e3..db9a2d517c5 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SpanDescriptionExtractorTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SpanDescriptionExtractorTest.kt @@ -265,6 +265,63 @@ class SpanDescriptionExtractorTest { assertEquals(TransactionNameSource.TASK, info.transactionNameSource) } + @Test + fun `maps replacement messaging system name to queue publish op`() { + givenAttributes( + mapOf( + MessagingIncubatingAttributes.MESSAGING_SYSTEM_NAME to "kafka", + MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", + MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "publish", + ), + ) + + val info = whenExtractingSpanInfo(queueTracingEnabled = true) + + assertEquals("queue.publish", info.op) + assertEquals("my-topic", info.description) + assertEquals(TransactionNameSource.TASK, info.transactionNameSource) + } + + @Test + fun `replacement messaging system name wins over http when queue tracing enabled`() { + givenSpanKind(SpanKind.PRODUCER) + givenAttributes( + mapOf( + HttpAttributes.HTTP_REQUEST_METHOD to "POST", + UrlAttributes.URL_FULL to "https://sqs.us-east-1.amazonaws.com/", + MessagingIncubatingAttributes.MESSAGING_SYSTEM_NAME to "aws.sqs", + MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-queue", + MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "publish", + ), + ) + + val info = whenExtractingSpanInfo(queueTracingEnabled = true) + + assertEquals("queue.publish", info.op) + assertEquals("my-queue", info.description) + assertEquals(TransactionNameSource.TASK, info.transactionNameSource) + } + + @Test + fun `http wins over replacement messaging system name when queue tracing disabled`() { + givenSpanKind(SpanKind.CLIENT) + givenAttributes( + mapOf( + HttpAttributes.HTTP_REQUEST_METHOD to "POST", + UrlAttributes.URL_FULL to "https://sqs.us-east-1.amazonaws.com/", + MessagingIncubatingAttributes.MESSAGING_SYSTEM_NAME to "aws.sqs", + MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-queue", + MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "publish", + ), + ) + + val info = whenExtractingSpanInfo(queueTracingEnabled = false) + + assertEquals("http.client", info.op) + assertEquals("POST https://sqs.us-east-1.amazonaws.com/", info.description) + assertEquals(TransactionNameSource.URL, info.transactionNameSource) + } + @Test fun `maps messaging send operation type to queue publish op`() { givenAttributes( diff --git a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java index 3c2b5ccbcff..785fa28a69c 100644 --- a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java +++ b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java @@ -213,14 +213,12 @@ public void close() { private class CompositeData { private final @NotNull List dataList; private final @Nullable ITransaction transaction; - private final @NotNull Deadline collectUntil; + private final @NotNull Deadline timeout; private CompositeData(final @Nullable ITransaction transaction) { this.dataList = new ArrayList<>(); this.transaction = transaction; - // On a ticker rather than the date provider: this is how long we have been collecting, and - // a device time change must not end a collection early or keep a finished one going. - this.collectUntil = + this.timeout = Deadline.after( options.getMonotonicTicker(), TRANSACTION_COLLECTION_TIMEOUT_MILLIS, @@ -239,7 +237,7 @@ boolean addDataAndCheckTimeout(final @NotNull PerformanceCollectionData data) { synchronized (dataList) { dataList.add(data); } - return transaction != null && collectUntil.hasPassed(); + return transaction != null && timeout.hasPassed(); } } } diff --git a/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java b/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java index b635c9fbd5e..caf3901034b 100644 --- a/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java +++ b/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java @@ -18,6 +18,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; @@ -379,23 +380,15 @@ private static void ensureAttachmentSizeLimit( String.format("Failed to serialize perfetto profile chunk\n%s", e.getMessage())); } - // Read binary Perfetto trace - final byte[] traceBytes; + // [JSON metadata bytes][raw .pftrace binary bytes] try { - traceBytes = readBytesFromFile(traceFile.getPath(), MAX_PROFILE_CHUNK_SIZE); + return readFileAfterPrefix(metadataBytes, traceFile, MAX_PROFILE_CHUNK_SIZE); } catch (IOException e) { throw new SentryEnvelopeException( String.format("Failed to read perfetto trace file\n%s", e.getMessage())); } finally { traceFile.delete(); } - - // Concatenate: [JSON metadata bytes][raw .pftrace binary bytes] - final byte[] payload = new byte[metadataBytes.length + traceBytes.length]; - System.arraycopy(metadataBytes, 0, payload, 0, metadataBytes.length); - System.arraycopy(traceBytes, 0, payload, metadataBytes.length, traceBytes.length); - - return payload; }); SentryEnvelopeItemHeader itemHeader = @@ -416,6 +409,47 @@ private static void ensureAttachmentSizeLimit( return new SentryEnvelopeItem(itemHeader, () -> cachedItem.getBytes()); } + /** + * Reads {@code file} into a new array that starts with {@code prefix}. The file is read straight + * into its place in the result, so a large trace is held in memory once instead of being copied + * through intermediate buffers. + */ + private static byte[] readFileAfterPrefix( + final byte[] prefix, final @NotNull File file, final long maxFileLength) throws IOException { + if (!file.isFile() || !file.canRead()) { + throw new IOException( + String.format("Reading file '%s' failed, because it's not a readable file.", file)); + } + final long fileLength = file.length(); + if (fileLength > maxFileLength) { + throw new IOException( + String.format( + "Reading file failed, because size located at '%s' with %d bytes is bigger " + + "than the maximum allowed size of %d bytes.", + file, fileLength, maxFileLength)); + } + + final byte[] result = new byte[prefix.length + (int) fileLength]; + System.arraycopy(prefix, 0, result, 0, prefix.length); + try (final FileInputStream input = new FileInputStream(file)) { + int offset = prefix.length; + while (offset < result.length) { + final int read = input.read(result, offset, result.length - offset); + if (read == -1) { + throw new IOException( + String.format( + "Reading file '%s' failed, because it got shorter while reading.", file)); + } + offset += read; + } + if (input.read() != -1) { + throw new IOException( + String.format("Reading file '%s' failed, because it got longer while reading.", file)); + } + } + return result; + } + public static @NotNull SentryEnvelopeItem fromProfilingTrace( final @NotNull ProfilingTraceData profilingTraceData, final long maxTraceFileSize, diff --git a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt index ef055b9e8b2..dabc043a8e5 100644 --- a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt @@ -8,6 +8,7 @@ import io.sentry.time.TestMonotonicTicker import io.sentry.util.thread.ThreadChecker import java.util.Timer import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -36,6 +37,7 @@ class DefaultCompositePerformanceCollectorTest { val id1 = "id1" val scopes: IScopes = mock() val ticker = TestMonotonicTicker() + // SentryOptions has no ticker setter. val options = object : SentryOptions() { override fun getMonotonicTicker(): MonotonicTicker = ticker @@ -194,14 +196,10 @@ class DefaultCompositePerformanceCollectorTest { collector.start(fixture.transaction1) verify(fixture.mockTimer, never())!!.cancel() - // 31 seconds of collecting have gone by - fixture.ticker.advance(31, TimeUnit.SECONDS) - + fixture.ticker.advance(30, TimeUnit.SECONDS) // Let's sleep to make the collector get values Thread.sleep(300) - // When the collector gets the values, it checks how long it has been collecting for, which is - // now past the 30 second budget. This means it should stop itself verify(fixture.mockTimer)!!.cancel() // When the collector times out, the data collection for spans is stopped, too @@ -213,25 +211,52 @@ class DefaultCompositePerformanceCollectorTest { } @Test - fun `collector keeps collecting while inside the 30 second budget`() { + fun `collector collects for 30 seconds`() { val collector = fixture.getSut() collector.start(fixture.transaction1) - verify(fixture.mockTimer, never())!!.cancel() - - // 29 seconds of collecting have gone by - fixture.ticker.advance(29, TimeUnit.SECONDS) + fixture.ticker.advance(TimeUnit.SECONDS.toNanos(30) - 1, TimeUnit.NANOSECONDS) // Let's sleep to make the collector get values Thread.sleep(300) - // Still inside the 30 second budget, so it should continue without being cancelled verify(fixture.mockTimer, never())!!.cancel() - // Data is deleted after the collector times out val data1 = collector.stop(fixture.transaction1) assertNotNull(data1) } + @Test + fun `collector keeps collecting when the wall clock steps forward`() { + val wallClock = AtomicReference(wallClockAt(TimeUnit.HOURS.toSeconds(2))) + val collector = fixture.getSut { it.dateProvider = SentryDateProvider { wallClock.get() } } + collector.start(fixture.transaction1) + + wallClock.set(wallClockAt(TimeUnit.HOURS.toSeconds(3))) + // Let's sleep to make the collector get values + Thread.sleep(300) + + verify(fixture.mockTimer, never())!!.cancel() + assertNotNull(collector.stop(fixture.transaction1)) + } + + @Test + fun `collector times out when the wall clock steps backward`() { + val wallClock = AtomicReference(wallClockAt(TimeUnit.HOURS.toSeconds(2))) + val collector = fixture.getSut { it.dateProvider = SentryDateProvider { wallClock.get() } } + collector.start(fixture.transaction1) + + wallClock.set(wallClockAt(TimeUnit.HOURS.toSeconds(1))) + fixture.ticker.advance(30, TimeUnit.SECONDS) + // Let's sleep to make the collector get values + Thread.sleep(300) + + verify(fixture.mockTimer)!!.cancel() + assertNull(collector.stop(fixture.transaction1)) + } + + private fun wallClockAt(seconds: Long) = + SentryNanotimeDate(TimeUnit.SECONDS.toMillis(seconds), TimeUnit.SECONDS.toNanos(seconds)) + @Test fun `collector has no IPerformanceCollector by default`() { val collector = fixture.getSut(null, null) diff --git a/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt b/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt index 561d12a26c2..702b052b7c2 100644 --- a/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt +++ b/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt @@ -1,5 +1,6 @@ package io.sentry +import com.google.common.truth.Truth.assertThat import io.sentry.exception.SentryEnvelopeException import io.sentry.protocol.ReplayRecordingSerializationTest import io.sentry.protocol.SentryId @@ -14,10 +15,12 @@ import java.io.File import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter +import java.io.RandomAccessFile import java.io.StringWriter import java.nio.charset.Charset import java.nio.file.Files import java.util.concurrent.Callable +import kotlin.random.Random import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals @@ -675,6 +678,47 @@ class SentryEnvelopeItemTest { ) } + @Test + fun `fromPerfettoProfileChunk keeps a multi-megabyte trace intact after the metadata`() { + val traceFile = tmpDir.newFile("trace.pftrace") + val traceBytes = Random(42).nextBytes(3 * 1024 * 1024 + 17) + traceFile.writeBytes(traceBytes) + + val item = + SentryEnvelopeItem.fromPerfettoProfileChunk(perfettoChunk(traceFile), fixture.serializer) + + val payload = item.data + val metaLength = item.header.metaLength!! + assertThat(payload.size).isEqualTo(metaLength + traceBytes.size) + assertThat(payload.copyOfRange(metaLength, payload.size)).isEqualTo(traceBytes) + assertThat(traceFile.exists()).isFalse() + } + + @Test + fun `fromPerfettoProfileChunk with trace over 50MB throws and deletes the file`() { + val traceFile = tmpDir.newFile("trace.pftrace") + RandomAccessFile(traceFile, "rw").use { it.setLength(50L * 1024 * 1024 + 1) } + + val item = + SentryEnvelopeItem.fromPerfettoProfileChunk(perfettoChunk(traceFile), fixture.serializer) + + val exception = assertFailsWith { item.data } + assertThat(exception.message).contains("bigger than the maximum allowed size") + assertThat(traceFile.exists()).isFalse() + } + + private fun perfettoChunk(traceFile: File): ProfileChunk = + ProfileChunk.Builder( + SentryId(), + SentryId(), + emptyMap(), + traceFile, + SentryNanotimeDate(), + ProfileChunk.PLATFORM_ANDROID, + ) + .setContentType(ProfileChunk.CONTENT_TYPE_PERFETTO) + .build(fixture.options) + @Test fun `fromPerfettoProfileChunk with missing file throws`() { val traceFile = File("nonexistent.pftrace") diff --git a/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt b/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt index ff52464cb2d..3e904910e7c 100644 --- a/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt @@ -233,4 +233,17 @@ class HttpUtilsTest { Locale.setDefault(originalLocale) } } + + @Test + fun `sensitive data key check matches keys containing denylist terms in any case`() { + assertThat(HttpUtils.containsSensitiveDataKey("authToken")).isTrue() + assertThat(HttpUtils.containsSensitiveDataKey("X-API-KEY")).isTrue() + assertThat(HttpUtils.containsSensitiveDataKey("SessionId")).isTrue() + } + + @Test + fun `sensitive data key check doesn't match keys without denylist terms`() { + assertThat(HttpUtils.containsSensitiveDataKey("productId")).isFalse() + assertThat(HttpUtils.containsSensitiveDataKey("query")).isFalse() + } }