diff --git a/.craft.yml b/.craft.yml index 74c9cf05f6a..b2900c1bb5e 100644 --- a/.craft.yml +++ b/.craft.yml @@ -119,6 +119,11 @@ targets: packageUrl: https://central.sonatype.com/artifact/io.sentry/sentry-android-ndk mainDocsUrl: https://docs.sentry.io/platforms/android/ apiDocsUrl: https://javadoc.io/doc/io.sentry + maven:io.sentry:sentry-android-ndk-outproc: + name: io.sentry:sentry-android-ndk-outproc + packageUrl: https://central.sonatype.com/artifact/io.sentry/sentry-android-ndk-outproc + mainDocsUrl: https://docs.sentry.io/platforms/android/configuration/using-ndk/ + apiDocsUrl: https://javadoc.io/doc/io.sentry maven:io.sentry:sentry-android-timber: name: io.sentry:sentry-android-timber packageUrl: https://central.sonatype.com/artifact/io.sentry/sentry-android-timber diff --git a/.cursor/rules/e2e_tests.mdc b/.cursor/rules/e2e_tests.mdc index 3de11557f87..8295253b07f 100644 --- a/.cursor/rules/e2e_tests.mdc +++ b/.cursor/rules/e2e_tests.mdc @@ -56,11 +56,14 @@ match on values only they produce. ## The OpenTelemetry agent The agent must not run in the test's JVM, because it would instrument the test's own HTTP client -and server. The Spring Boot modules have an `agentFixture` source set with the app. `AgentApp` -starts it once per test JVM in a child process, with `ChildJvmApp` and the agent jar passed through +and server. The `io.sentry.otel-agent-tests` plugin in `build-logic` gives the Spring Boot modules +an `agentFixture` source set with the app, the `integrationTestOtelAgent` suite and the built agent +jar; each module adds only the dependencies of its Spring Boot line. `AgentApp` starts the app once +per test JVM in a child process, with `ChildJvmApp` and the agent jar passed through `ChildJvmTestArguments`. The suite's task runs with the agent initializing Sentry, and `integrationTestOtelAgentWithoutAutoInit` runs the same tests with the Spring Boot starter doing -it. Gradle runs the two in parallel. +it. Gradle runs the two in parallel. `otelAgentTests()` in a `springBootMatrix` block registers +both on each version. ## Running them diff --git a/.github/ISSUE_TEMPLATE/bug_report_android.yml b/.github/ISSUE_TEMPLATE/bug_report_android.yml index b16ab5ae7e2..9be51036190 100644 --- a/.github/ISSUE_TEMPLATE/bug_report_android.yml +++ b/.github/ISSUE_TEMPLATE/bug_report_android.yml @@ -10,6 +10,7 @@ body: options: - sentry-android - sentry-android-ndk + - sentry-android-ndk-outproc - sentry-android-timber - sentry-android-fragment - sentry-android-navigation3 diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d1593330dd3..93fc79f4a2f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -7,18 +7,18 @@ registries: password: dummy # Required by dependabot updates: - package-ecosystem: "gradle" - # The root build doesn't include the separate sample and test builds. - directories: - - "/" - - "/sentry-samples/sentry-samples-android" - - "/sentry-android-integration-tests" - - "/sentry-samples" + # The separate sample and test builds read this build's version catalog, so one directory + # covers them. Listing them too opens one PR per directory for the same bump. + directory: "/" registries: - gradle-plugin-portal schedule: interval: "daily" ignore: - dependency-name: "org.springframework.boot*" + - dependency-name: "io.opentelemetry*" + # DGS 5+ needs Spring Boot 3; the sample is on Spring Boot 2. + - dependency-name: "com.netflix.graphql.dgs*" commit-message: prefix: "chore(deps)" - package-ecosystem: "github-actions" diff --git a/.github/workflows/agp-matrix.yml b/.github/workflows/agp-matrix.yml index 7b1980b114d..26463fbcf32 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.2.1', '9.4.0' ] + agp: [ '9.0.0', '9.4.0', '9.5.1' ] 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.4.0' && matrix.integrations && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + 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) }} steps: - name: Checkout Repo diff --git a/.github/workflows/danger.yml b/.github/workflows/danger.yml index a39e3f8906a..e00d8a6e677 100644 --- a/.github/workflows/danger.yml +++ b/.github/workflows/danger.yml @@ -8,4 +8,4 @@ jobs: danger: runs-on: ubuntu-latest steps: - - uses: getsentry/github-workflows/danger@959162c159b866489d3fabe93327f48f9b8cb7ee # v3 + - uses: getsentry/github-workflows/danger@36529d71129a14967bea1fb81bcaf2a5943cf877 # v3 diff --git a/.github/workflows/pr-risk-jev.yml b/.github/workflows/pr-risk-jev.yml new file mode 100644 index 00000000000..48e7e8b7eb3 --- /dev/null +++ b/.github/workflows/pr-risk-jev.yml @@ -0,0 +1,120 @@ +name: PR Risk (Jev) + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review, edited] + workflow_dispatch: + inputs: + pr_number: + description: Pull request number to analyze + required: true + type: number + +permissions: + contents: read + pull-requests: write + +concurrency: + group: pr-risk-jev-${{ github.event.pull_request.number || inputs.pr_number }} + cancel-in-progress: true + +jobs: + risk: + name: PR risk (Jev) + runs-on: ubuntu-latest + timeout-minutes: 10 + if: github.event_name == 'workflow_dispatch' || github.event.pull_request.draft == false + steps: + # The Action reads PR Git objects without checking out or executing PR code. + - name: Classify PR risk + id: risk + uses: getsentry/pr-risk-action@1cdeab5ada06969e5376666b3a79f444c2f41a67 # main + env: + AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} + with: + repo: ${{ github.repository }} + pr-number: ${{ github.event.pull_request.number || inputs.pr_number }} + expected-head-sha: ${{ github.event.pull_request.head.sha }} + result-path: risk-pr-result.json + + - name: Publish risk label + if: ${{ !cancelled() && steps.risk.outcome != 'skipped' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr_number }} + with: + script: | + // Only this trusted workflow publishes labels; PR source is never executed. + const fs = require('node:fs'); + if (!fs.existsSync('risk-pr-result.json')) { + core.warning('Risk analysis did not produce a result; no label was published.'); + return; + } + const result = JSON.parse(fs.readFileSync('risk-pr-result.json', 'utf8')); + const prNumber = Number(process.env.PR_NUMBER); + const repo = context.repo; + const colors = { low: '0E8A16', medium: 'FBCA04', high: 'B60205' }; + const riskLabels = Object.keys(colors).map(risk => `risk: ${risk}`); + if (!Number.isSafeInteger(prNumber) || prNumber <= 0 + || result.number !== prNumber || result.repo !== `${repo.owner}/${repo.repo}` + || typeof result.status !== 'string' + || (result.status === 'ok' && !Object.hasOwn(colors, result.risk_label))) { + throw new Error('Risk result does not match this PR or a valid risk class.'); + } + const snapshot = result.snapshot; + if (result.status === 'pr_changed' || !snapshot?.source_head_sha || !snapshot?.source_base_sha) { + core.warning('Risk analysis has no current revision; no label was published.'); + return; + } + const { data: pr } = await github.rest.pulls.get({ ...repo, pull_number: prNumber }); + if (pr.state !== 'open' || pr.head.sha !== snapshot.source_head_sha + || pr.base.sha !== snapshot.source_base_sha) { + core.warning('PR changed after risk analysis; no label was published.'); + return; + } + const target = result.status === 'ok' ? `risk: ${result.risk_label}` : null; + const existing = pr.labels.map(label => label.name); + if (target && !existing.includes(target)) { + try { + await github.rest.issues.getLabel({ ...repo, name: target }); + } catch (error) { + if (error.status !== 404) throw error; + try { + await github.rest.issues.createLabel({ + ...repo, name: target, color: colors[result.risk_label], + description: `PR risk score: ${result.risk_label}`, + }); + } catch (error) { + if (error.status !== 422) throw error; + // Another PR may have created the shared repository label. + await github.rest.issues.getLabel({ ...repo, name: target }); + } + } + await github.rest.issues.addLabels({ ...repo, issue_number: prNumber, labels: [target] }); + } + // A failed classification must not leave an earlier low/medium/high verdict. + for (const name of existing.filter(name => riskLabels.includes(name) && name !== target)) { + try { + await github.rest.issues.removeLabel({ ...repo, issue_number: prNumber, name }); + } catch (error) { + if (error.status !== 404) throw error; + } + } + const { data: latest } = await github.rest.pulls.get({ ...repo, pull_number: prNumber }); + if (target && (latest.state !== 'open' || latest.head.sha !== pr.head.sha + || latest.base.sha !== pr.base.sha || latest.title !== pr.title || latest.body !== pr.body)) { + await github.rest.issues.removeLabel({ ...repo, issue_number: prNumber, name: target }); + core.warning('PR changed while publishing; removed the outdated risk label.'); + return; + } + if (!target) core.warning(`PR remains unclassified: ${result.status}. Previous risk labels were cleared.`); + core.info(target ? `Published ${target}` : 'No risk label published.'); + + - name: Upload risk result + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: pr-risk-jev-${{ github.event.pull_request.number || inputs.pr_number }} + path: risk-pr-result.json + if-no-files-found: warn + retention-days: 30 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 785e319eab2..6c0db20e7b6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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@9567926a606072678ef367b02445c4f99f374795 # 3.11.2 + uses: getsentry/craft@0da9309228741a4c300d3c87ed7dcafa8f703525 # 3.12.0 env: GITHUB_TOKEN: ${{ steps.token.outputs.token }} with: diff --git a/.github/workflows/update-deps.yml b/.github/workflows/update-deps.yml index ef51d5da084..f4a5a5d7d5c 100644 --- a/.github/workflows/update-deps.yml +++ b/.github/workflows/update-deps.yml @@ -18,7 +18,7 @@ jobs: native: runs-on: ubuntu-latest steps: - - uses: getsentry/github-workflows/updater@959162c159b866489d3fabe93327f48f9b8cb7ee # v3 + - uses: getsentry/github-workflows/updater@36529d71129a14967bea1fb81bcaf2a5943cf877 # v3 with: path: scripts/update-sentry-native-ndk.sh name: Native SDK diff --git a/.github/workflows/validate-pr.yml b/.github/workflows/validate-pr.yml index 307c7474be9..04dace10f49 100644 --- a/.github/workflows/validate-pr.yml +++ b/.github/workflows/validate-pr.yml @@ -10,7 +10,7 @@ jobs: permissions: pull-requests: write steps: - - uses: getsentry/github-workflows/validate-pr@959162c159b866489d3fabe93327f48f9b8cb7ee # v3 + - uses: getsentry/github-workflows/validate-pr@36529d71129a14967bea1fb81bcaf2a5943cf877 # v3 with: app-id: ${{ vars.SDK_MAINTAINER_BOT_APP_ID }} private-key: ${{ secrets.SDK_MAINTAINER_BOT_PRIVATE_KEY }} diff --git a/CHANGELOG.md b/CHANGELOG.md index cdc4d0f5eb9..be7899e2dd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,58 +72,90 @@ ### Features -- Monitor every Spring `@Scheduled` method with Sentry Crons by setting `sentry.monitor-scheduled-tasks=true`, without adding `@SentryCheckIn` to each method. Sentry creates each monitor from the method's `@Scheduled` schedule. Exclude methods with `sentry.exclude-scheduled-tasks` ([#6275](https://github.com/getsentry/sentry-java/pull/6275), [#6276](https://github.com/getsentry/sentry-java/pull/6276), [#6277](https://github.com/getsentry/sentry-java/pull/6277)) -- Quartz `SentryJobListener` can send a monitor config derived from the trigger with check-ins, so Sentry creates or updates the monitor from code. Set the `sentry-upsert-monitor-config` job or trigger data key to `"true"` to send the schedule ([#6216](https://github.com/getsentry/sentry-java/pull/6216)) -- Send a monitor config derived from Spring `@Scheduled` with `@SentryCheckIn` check-ins, so Sentry creates or updates the monitor from code. Set `@SentryCheckIn(upsertMonitorConfig = true)` to send the schedule ([#6215](https://github.com/getsentry/sentry-java/pull/6215)) -- Sentry OpenTelemetry integrations now honor `OTEL_BSP_SCHEDULE_DELAY` (`otel.bsp.schedule.delay`) for how often spans are sent to Sentry, instead of always waiting 5 seconds ([#6388](https://github.com/getsentry/sentry-java/pull/6388)) +- Add policy-controlled URL query parameters and fragments to Ktor HTTP client spans ([#6433](https://github.com/getsentry/sentry-java/pull/6433)) +- Session Replay: Add `Sentry.replay().pauseTouchTracking()` and `resumeTouchTracking()` to stop recording touches on sensitive screens, such as a custom PIN pad, while the screen recording continues. Touch tracking stays paused until `resumeTouchTracking()` is called, also for new replays and after `resume()` ([#6546](https://github.com/getsentry/sentry-java/pull/6546)) + +### Performance + +- Most SDK log calls no longer allocate when `debug` is off ([#6600](https://github.com/getsentry/sentry-java/pull/6600)) ### Behavioral Changes -- Gradle builds now resolve all Sentry SDK modules to the same version, the highest one present, because every module depends on `sentry-bom` as a platform ([#6466](https://github.com/getsentry/sentry-java/pull/6466)) - - Before, a build could mix module versions, for example a newer `sentry-android-core` with an older `sentry-android-fragment`, which failed at runtime. Maven builds resolve as before. - - `sentry-bom` now also includes `sentry-android-distribution`. +- Nav3: Returning to an Activity or Fragment with its own `SentryNavEffect` within the app (e.g., closing the Activity that covered it, swiping back to its ViewPager2 page, or dismissing a dialog over it) now starts a new navigation transaction for the current destination if the previous one finished, so spans produced upon return can now be consistently captured ([#6482](https://github.com/getsentry/sentry-java/pull/6482)) +- Nav3: `ui.load` transactions are bound to `IScope` in preference to Nav3 transactions when transitioning between Activities, matching Nav2 behavior (API 29+) ([#6484](https://github.com/getsentry/sentry-java/pull/6484)) -### Fixes +### Improvements -- Add opt-in support for matching GraphQL ignored error types against classification specifications via `sentry.graphql.enable-specification-error-type-filtering` ([#6092](https://github.com/getsentry/sentry-java/pull/6092)) -- Session Replay: Fix `SentryOkHttpInterceptor` hanging forever on responses whose body has no known length, such as Server-Sent Events or a gzipped response, when network details are enabled for the URL ([#6231](https://github.com/getsentry/sentry-java/pull/6231)) -- Session Replay: `SentryOkHttpInterceptor` now captures network request and response details only while Session Replay is recording or buffering ([#6486](https://github.com/getsentry/sentry-java/pull/6486)) -- Stop marking an OkHttp call span as failed when a connection attempt to one of the host's addresses fails but OkHttp connects on another ([#6472](https://github.com/getsentry/sentry-java/pull/6472)) -- Stop blocking the main thread while the frame metrics thread starts when the first activity transaction begins ([#6500](https://github.com/getsentry/sentry-java/pull/6500)) - - On a busy device during cold start this could stall the launcher activity's `onCreate` for hundreds of milliseconds. -- Do not inspect the response body of streaming Apollo 3 and 4 responses (`multipart/mixed`, `text/event-stream`) for failed requests, which blocked `@defer` and `@stream` ([#6432](https://github.com/getsentry/sentry-java/pull/6432)) -- 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)) +- Promote check-in APIs from experimental to stable ([#6422](https://github.com/getsentry/sentry-java/pull/6422)) +- Promote the backpressure handling option from experimental to stable ([#6423](https://github.com/getsentry/sentry-java/pull/6423)) +- Promote structured logs APIs from experimental to stable ([#6424](https://github.com/getsentry/sentry-java/pull/6424)) +- Promote the metrics capture API from experimental to stable ([#6425](https://github.com/getsentry/sentry-java/pull/6425)) +- Promote ignored span origin configuration APIs from experimental to stable ([#6427](https://github.com/getsentry/sentry-java/pull/6427)) +- Promote continuous profiler start and stop APIs from experimental to stable ([#6426](https://github.com/getsentry/sentry-java/pull/6426)) ### Fixes +- 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)) +- Session Replay: Send Ktor client network request start and end times in milliseconds, so the requests line up with the replay ([#6619](https://github.com/getsentry/sentry-java/pull/6619)) +- Nav3: Stop attributing errors and spans from an Activity or ViewPager2 page without a `SentryNavEffect` to the most recently visited Nav3 root ([#6483](https://github.com/getsentry/sentry-java/pull/6483)) +- Android: Count deep sleep in breadcrumb, screenshot and view hierarchy debounce windows, so the first low-memory or battery breadcrumb after a long Doze is no longer dropped ([#6590](https://github.com/getsentry/sentry-java/pull/6590)) +- Avoid duplicate serialization debug logs when calculating serialized object sizes ([#6255](https://github.com/getsentry/sentry-java/pull/6255)) -### Improvements +### Dependencies -- Promote check-in APIs from experimental to stable ([#6422](https://github.com/getsentry/sentry-java/pull/6422)) +- Bump OpenTelemetry ([#6602](https://github.com/getsentry/sentry-java/pull/6602)) + - OpenTelemetry to 1.67.0 (was 1.63.0) + - OpenTelemetry Instrumentation to 2.33.1 (was 2.29.0) + - OpenTelemetry Instrumentation Alpha to 2.33.1-alpha (was 2.29.0-alpha) + - OpenTelemetry Semantic Conventions to 1.44.0 (was 1.42.0) + - OpenTelemetry Semantic Conventions Alpha to 1.44.0-alpha (was 1.42.0-alpha) + - OpenTelemetry 1.67 creates no-op spans when no `SpanProcessor` is configured. If you construct the OpenTelemetry SDK manually while using `sentry-opentelemetry-otlp` classes directly, configure a span processor. Without one, Sentry cannot inspect outgoing request URLs and may inject `sentry-trace` and `baggage` headers into destinations excluded by `tracePropagationTargets`. Standard OTLP exporter, Sentry Java agent, and agentless setups already configure one. -### Improvements +### Internal -- Promote the backpressure handling option from experimental to stable ([#6423](https://github.com/getsentry/sentry-java/pull/6423)) +- 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.64.0 -### Improvements +### Breaking Changes -- Promote structured logs APIs from experimental to stable ([#6424](https://github.com/getsentry/sentry-java/pull/6424)) +- Android: `AnrV2Integration`, `AnrProfilingIntegration`, `WindowContentChangedCallback`, the deprecated `SentryUserFeedbackButton` and `SentryUserFeedbackDialog.Builder`, and the internal `sentry-android-core` classes are now `final`, and `ActivityLifecycleCallbacksAdapter` is now `abstract` ([#6494](https://github.com/getsentry/sentry-java/pull/6494)) -### Improvements +### Features -- Promote the metrics capture API from experimental to stable ([#6425](https://github.com/getsentry/sentry-java/pull/6425)) +- Connect Android traces with web content in a `WebView` using `SentryWebViewTracing.addTracePropagation(webView, "example.com")` ([#6395](https://github.com/getsentry/sentry-java/pull/6395)) + - Requires the `androidx.webkit:webkit` dependency. Only list hosts whose content you control. + - Call it on the main thread before each page load you want connected. + - Set `options.webViewTracing.allowedHosts`, or the `io.sentry.webview-tracing.allowed-hosts` manifest entry, to call `addTracePropagation(webView)` without passing hosts ([#6516](https://github.com/getsentry/sentry-java/pull/6516)) + - See the [WebView docs](https://docs.sentry.io/platforms/android/configuration/webview/) for details. +- Monitor every Spring `@Scheduled` method with Sentry Crons by setting `sentry.monitor-scheduled-tasks=true`, without adding `@SentryCheckIn` to each method. Sentry creates each monitor from the method's `@Scheduled` schedule. Exclude methods with `sentry.exclude-scheduled-tasks` ([#6275](https://github.com/getsentry/sentry-java/pull/6275), [#6276](https://github.com/getsentry/sentry-java/pull/6276), [#6277](https://github.com/getsentry/sentry-java/pull/6277)) +- Quartz `SentryJobListener` can send a monitor config derived from the trigger with check-ins, so Sentry creates or updates the monitor from code. Set the `sentry-upsert-monitor-config` job or trigger data key to `"true"` to send the schedule ([#6216](https://github.com/getsentry/sentry-java/pull/6216)) +- Send a monitor config derived from Spring `@Scheduled` with `@SentryCheckIn` check-ins, so Sentry creates or updates the monitor from code. Set `@SentryCheckIn(upsertMonitorConfig = true)` to send the schedule ([#6215](https://github.com/getsentry/sentry-java/pull/6215)) +- Sentry OpenTelemetry integrations now honor `OTEL_BSP_SCHEDULE_DELAY` (`otel.bsp.schedule.delay`) for how often spans are sent to Sentry, instead of always waiting 5 seconds ([#6388](https://github.com/getsentry/sentry-java/pull/6388)) +- Add experimental, opt-in out-of-process crash reporting on Android ([#6347](https://github.com/getsentry/sentry-java/pull/6347)) + - To enable it, add the `sentry-android-ndk-outproc` dependency and exclude `sentry-native-ndk`. Requires Android 11 (API level 30) or later. + - See the [NDK docs](https://docs.sentry.io/platforms/android/configuration/using-ndk/#out-of-process-crash-handling) for details. -### Dependencies +### Behavioral Changes -- Bump OkHttp from 4.9.2 to 5.5.1 ([#6472](https://github.com/getsentry/sentry-java/pull/6472)) - - `sentry-okhttp` and the Spring Boot integrations keep OkHttp as a `compileOnly` dependency, so your app keeps the OkHttp version it declares. OkHttp 4 is still supported. - - [changelog](https://github.com/square/okhttp/blob/master/CHANGELOG.md) - - [diff](https://github.com/square/okhttp/compare/parent-4.9.2...parent-5.5.1) +- Gradle builds now resolve all Sentry SDK modules to the same version, the highest one present, because every module depends on `sentry-bom` as a platform ([#6466](https://github.com/getsentry/sentry-java/pull/6466)) + - Before, a build could mix module versions, for example a newer `sentry-android-core` with an older `sentry-android-fragment`, which failed at runtime. Maven builds resolve as before. + - `sentry-bom` now also includes `sentry-android-distribution`. -### Internal +### Fixes -- 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)) +- Keep the interrupt of the thread that calls `Sentry.init` when it is interrupted while the SDK waits for cached events to be sent after a startup crash ([#6568](https://github.com/getsentry/sentry-java/pull/6568)) +- Capture scroll breadcrumbs for `LazyColumn`, `LazyRow`, lazy grids, and `Pager` on Jetpack Compose foundation 1.10+ ([#6548](https://github.com/getsentry/sentry-java/pull/6548)) +- Prevent the main thread from potentially hanging during app start or when returning to the foreground if Android is slow to register the SDK's network or telephony listeners. `Sentry.init`, Session Replay, and capturing events no longer wait for that registration ([#6537](https://github.com/getsentry/sentry-java/pull/6537)) +- Add opt-in support for matching GraphQL ignored error types against classification specifications via `sentry.graphql.enable-specification-error-type-filtering` ([#6092](https://github.com/getsentry/sentry-java/pull/6092)) +- Session Replay: Fix `SentryOkHttpInterceptor` hanging forever on responses whose body has no known length, such as Server-Sent Events or a gzipped response, when network details are enabled for the URL ([#6231](https://github.com/getsentry/sentry-java/pull/6231)) +- Session Replay: `SentryOkHttpInterceptor` now captures network request and response details only while Session Replay is recording or buffering ([#6486](https://github.com/getsentry/sentry-java/pull/6486)) +- Stop marking an OkHttp call span as failed when a connection attempt to one of the host's addresses fails but OkHttp connects on another ([#6472](https://github.com/getsentry/sentry-java/pull/6472)) +- Stop blocking the main thread while the frame metrics thread starts when the first activity transaction begins ([#6500](https://github.com/getsentry/sentry-java/pull/6500)) + - On a busy device during cold start this could stall the launcher activity's `onCreate` for hundreds of milliseconds. +- Do not inspect the response body of streaming Apollo 3 and 4 responses (`multipart/mixed`, `text/event-stream`) for failed requests, which blocked `@defer` and `@stream` ([#6432](https://github.com/getsentry/sentry-java/pull/6432)) +- Session Replay: Measure how long touch moves are batched on a monotonic clock, so a device time change during a swipe no longer drops its positions, delays them, or stretches their timing ([#6538](https://github.com/getsentry/sentry-java/pull/6538)) ## 8.63.0 @@ -167,21 +199,9 @@ - Measure ANR detection and ANR profiling durations on the internal `MonotonicTicker` ([#6041](https://github.com/getsentry/sentry-java/pull/6041)) -### Improvements - -- Promote ignored span origin configuration APIs from experimental to stable ([#6427](https://github.com/getsentry/sentry-java/pull/6427)) - -### Improvements - -- Promote continuous profiler start and stop APIs from experimental to stable ([#6426](https://github.com/getsentry/sentry-java/pull/6426)) +### Known Issues -### Features - -- Add policy-controlled URL query parameters and fragments to Ktor HTTP client spans ([#6433](https://github.com/getsentry/sentry-java/pull/6433)) - -### Fixes - -- Prevent changes to reused tracing options from affecting spans and transactions after creation ([#6417](https://github.com/getsentry/sentry-java/pull/6417)) +- On Android, the main thread may hang or trigger an ANR if the system is slow to register network or telephony callbacks during SDK initialization or when the app returns to the foreground. Fixed in `8.64.0` ([#6537](https://github.com/getsentry/sentry-java/pull/6537)). ## 8.62.0 @@ -196,6 +216,10 @@ - Always remove the first-draw listener after the first frame, even if no layout pass follows it ([#6152](https://github.com/getsentry/sentry-java/pull/6152)) - Prevent Reactor pool maintenance tasks from retaining unbounded Sentry scope chains ([#6283](https://github.com/getsentry/sentry-java/pull/6283)) +### Known Issues + +- On Android, the main thread may hang or trigger an ANR if the system is slow to register network or telephony callbacks during SDK initialization or when the app returns to the foreground. Fixed in `8.64.0` ([#6537](https://github.com/getsentry/sentry-java/pull/6537)). + ## 8.61.1 ### Fixes @@ -223,6 +247,10 @@ - [changelog](https://github.com/getsentry/sentry-native/blob/master/CHANGELOG.md#0174) - [diff](https://github.com/getsentry/sentry-native/compare/0.17.3...0.17.4) +### Known Issues + +- On Android, the main thread may hang or trigger an ANR if the system is slow to register network or telephony callbacks during SDK initialization or when the app returns to the foreground. Fixed in `8.64.0` ([#6537](https://github.com/getsentry/sentry-java/pull/6537)). + ## 8.61.0 ### Fixes @@ -253,6 +281,10 @@ - [changelog](https://github.com/getsentry/sentry-native/blob/master/CHANGELOG.md#0173) - [diff](https://github.com/getsentry/sentry-native/compare/0.17.2...0.17.3) +### Known Issues + +- On Android, the main thread may hang or trigger an ANR if the system is slow to register network or telephony callbacks during SDK initialization or when the app returns to the foreground. Fixed in `8.64.0` ([#6537](https://github.com/getsentry/sentry-java/pull/6537)). + ## 8.60.0 ### Features @@ -262,16 +294,16 @@ - See the [Navigation for Android docs](https://docs.sentry.io/platforms/android/integrations/navigation/) for additional details. - Report the cellular network technology generation in `device.connection_effective_type`, for example `4g` or `5g` ([#6146](https://github.com/getsentry/sentry-java/pull/6146)) -### Fixes - -- Avoid duplicate serialization debug logs when calculating serialized object sizes ([#6255](https://github.com/getsentry/sentry-java/pull/6255)) - ### Dependencies - Bump Native SDK from v0.17.1 to v0.17.2 ([#6230](https://github.com/getsentry/sentry-java/pull/6230)) - [changelog](https://github.com/getsentry/sentry-native/blob/master/CHANGELOG.md#0172) - [diff](https://github.com/getsentry/sentry-native/compare/0.17.1...0.17.2) +### Known Issues + +- On Android, the main thread may hang or trigger an ANR if the system is slow to register network or telephony callbacks during SDK initialization or when the app returns to the foreground. Fixed in `8.64.0` ([#6537](https://github.com/getsentry/sentry-java/pull/6537)). + ## 8.59.0 ### Breaking Changes diff --git a/README.md b/README.md index 89af6e7f128..5e6a607c4af 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ Sentry SDK for Java and Android | sentry-android-core | [![Maven Central Version](https://img.shields.io/maven-central/v/io.sentry/sentry-android-core?style=for-the-badge&logo=sentry&color=green)](https://central.sonatype.com/artifact/io.sentry/sentry-android-core) | 24 | | sentry-android-distribution | [![Maven Central Version](https://img.shields.io/maven-central/v/io.sentry/sentry-android-distribution?style=for-the-badge&logo=sentry&color=green)](https://central.sonatype.com/artifact/io.sentry/sentry-android-distribution) | 24 | | sentry-android-ndk | [![Maven Central Version](https://img.shields.io/maven-central/v/io.sentry/sentry-android-ndk?style=for-the-badge&logo=sentry&color=green)](https://central.sonatype.com/artifact/io.sentry/sentry-android-ndk) | 24 | +| sentry-android-ndk-outproc | [![Maven Central Version](https://img.shields.io/maven-central/v/io.sentry/sentry-android-ndk-outproc?style=for-the-badge&logo=sentry&color=green)](https://central.sonatype.com/artifact/io.sentry/sentry-android-ndk-outproc) | 24 | | sentry-android-timber | [![Maven Central Version](https://img.shields.io/maven-central/v/io.sentry/sentry-android-timber?style=for-the-badge&logo=sentry&color=green)](https://central.sonatype.com/artifact/io.sentry/sentry-android-timber) | 24 | | sentry-android-fragment | [![Maven Central Version](https://img.shields.io/maven-central/v/io.sentry/sentry-android-fragment?style=for-the-badge&logo=sentry&color=green)](https://central.sonatype.com/artifact/io.sentry/sentry-android-fragment) | 24 | | sentry-android-navigation | [![Maven Central Version](https://img.shields.io/maven-central/v/io.sentry/sentry-android-navigation?style=for-the-badge&logo=sentry&color=green)](https://central.sonatype.com/artifact/io.sentry/sentry-android-navigation) | 24 | diff --git a/agents.toml b/agents.toml index d9770ee7df5..04ad184c02c 100644 --- a/agents.toml +++ b/agents.toml @@ -1,6 +1,6 @@ -# Whenever you make changes to this file, run the following to update all generated dotagent files -# npx @sentry/dotagents install -# npx @sentry/dotagents sync +# Whenever you make changes to this file, run the following to update all generated dotagent files +# npx @sentry/dotagents --project install +# npx @sentry/dotagents --project sync version = 1 @@ -8,22 +8,6 @@ version = 1 name = "dotagents" source = "getsentry/dotagents" -[[skills]] -name = "sentry-workflow" -source = "getsentry/sentry-for-ai" - -[[skills]] -name = "sentry-fix-issues" -source = "getsentry/sentry-for-ai" - -[[skills]] -name = "sentry-code-review" -source = "getsentry/sentry-for-ai" - -[[skills]] -name = "sentry-pr-code-review" -source = "getsentry/sentry-for-ai" - [[skills]] name = "create-java-pr" source = "path:.agents/skills/create-java-pr" diff --git a/build-logic/build.gradle.kts b/build-logic/build.gradle.kts index 262315cd7d1..a947330afea 100644 --- a/build-logic/build.gradle.kts +++ b/build-logic/build.gradle.kts @@ -38,9 +38,17 @@ gradlePlugin { id = "io.sentry.animalsniffer.android" implementationClass = "io.sentry.gradle.SentryAnimalSnifferAndroidPlugin" } + register("sentryRobolectric") { + id = "io.sentry.robolectric" + implementationClass = "io.sentry.gradle.SentryRobolectricPlugin" + } register("sentrySpringBootMatrix") { id = "io.sentry.spring-boot-matrix" implementationClass = "io.sentry.gradle.SpringBootMatrixPlugin" } + register("sentryOtelAgentTests") { + id = "io.sentry.otel-agent-tests" + implementationClass = "io.sentry.gradle.OtelAgentTestsPlugin" + } } } diff --git a/build-logic/src/main/kotlin/io/sentry/gradle/AarTypes.kt b/build-logic/src/main/kotlin/io/sentry/gradle/AarTypes.kt index 0dda1a6bcb4..59145bf4d95 100644 --- a/build-logic/src/main/kotlin/io/sentry/gradle/AarTypes.kt +++ b/build-logic/src/main/kotlin/io/sentry/gradle/AarTypes.kt @@ -25,6 +25,7 @@ private val androidLibs = setOf( "sentry-android-core", "sentry-android-ndk", + "sentry-android-ndk-outproc", "sentry-android-fragment", "sentry-android-navigation", "sentry-android-navigation3", diff --git a/build-logic/src/main/kotlin/io/sentry/gradle/OtelAgentTestsPlugin.kt b/build-logic/src/main/kotlin/io/sentry/gradle/OtelAgentTestsPlugin.kt new file mode 100644 index 00000000000..33271f731a3 --- /dev/null +++ b/build-logic/src/main/kotlin/io/sentry/gradle/OtelAgentTestsPlugin.kt @@ -0,0 +1,107 @@ +package io.sentry.gradle + +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.attributes.Bundling +import org.gradle.api.attributes.Usage +import org.gradle.api.file.FileCollection +import org.gradle.api.plugins.JavaPlugin +import org.gradle.api.plugins.jvm.JvmTestSuite +import org.gradle.api.tasks.SourceSetContainer +import org.gradle.api.tasks.testing.Test +import org.gradle.language.base.plugins.LifecycleBasePlugin +import org.gradle.testing.base.TestingExtension + +private const val AGENT_FIXTURE = "agentFixture" +private const val OTEL_AGENT_JAR = "otelAgentJar" +private const val SUITE = "integrationTestOtelAgent" +private const val WITHOUT_AUTO_INIT = "${SUITE}WithoutAutoInit" + +/** + * Runs a Spring Boot module's OpenTelemetry agent tests against an app in a child JVM, with the + * built agent attached. + * + * The agent must not run in the test's JVM, because it would instrument the test's own HTTP client + * and server. So the app lives in the `agentFixture` source set and runs on its own classpath, like + * a real app. The `integrationTestOtelAgent` suite's task runs the tests with the agent + * initializing Sentry, and `integrationTestOtelAgentWithoutAutoInit` runs them with the Spring Boot + * starter doing it. Each test JVM starts one app, so the second mode needs a task of its own, which + * Gradle runs in parallel with the suite's. + * + * The module adds the app's and the suite's dependencies, which differ per Spring Boot line. + */ +class OtelAgentTestsPlugin : Plugin { + override fun apply(project: Project) { + project.pluginManager.apply(JavaPlugin::class.java) + val sourceSets = project.extensions.getByType(SourceSetContainer::class.java) + val agentFixture = sourceSets.create(AGENT_FIXTURE) + + // A plain project dependency on the agent module resolves to its unshadowed jar, which holds + // only AgentMarker. The agent itself is the shadowed jar, which already bundles its + // dependencies. + project.configurations.create(OTEL_AGENT_JAR) { + isCanBeResolved = true + isCanBeConsumed = false + isTransitive = false + attributes { + attribute( + Usage.USAGE_ATTRIBUTE, + project.objects.named(Usage::class.java, Usage.JAVA_RUNTIME), + ) + attribute( + Bundling.BUNDLING_ATTRIBUTE, + project.objects.named(Bundling::class.java, Bundling.SHADOWED), + ) + } + } + project.dependencies.add( + OTEL_AGENT_JAR, + project.dependencies.project( + mapOf("path" to ":sentry-opentelemetry:sentry-opentelemetry-agent") + ), + ) + + val testing = project.extensions.getByType(TestingExtension::class.java) + testing.suites.register(SUITE, JvmTestSuite::class.java) { + useJUnit() + targets.all { + testTask.configure { runAgentFixture(autoInit = true, agentFixture.runtimeClasspath) } + } + } + + project.tasks.register(WITHOUT_AUTO_INIT, Test::class.java) { + description = "Runs the OpenTelemetry agent tests with SENTRY_AUTO_INIT=false." + group = LifecycleBasePlugin.VERIFICATION_GROUP + val sources = sourceSets.getByName(SUITE) + testClassesDirs = sources.output.classesDirs + classpath = sources.runtimeClasspath + useJUnit() + runAgentFixture(autoInit = false, agentFixture.runtimeClasspath) + } + } +} + +/** Registers both OpenTelemetry agent test tasks on each Spring Boot version of the matrix. */ +fun SpringBootMatrixExtension.otelAgentTests() { + test(SUITE) { version -> + runAgentFixture(autoInit = true, runtimeClasspath(AGENT_FIXTURE, version)) + } + test(SUITE, name = WITHOUT_AUTO_INIT) { version -> + runAgentFixture(autoInit = false, runtimeClasspath(AGENT_FIXTURE, version)) + } +} + +/** + * Has the tests start the app on [appClasspath] in a child JVM, with the built agent attached. + * [autoInit] decides whether the agent initializes Sentry or, as with `SENTRY_AUTO_INIT=false`, the + * Spring Boot starter. + */ +private fun Test.runAgentFixture(autoInit: Boolean, appClasspath: FileCollection) { + jvmArgumentProviders.add( + project.objects.newInstance(ChildJvmTestArguments::class.java).apply { + agentJar.from(project.configurations.getByName(OTEL_AGENT_JAR)) + this.appClasspath.from(appClasspath) + } + ) + systemProperty("sentry.test.agentAutoInit", autoInit) +} diff --git a/build-logic/src/main/kotlin/io/sentry/gradle/SentryRobolectricPlugin.kt b/build-logic/src/main/kotlin/io/sentry/gradle/SentryRobolectricPlugin.kt new file mode 100644 index 00000000000..a996574f7da --- /dev/null +++ b/build-logic/src/main/kotlin/io/sentry/gradle/SentryRobolectricPlugin.kt @@ -0,0 +1,115 @@ +package io.sentry.gradle + +import com.android.build.api.dsl.LibraryExtension +import java.util.Properties +import org.gradle.api.DefaultTask +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.MapProperty +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.Internal +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import org.gradle.process.CommandLineArgumentProvider +import org.gradle.work.DisableCachingByDefault + +/** + * The android-all jars our Robolectric tests run against, by API level. Robolectric picks the + * version for each level itself (see its DefaultSdkProvider), so a Robolectric upgrade can change + * them, and a test on a level missing here fails with "no artifacts found for + * org.robolectric:android-all-instrumented:...". + */ +private val ANDROID_ALL_VERSIONS = + mapOf( + 21 to "5.0.2_r3-robolectric-r0", + 24 to "7.0.0_r1-robolectric-r1", + 28 to "9-robolectric-4913185-2", + 29 to "10-robolectric-5803371", + 30 to "11-robolectric-6757853", + 31 to "12-robolectric-7732740", + 33 to "13-robolectric-9030017", + 35 to "15-robolectric-12650502", + ) + +/** The instrumentation revision Robolectric appends to every android-all version. */ +private const val ANDROID_ALL_INSTRUMENTATION = "i7" + +/** + * Has Gradle download the android-all jars that Robolectric runs tests against, instead of + * Robolectric fetching them from Maven Central while the tests run. + * + * Gradle caches them with every other dependency, so CI restores them with the Gradle cache, and + * fetches them before any test JVM starts. See + * https://robolectric.org/blog/2023/11/11/improving-android-all-downloading/. Unlike the post, + * which copies the jars into `robolectric.dependency.dir`, the tests read them straight from + * Gradle's cache through a `robolectric-deps.properties` file, so no module keeps a 1 GB copy. + */ +class SentryRobolectricPlugin : Plugin { + override fun apply(project: Project) { + val coordinatesToJar = + ANDROID_ALL_VERSIONS.values.associate { version -> + val coordinates = + "org.robolectric:android-all-instrumented:$version-$ANDROID_ALL_INSTRUMENTATION" + // One configuration per jar, because resolving them together would keep only the highest + // version. + coordinates to + project.configurations.detachedConfiguration(project.dependencies.create(coordinates)) + } + + val writeDeps = + project.tasks.register("writeRobolectricDeps", WriteRobolectricDeps::class.java) { + coordinatesToJar.forEach { (coordinates, jar) -> + jars.put(coordinates, jar.elements.map { it.single().asFile.absolutePath }) + } + propertiesFile.set(project.layout.buildDirectory.file("robolectric/deps.properties")) + } + + project.plugins.withId("com.android.library") { + project.extensions.getByType(LibraryExtension::class.java).testOptions.unitTests.all { test -> + // The properties file holds absolute paths, so it can't be a test input without breaking + // build cache hits across machines. The jars are the input instead. + test.dependsOn(writeDeps) + test.jvmArgumentProviders.add( + project.objects.newInstance(RobolectricDepsArgument::class.java).apply { + androidAllJars.from(coordinatesToJar.values) + propertiesFile.set(writeDeps.flatMap { it.propertiesFile }) + } + ) + } + } + } +} + +/** + * Writes the file Robolectric's PropertiesDependencyResolver reads: each android-all coordinate + * mapped to its jar. + */ +@DisableCachingByDefault(because = "Writing a few lines is cheaper than caching them") +abstract class WriteRobolectricDeps : DefaultTask() { + @get:Input abstract val jars: MapProperty + + @get:OutputFile abstract val propertiesFile: RegularFileProperty + + @TaskAction + fun write() { + val properties = Properties() + properties.putAll(jars.get()) + propertiesFile.get().asFile.outputStream().use { properties.store(it, null) } + } +} + +abstract class RobolectricDepsArgument : CommandLineArgumentProvider { + @get:InputFiles + @get:PathSensitive(PathSensitivity.NONE) + abstract val androidAllJars: ConfigurableFileCollection + + @get:Internal abstract val propertiesFile: RegularFileProperty + + override fun asArguments(): List = + listOf("-Drobolectric-deps.properties=${propertiesFile.get().asFile.absolutePath}") +} diff --git a/build.gradle.kts b/build.gradle.kts index 824afcca706..b4d99e20543 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -39,11 +39,9 @@ allprojects { description = Config.Sentry.description tasks { withType().configureEach { - testLogging.showStandardStreams = true testLogging.exceptionFormat = TestExceptionFormat.FULL testLogging.events = setOf( TestLogEvent.SKIPPED, - TestLogEvent.PASSED, TestLogEvent.FAILED ) } diff --git a/gradle.properties b/gradle.properties index 417334e771c..ea37b9864f6 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,7 +18,7 @@ android.newDsl=false android.disableAgpUpgradePrompt=true # Release information -versionName=8.63.0 +versionName=8.64.0 # Override the SDK name on native crashes on Android sentryAndroidSdkName=sentry.native.android diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 1fd2d0f7581..7b3a04b0ea0 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -9,18 +9,19 @@ androidxCompose = "1.9.5" asyncProfiler = "4.4" camerax = "1.4.0" composeCompiler = "1.5.14" -coroutines = "1.6.1" +coroutines = "1.11.0" +dgs = "4.9.2" detekt = "1.23.8" dokka = "2.0.0" espresso = "3.7.0" -feign = "11.6" +feign = "13.17" gummyBears = "0.16.0" jackson = "2.18.3" jetbrainsCompose = "1.6.11" kotlin = "2.3.21" kotlin-compatible-version = "1.9" -ksp = "2.3.13" -ktorClient = "3.0.0" +ksp = "2.3.14" +ktorClient = "3.6.1" logback = "1.2.9" log4j2 = "2.26.1" nopen = "1.0.1" @@ -28,26 +29,26 @@ nopen = "1.0.1" # see https://developer.android.com/jetpack/androidx/releases/compose-kotlin okhttp = "5.5.1" openfeature = "1.18.2" -otel = "1.63.0" -otelAlpha = "1.63.0-alpha" -otelInstrumentation = "2.29.0" -otelInstrumentationAlpha = "2.29.0-alpha" +otel = "1.67.0" +otelAlpha = "1.67.0-alpha" +otelInstrumentation = "2.33.1" +otelInstrumentationAlpha = "2.33.1-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.42.0" -otelSemanticConventionsAlpha = "1.42.0-alpha" -retrofit = "2.9.0" -room2 = "2.8.4" -room3 = "3.0.0-rc01" +otelSemanticConventions = "1.44.0" +otelSemanticConventionsAlpha = "1.44.0-alpha" +retrofit = "3.0.0" +room2 = "2.8.5" +room3 = "3.0.3" sagp = "6.13.0" # The AGP matrix job overrides this with the VERSION_AGP env var, through each build's settings. -agp = "9.4.0" +agp = "9.5.1" # 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.4.14" +r8 = "9.5.29" sqlite = "2.6.2" -sqliteRc = "2.8.0-alpha03" # Required by Room3 3.0.0-rc* +sqliteDrivers = "2.7.1" slf4j = "1.7.30" -spotless = "8.8.0" +spotless = "8.11.0" springboot2 = "2.7.18" springboot3 = "3.5.0" springboot4 = "4.1.0" @@ -74,7 +75,7 @@ buildconfig = { id = "com.github.gmazzo.buildconfig", version = "5.6.5" } dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } dokka-javadoc = { id = "org.jetbrains.dokka-javadoc", version.ref = "dokka" } errorprone = { id = "net.ltgt.errorprone", version = "5.1.1" } -gradle-versions = { id = "com.github.ben-manes.versions", version = "0.42.0" } +gradle-versions = { id = "com.github.ben-manes.versions", version = "0.67.0" } spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" } vanniktech-maven-publish = { id = "com.vanniktech.maven.publish", version.ref = "vanniktechMavenPublish" } @@ -98,7 +99,7 @@ apollo4-kotlin = { module = "com.apollographql.apollo:apollo-runtime", version = apollo5-kotlin = { module = "com.apollographql.apollo:apollo-runtime", version = "5.0.0" } apollo5-kotlin-latest = { module = "com.apollographql.apollo:apollo-runtime", version = "5.1.0" } androidx-appcompat = { module = "androidx.appcompat:appcompat", version = "1.7.1" } -androidx-annotation = { module = "androidx.annotation:annotation", version = "1.9.1" } +androidx-annotation = { module = "androidx.annotation:annotation", version = "1.11.0" } androidx-activity = { module = "androidx.activity:activity", version = "1.8.2" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version = "1.9.3" } androidx-compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "androidxCompose" } @@ -128,9 +129,10 @@ androidx-room-ktx = { module = "androidx.room:room-ktx", version.ref = "room2" } androidx-room-runtime = { module = "androidx.room:room-runtime", version.ref = "room2" } androidx-room3-compiler = { module = "androidx.room3:room3-compiler", version.ref = "room3" } androidx-room3-runtime = { module = "androidx.room3:room3-runtime", version.ref = "room3" } +androidx-webkit = { module = "androidx.webkit:webkit", version = "1.14.0" } androidx-sqlite = { module = "androidx.sqlite:sqlite", version.ref = "sqlite" } -androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqliteRc" } -androidx-sqlite-framework = { module = "androidx.sqlite:sqlite-framework", version.ref = "sqliteRc" } +androidx-sqlite-bundled = { module = "androidx.sqlite:sqlite-bundled", version.ref = "sqliteDrivers" } +androidx-sqlite-framework = { module = "androidx.sqlite:sqlite-framework", version.ref = "sqliteDrivers" } androidx-recyclerview = { module = "androidx.recyclerview:recyclerview", version = "1.4.0" } androidx-browser = { module = "androidx.browser:browser", version = "1.10.0" } aspectjweaver = { module = "org.aspectj:aspectjweaver" } @@ -148,6 +150,8 @@ feign-gson = { module = "io.github.openfeign:feign-gson", version.ref = "feign" graphql-java17 = { module = "com.graphql-java:graphql-java", version = "17.3" } graphql-java22 = { module = "com.graphql-java:graphql-java", version = "22.1" } graphql-java24 = { module = "com.graphql-java:graphql-java", version = "24.0" } +netflix-dgs-platform = { module = "com.netflix.graphql.dgs:graphql-dgs-platform-dependencies", version.ref = "dgs" } +netflix-dgs-subscriptions-websockets-autoconfigure = { module = "com.netflix.graphql.dgs:graphql-dgs-subscriptions-websockets-autoconfigure", version.ref = "dgs" } jackson-bom = { module = "com.fasterxml.jackson:jackson-bom", version.ref = "jackson" } jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" } jetbrains-annotations = { module = "org.jetbrains:annotations", version = "23.0.0" } @@ -196,11 +200,13 @@ 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" } 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" } slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } slf4j-jdk14 = { module = "org.slf4j:slf4j-jdk14", version.ref = "slf4j" } -slf4j2-api = { module = "org.slf4j:slf4j-api", version = "2.0.5" } +slf4j2-api = { module = "org.slf4j:slf4j-api", version = "2.0.20" } spotlessLib = { module = "com.diffplug.spotless:com.diffplug.spotless.gradle.plugin", version.ref = "spotless"} detektLib = { module = "io.gitlab.arturbosch.detekt:io.gitlab.arturbosch.detekt.gradle.plugin", version.ref = "detekt" } vanniktechMavenPublishLib = { module = "com.vanniktech.maven.publish:com.vanniktech.maven.publish.gradle.plugin", version.ref = "vanniktechMavenPublish" } @@ -264,7 +270,7 @@ gummy-bears-api21 = { module = "com.toasttab.android:gummy-bears-api-21", versio # tomcat libraries tomcat-catalina = { module = "org.apache.tomcat:tomcat-catalina", version = "9.0.108" } tomcat-embed-jasper = { module = "org.apache.tomcat.embed:tomcat-embed-jasper", version = "9.0.108" } -tomcat-catalina-jakarta = { module = "org.apache.tomcat:tomcat-catalina", version = "11.0.22" } +tomcat-catalina-jakarta = { module = "org.apache.tomcat:tomcat-catalina", version = "11.0.27" } tomcat-embed-jasper-jakarta = { module = "org.apache.tomcat.embed:tomcat-embed-jasper", version = "11.0.22" } # The version comes from the Spring Boot BOM of whichever Spring line uses it. tomcat-embed-core = { module = "org.apache.tomcat.embed:tomcat-embed-core" } @@ -291,7 +297,7 @@ camerax-lifecycle = { module = "androidx.camera:camera-lifecycle", version.ref = camerax-view = { module = "androidx.camera:camera-view", version.ref = "camerax" } google-truth = { module = "com.google.truth:truth", version = "1.4.5" } -hsqldb = { module = "org.hsqldb:hsqldb", version = "2.6.1" } +hsqldb = { module = "org.hsqldb:hsqldb", version = "2.7.4" } javafaker = { module = "com.github.javafaker:javafaker", version = "1.0.2" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } leakcanary-instrumentation = { module = "com.squareup.leakcanary:leakcanary-android-instrumentation", version = "2.14" } @@ -305,6 +311,8 @@ okhttp-mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version. okhttp-mockwebserver4 = { module = "com.squareup.okhttp3:mockwebserver", version = "4.9.2" } okhttp-tls = { module = "com.squareup.okhttp3:okhttp-tls", version.ref = "okhttp" } okio = { module = "com.squareup.okio:okio", version = "1.13.0" } +rhino = { module = "org.mozilla:rhino", version = "1.8.0" } +# Upgrading Robolectric can change the android-all jars it needs, see SentryRobolectricPlugin. roboelectric = { module = "org.robolectric:robolectric", version = "4.15" } [bundles] diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 9fa7f288283..51cbd2a6f81 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 91c4fc64aa0..04d7959523b 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.8.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-bin.zip networkTimeout=10000 retries=0 retryBackOffMs=500 diff --git a/scripts/update-sentry-native-ndk.sh b/scripts/update-sentry-native-ndk.sh index 0aef9ebb257..fa5aa12a636 100755 --- a/scripts/update-sentry-native-ndk.sh +++ b/scripts/update-sentry-native-ndk.sh @@ -16,7 +16,7 @@ set-version) echo "Setting sentry-native-ndk version to '$version'" - PATTERN='(module = "io\.sentry:sentry-native-ndk", version = ")[0-9.]+(")' + PATTERN='(module = "io\.sentry:sentry-native-ndk(?:-outproc)?", version = ")[0-9.]+(")' perl -pi -e "s/$PATTERN/\${1}$version\${2}/" "$GRADLE_NDK_FILEPATH" ;; *) diff --git a/sentry-android-core/api/sentry-android-core.api b/sentry-android-core/api/sentry-android-core.api index 021528ce9e8..49f3634bad8 100644 --- a/sentry-android-core/api/sentry-android-core.api +++ b/sentry-android-core/api/sentry-android-core.api @@ -30,7 +30,7 @@ public final class io/sentry/android/core/ActivityLifecycleIntegration : android public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V } -public class io/sentry/android/core/AndroidContinuousProfiler : io/sentry/IContinuousProfiler, io/sentry/transport/RateLimiter$IRateLimitObserver { +public final class io/sentry/android/core/AndroidContinuousProfiler : io/sentry/IContinuousProfiler, io/sentry/transport/RateLimiter$IRateLimitObserver { public fun (Lio/sentry/android/core/BuildInfoProvider;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/ILogger;Ljava/lang/String;ILio/sentry/util/LazyEvaluator$Evaluator;)V public fun close (Z)V public fun getChunkId ()Lio/sentry/protocol/SentryId; @@ -90,7 +90,7 @@ public final class io/sentry/android/core/AndroidLoggerBatchProcessorFactory : i public fun create (Lio/sentry/SentryOptions;Lio/sentry/SentryClient;)Lio/sentry/logger/ILoggerBatchProcessor; } -public class io/sentry/android/core/AndroidMemoryCollector : io/sentry/IPerformanceSnapshotCollector { +public final class io/sentry/android/core/AndroidMemoryCollector : io/sentry/IPerformanceSnapshotCollector { public fun ()V public fun collect (Lio/sentry/PerformanceCollectionData;)V public fun setup ()V @@ -108,15 +108,14 @@ public final class io/sentry/android/core/AndroidMetricsBatchProcessorFactory : public fun create (Lio/sentry/SentryOptions;Lio/sentry/SentryClient;)Lio/sentry/metrics/IMetricsBatchProcessor; } -public class io/sentry/android/core/AndroidProfiler { - protected final field lock Lio/sentry/util/AutoClosableReentrantLock; +public final class io/sentry/android/core/AndroidProfiler { public fun (Ljava/lang/String;ILio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/util/LazyEvaluator$Evaluator;Lio/sentry/ILogger;)V public fun close ()V public fun endAndCollect (ZLjava/util/List;)Lio/sentry/android/core/AndroidProfiler$ProfileEndData; public fun start ()Lio/sentry/android/core/AndroidProfiler$ProfileStartData; } -public class io/sentry/android/core/AndroidProfiler$ProfileEndData { +public final class io/sentry/android/core/AndroidProfiler$ProfileEndData { public final field didTimeout Z public final field endCpuMillis J public final field endNanos J @@ -125,7 +124,7 @@ public class io/sentry/android/core/AndroidProfiler$ProfileEndData { public fun (JJZLjava/io/File;Ljava/util/Map;)V } -public class io/sentry/android/core/AndroidProfiler$ProfileStartData { +public final class io/sentry/android/core/AndroidProfiler$ProfileStartData { public final field startCpuMillis J public final field startNanos J public final field startTimestamp Ljava/util/Date; @@ -149,7 +148,7 @@ public final class io/sentry/android/core/AnrIntegrationFactory { public static fun create (Landroid/content/Context;Lio/sentry/android/core/BuildInfoProvider;)Lio/sentry/Integration; } -public class io/sentry/android/core/AnrV2Integration : io/sentry/Integration, java/io/Closeable { +public final class io/sentry/android/core/AnrV2Integration : io/sentry/Integration, java/io/Closeable { public fun (Landroid/content/Context;)V public fun close ()V public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V @@ -260,7 +259,7 @@ public final class io/sentry/android/core/ContextUtils { public static fun isForegroundImportance ()Z } -public class io/sentry/android/core/CurrentActivityHolder { +public final class io/sentry/android/core/CurrentActivityHolder { public fun clearActivity ()V public fun clearActivity (Landroid/app/Activity;)V public fun getActivity ()Landroid/app/Activity; @@ -360,6 +359,7 @@ public final class io/sentry/android/core/NdkHandlerStrategy : java/lang/Enum { public final class io/sentry/android/core/NdkIntegration : io/sentry/Integration, java/io/Closeable { public static final field SENTRY_NDK_CLASS_NAME Ljava/lang/String; + public static final field SENTRY_NDK_OUTPROC_CLASS_NAME Ljava/lang/String; public fun (Ljava/lang/Class;)V public fun close ()V public final fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V @@ -371,7 +371,7 @@ public final class io/sentry/android/core/NetworkBreadcrumbsIntegration : io/sen public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V } -public class io/sentry/android/core/PerfettoContinuousProfiler : io/sentry/IContinuousProfiler, io/sentry/transport/RateLimiter$IRateLimitObserver { +public final class io/sentry/android/core/PerfettoContinuousProfiler : io/sentry/IContinuousProfiler, io/sentry/transport/RateLimiter$IRateLimitObserver { public fun (Lio/sentry/ILogger;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;Lio/sentry/util/LazyEvaluator$Evaluator;Ljava/util/function/Supplier;)V public fun close (Z)V public fun getChunkId ()Lio/sentry/protocol/SentryId; @@ -384,7 +384,7 @@ public class io/sentry/android/core/PerfettoContinuousProfiler : io/sentry/ICont public fun stopProfiler (Lio/sentry/ProfileLifecycle;)V } -public class io/sentry/android/core/PerfettoProfiler { +public final class io/sentry/android/core/PerfettoProfiler { public fun (Landroid/content/Context;Lio/sentry/ILogger;Lio/sentry/ISentryExecutorService;)V public fun endAndCollect (Ljava/util/function/Consumer;)V } @@ -426,6 +426,7 @@ public final class io/sentry/android/core/SentryAndroidOptions : io/sentry/Sentr public fun getStartupCrashDurationThresholdMillis ()J public fun getTimberLogCaptureEnabled ()Z public fun getTombstoneMergeTimeThresholdMillis ()J + public fun getWebViewTracing ()Lio/sentry/android/core/SentryWebViewTracingOptions; public fun isAnrEnabled ()Z public fun isAnrProfilingEnabled ()Z public fun isAnrReportInDebug ()Z @@ -562,17 +563,14 @@ public abstract interface class io/sentry/android/core/SentryShakeDetector$Liste public abstract fun onShake ()V } -public class io/sentry/android/core/SentryUserFeedbackForm : android/app/Dialog { - protected fun onCreate (Landroid/os/Bundle;)V +public final class io/sentry/android/core/SentryUserFeedbackForm : android/app/Dialog { public fun onDetachedFromWindow ()V - protected fun onStart ()V - protected fun onStop ()V public fun setCancelable (Z)V public fun setOnDismissListener (Landroid/content/DialogInterface$OnDismissListener;)V public fun show ()V } -public class io/sentry/android/core/SentryUserFeedbackForm$Builder { +public final class io/sentry/android/core/SentryUserFeedbackForm$Builder { public fun (Landroid/content/Context;)V public fun (Landroid/content/Context;I)V public fun (Landroid/content/Context;ILio/sentry/android/core/SentryUserFeedbackForm$OptionsConfiguration;)V @@ -586,8 +584,19 @@ public abstract interface class io/sentry/android/core/SentryUserFeedbackForm$Op public abstract fun configure (Landroid/content/Context;Lio/sentry/SentryFeedbackOptions;)V } -public class io/sentry/android/core/SpanFrameMetricsCollector : io/sentry/IPerformanceContinuousCollector, io/sentry/android/core/internal/util/SentryFrameMetricsCollector$FrameMetricsCollectorListener { - protected final field lock Lio/sentry/util/AutoClosableReentrantLock; +public final class io/sentry/android/core/SentryWebViewTracing { + public static fun addTracePropagation (Landroid/webkit/WebView;)Z + public static fun addTracePropagation (Landroid/webkit/WebView;Ljava/util/List;)Z + public static fun addTracePropagation (Landroid/webkit/WebView;[Ljava/lang/String;)Z +} + +public final class io/sentry/android/core/SentryWebViewTracingOptions { + public fun ()V + public fun getAllowedHosts ()Ljava/util/List; + public fun setAllowedHosts (Ljava/util/List;)V +} + +public final class io/sentry/android/core/SpanFrameMetricsCollector : io/sentry/IPerformanceContinuousCollector, io/sentry/android/core/internal/util/SentryFrameMetricsCollector$FrameMetricsCollectorListener { public fun (Lio/sentry/android/core/SentryAndroidOptions;Lio/sentry/android/core/internal/util/SentryFrameMetricsCollector;)V public fun clear ()V public fun onFrameMetricCollected (JJJJZZF)V @@ -606,7 +615,7 @@ public final class io/sentry/android/core/SystemEventsBreadcrumbsIntegration : i public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V } -public class io/sentry/android/core/TombstoneIntegration : io/sentry/Integration, java/io/Closeable { +public final class io/sentry/android/core/TombstoneIntegration : io/sentry/Integration, java/io/Closeable { public fun (Landroid/content/Context;)V public fun close ()V public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V @@ -620,13 +629,14 @@ public final class io/sentry/android/core/TombstoneIntegration$TombstoneHint : i public fun timestamp ()Ljava/lang/Long; } -public class io/sentry/android/core/TombstoneIntegration$TombstonePolicy : io/sentry/android/core/ApplicationExitInfoHistoryDispatcher$ApplicationExitInfoPolicy { +public final class io/sentry/android/core/TombstoneIntegration$TombstonePolicy : io/sentry/android/core/ApplicationExitInfoHistoryDispatcher$ApplicationExitInfoPolicy { public fun (Lio/sentry/android/core/SentryAndroidOptions;Landroid/content/Context;)V public fun buildReport (Landroid/app/ApplicationExitInfo;Z)Lio/sentry/android/core/ApplicationExitInfoHistoryDispatcher$Report; public fun getLabel ()Ljava/lang/String; public fun getLastReportedTimestamp ()Ljava/lang/Long; public fun markReported (J)V public fun matches (Landroid/app/ApplicationExitInfo;)Z + public static fun mergeNativeCrashes (Lio/sentry/SentryEvent;Lio/sentry/SentryEvent;)V public fun shouldReportHistorical ()Z } @@ -655,26 +665,26 @@ public final class io/sentry/android/core/ViewHierarchyEventProcessor : io/sentr public static fun snapshotViewHierarchyAsData (Landroid/app/Activity;Lio/sentry/util/thread/IThreadChecker;Lio/sentry/ISerializer;Lio/sentry/ILogger;)[B } -public class io/sentry/android/core/anr/AggregatedStackTrace { +public final class io/sentry/android/core/anr/AggregatedStackTrace { public fun ([Ljava/lang/StackTraceElement;IIJF)V public fun addOccurrence (J)V public fun getStack ()[Ljava/lang/StackTraceElement; } -public class io/sentry/android/core/anr/AnrCulpritIdentifier { +public final class io/sentry/android/core/anr/AnrCulpritIdentifier { public fun ()V public static fun identify (Ljava/util/List;)Lio/sentry/android/core/anr/AggregatedStackTrace; public static fun isSystemFrame (Ljava/lang/String;)Z } -public class io/sentry/android/core/anr/AnrProfile { +public final class io/sentry/android/core/anr/AnrProfile { public final field endTimeMs J public final field stacks Ljava/util/List; public final field startTimeMs J public fun (Ljava/util/List;)V } -public class io/sentry/android/core/anr/AnrProfileManager : java/lang/AutoCloseable { +public final class io/sentry/android/core/anr/AnrProfileManager : java/lang/AutoCloseable { public fun (Lio/sentry/SentryOptions;)V public fun (Lio/sentry/SentryOptions;Ljava/io/File;)V public fun add (Lio/sentry/android/core/anr/AnrStackTrace;)V @@ -683,7 +693,7 @@ public class io/sentry/android/core/anr/AnrProfileManager : java/lang/AutoClosea public fun load ()Lio/sentry/android/core/anr/AnrProfile; } -public class io/sentry/android/core/anr/AnrProfileRotationHelper { +public final class io/sentry/android/core/anr/AnrProfileRotationHelper { public fun ()V public static fun deleteLastFile (Ljava/io/File;)Z public static fun getFileForRecording (Ljava/io/File;)Ljava/io/File; @@ -691,32 +701,23 @@ public class io/sentry/android/core/anr/AnrProfileRotationHelper { public static fun rotate ()V } -public class io/sentry/android/core/anr/AnrProfilingIntegration : io/sentry/Integration, io/sentry/android/core/AppState$AppStateListener, java/io/Closeable, java/lang/Runnable { +public final class io/sentry/android/core/anr/AnrProfilingIntegration : io/sentry/Integration, io/sentry/android/core/AppState$AppStateListener, java/io/Closeable, java/lang/Runnable { public static final field POLLING_INTERVAL_MS J public static final field THRESHOLD_ANR_MS J public fun ()V - protected fun checkMainThread (Ljava/lang/Thread;)V public fun close ()V - protected fun getProfileManager ()Lio/sentry/android/core/anr/AnrProfileManager; - protected fun getState ()Lio/sentry/android/core/anr/AnrProfilingIntegration$MainThreadState; public fun onBackground ()V public fun onForeground ()V public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V public fun run ()V } -protected final class io/sentry/android/core/anr/AnrProfilingIntegration$MainThreadState : java/lang/Enum { - public static final field ANR_DETECTED Lio/sentry/android/core/anr/AnrProfilingIntegration$MainThreadState; - public static final field IDLE Lio/sentry/android/core/anr/AnrProfilingIntegration$MainThreadState; - public static final field SUSPICIOUS Lio/sentry/android/core/anr/AnrProfilingIntegration$MainThreadState; - public static fun valueOf (Ljava/lang/String;)Lio/sentry/android/core/anr/AnrProfilingIntegration$MainThreadState; - public static fun values ()[Lio/sentry/android/core/anr/AnrProfilingIntegration$MainThreadState; -} - public final class io/sentry/android/core/anr/AnrStackTrace : java/lang/Comparable { public final field stack [Ljava/lang/StackTraceElement; + public final field state Ljava/lang/Thread$State; public final field timestampMs J public fun (J[Ljava/lang/StackTraceElement;)V + public fun (J[Ljava/lang/StackTraceElement;Ljava/lang/Thread$State;)V public fun compareTo (Lio/sentry/android/core/anr/AnrStackTrace;)I public synthetic fun compareTo (Ljava/lang/Object;)I public static fun deserialize (Ljava/io/DataInputStream;)Lio/sentry/android/core/anr/AnrStackTrace; @@ -747,7 +748,7 @@ public final class io/sentry/android/core/cache/AndroidEnvelopeCache : io/sentry public fun storeEnvelope (Lio/sentry/SentryEnvelope;Lio/sentry/Hint;)Z } -public class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter : android/app/Application$ActivityLifecycleCallbacks { +public abstract class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter : android/app/Application$ActivityLifecycleCallbacks { public fun ()V public fun onActivityCreated (Landroid/app/Activity;Landroid/os/Bundle;)V public fun onActivityDestroyed (Landroid/app/Activity;)V @@ -758,7 +759,7 @@ public class io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapte public fun onActivityStopped (Landroid/app/Activity;)V } -public class io/sentry/android/core/performance/ActivityLifecycleSpanHelper { +public final class io/sentry/android/core/performance/ActivityLifecycleSpanHelper { public fun (Ljava/lang/String;)V public fun clear ()V public fun createAndStopOnCreateSpan (Lio/sentry/ISpan;)V @@ -772,7 +773,7 @@ public class io/sentry/android/core/performance/ActivityLifecycleSpanHelper { public fun setOnStartStartTimestamp (Lio/sentry/SentryDate;)V } -public class io/sentry/android/core/performance/ActivityLifecycleTimeSpan : java/lang/Comparable { +public final class io/sentry/android/core/performance/ActivityLifecycleTimeSpan : java/lang/Comparable { public fun ()V public fun compareTo (Lio/sentry/android/core/performance/ActivityLifecycleTimeSpan;)I public synthetic fun compareTo (Ljava/lang/Object;)I @@ -780,7 +781,7 @@ public class io/sentry/android/core/performance/ActivityLifecycleTimeSpan : java public final fun getOnStart ()Lio/sentry/android/core/performance/TimeSpan; } -public class io/sentry/android/core/performance/AppStartMetrics : io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter { +public final class io/sentry/android/core/performance/AppStartMetrics : io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter { public static final field staticLock Lio/sentry/util/AutoClosableReentrantLock; public fun ()V public fun addActivityLifecycleTimeSpans (Lio/sentry/android/core/performance/ActivityLifecycleTimeSpan;)V @@ -847,7 +848,7 @@ public abstract interface class io/sentry/android/core/performance/AppStartMetri public abstract fun onHeadlessAppStart ()V } -public class io/sentry/android/core/performance/TimeSpan : java/lang/Comparable { +public final class io/sentry/android/core/performance/TimeSpan : java/lang/Comparable { public fun ()V public fun compareTo (Lio/sentry/android/core/performance/TimeSpan;)I public synthetic fun compareTo (Ljava/lang/Object;)I @@ -873,7 +874,7 @@ public class io/sentry/android/core/performance/TimeSpan : java/lang/Comparable public fun stop ()V } -public class io/sentry/android/core/performance/WindowContentChangedCallback : io/sentry/android/core/internal/gestures/WindowCallbackAdapter { +public final class io/sentry/android/core/performance/WindowContentChangedCallback : io/sentry/android/core/internal/gestures/WindowCallbackAdapter { public fun (Landroid/view/Window$Callback;Ljava/lang/Runnable;)V public fun onContentChanged ()V } diff --git a/sentry-android-core/build.gradle.kts b/sentry-android-core/build.gradle.kts index 64e9a7ac09c..22613df021f 100644 --- a/sentry-android-core/build.gradle.kts +++ b/sentry-android-core/build.gradle.kts @@ -12,6 +12,7 @@ plugins { id("io.sentry.jdk-target") id("io.sentry.publish") id("io.sentry.api-validation") + id("io.sentry.robolectric") } android { @@ -74,10 +75,19 @@ android { } } -tasks.withType().configureEach { - options.errorprone { - check("NullAway", net.ltgt.gradle.errorprone.CheckSeverity.ERROR) - option("NullAway:AnnotatedPackages", "io.sentry") +// net.ltgt.errorprone only configures Gradle's JVM source sets, not Android variants, so put Error +// Prone on each variant's processor path and enable it ourselves. +androidComponents.onVariants { variant -> + variant.annotationProcessorConfiguration.extendsFrom(configurations.errorprone.get()) + variant.configureJavaCompileTask { task -> + // Tells Error Prone this is Android code, so it skips checks that don't apply there, such as + // DefaultCharset (Android's default charset is always UTF-8), and runs its Android checks. + task.options.compilerArgs.add("-XDandroidCompatible=true") + task.options.errorprone { + enabled = true + check("NullAway", net.ltgt.gradle.errorprone.CheckSeverity.ERROR) + option("NullAway:AnnotatedPackages", "io.sentry") + } } } @@ -104,6 +114,8 @@ dependencies { implementation(libs.androidx.core) // photo picker for user feedback screenshot attachments compileOnly(libs.androidx.activity) + // document-start script injection for WebView trace propagation + compileOnly(libs.androidx.webkit) implementation(libs.epitaph) @@ -133,6 +145,8 @@ dependencies { testImplementation(projects.sentryAndroidNdk) testImplementation(libs.androidx.activity.compose) + testImplementation(libs.androidx.webkit) + testImplementation(libs.rhino) testImplementation(libs.androidx.compose.ui) testImplementation(libs.androidx.compose.foundation) testImplementation(libs.androidx.compose.foundation.layout) diff --git a/sentry-android-core/proguard-rules.pro b/sentry-android-core/proguard-rules.pro index 73c5cf68360..150a214a2ec 100644 --- a/sentry-android-core/proguard-rules.pro +++ b/sentry-android-core/proguard-rules.pro @@ -29,6 +29,12 @@ -dontwarn androidx.activity.ComponentActivity -dontwarn androidx.activity.result.** +# androidx.webkit is a compileOnly dependency, used by WebView trace propagation +# its presence is checked at runtime before use +-dontwarn androidx.webkit.** +# keep the name of the class the presence check looks up, so it still finds it in minified apps +-keepnames class androidx.webkit.ScriptHandler + # To ensure that stack traces is unambiguous # https://developer.android.com/studio/build/shrink-code#decode-stack-trace -keepattributes LineNumberTable,SourceFile diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java b/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java index 6f8fedcecea..c109855daa7 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ANRWatchDog.java @@ -49,7 +49,6 @@ final class ANRWatchDog extends Thread { private final boolean reportInDebug; private final ANRListener anrListener; private final MainLooperHandler uiHandler; - private final MonotonicTicker monotonicTicker; /** the interval in which we check if there's an ANR, in ms */ private long pollingIntervalMs; @@ -65,7 +64,6 @@ final class ANRWatchDog extends Thread { private final @NotNull Context context; private final @Nullable IDebugManager debugManager; - @SuppressWarnings("UnnecessaryLambda") private final Runnable ticker; static @NotNull ANRWatchDog create( @@ -97,7 +95,6 @@ final class ANRWatchDog extends Thread { super("|ANR-WatchDog|"); - this.monotonicTicker = monotonicTicker; this.timeoutIntervalMillis = timeoutIntervalMillis; this.pollingIntervalMs = pollingIntervalMillis; this.reportInDebug = reportInDebug; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ActivityLifecycleIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/ActivityLifecycleIntegration.java index 4ab9be82248..de8a0e6bbfa 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ActivityLifecycleIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ActivityLifecycleIntegration.java @@ -176,7 +176,7 @@ private void stopPreviousTransactions() { } private void startTracing(final @NotNull Activity activity) { - if (scopes != null && !isRunningTransactionOrTrace(activity)) { + if (scopes != null && options != null && !isRunningTransactionOrTrace(activity)) { if (!performanceEnabled) { activitiesWithOngoingTransactions.put(activity, NoOpTransaction.getInstance()); if (options.isEnableAutoTraceIdGeneration()) { @@ -282,7 +282,7 @@ private void startTracing(final @NotNull Activity activity) { // Continue either the foreground app.start above or an earlier headless app.start. final @Nullable String continueSentryTrace; final @Nullable String continueBaggage; - if (createStandaloneAppStart) { + if (createStandaloneAppStart && appStartTransaction != null) { continueSentryTrace = appStartTransaction.toSentryTrace().getValue(); final @Nullable BaggageHeader baggageHeader = appStartTransaction.toBaggageHeader(null); continueBaggage = baggageHeader == null ? null : baggageHeader.getValue(); @@ -332,7 +332,7 @@ private void startTracing(final @NotNull Activity activity) { final SpanOptions spanOptions = new SpanOptions(); setSpanOrigin(spanOptions); - if (isAppStart) { + if (isAppStart && coldStart != null) { if (!createStandaloneAppStart && !options.isEnableStandaloneAppStartTracing()) { appStartSpan = transaction.startChild( @@ -370,10 +370,9 @@ private void startTracing(final @NotNull Activity activity) { } // lets bind to the scope so other integrations can pick it up - scopes.configureScope( - scope -> { - applyScope(scope, transaction); - }); + scopes.configureScope(scope -> { + applyScope(scope, transaction); + }); activitiesWithOngoingTransactions.put(activity, transaction); } @@ -441,31 +440,30 @@ private boolean isWithinAppStartContinuationWindow(final @NotNull SentryDate uiL @VisibleForTesting void applyScope(final @NotNull IScope scope, final @NotNull ITransaction transaction) { - scope.withTransaction( - scopeTransaction -> { - // we'd not like to overwrite existent transactions bound to the Scope - // manually. - if (scopeTransaction == null) { - scope.setTransaction(transaction); - } else if (options != null) { - options - .getLogger() - .log( - SentryLevel.DEBUG, - "Transaction '%s' won't be bound to the Scope since there's one already in there.", - transaction.getName()); - } - }); + scope.withTransaction(scopeTransaction -> { + // we'd not like to overwrite existent transactions bound to the Scope + // manually. + if (scopeTransaction == null) { + scope.setTransaction(transaction); + } else if (options != null) { + options + .getLogger() + .log( + SentryLevel.DEBUG, + "Transaction '%s' won't be bound to the Scope since there's one already in there.", + transaction.getName()); + } + }); } @VisibleForTesting + @SuppressWarnings("ReferenceEquality") void clearScope(final @NotNull IScope scope, final @NotNull ITransaction transaction) { - scope.withTransaction( - scopeTransaction -> { - if (scopeTransaction == transaction) { - scope.clearTransaction(); - } - }); + scope.withTransaction(scopeTransaction -> { + if (scopeTransaction == transaction) { + scope.clearTransaction(); + } + }); } private boolean isRunningTransactionOrTrace(final @NotNull Activity activity) { @@ -504,10 +502,9 @@ private void finishTransaction( if (scopes != null) { // make sure to remove the transaction from scope, as it may contain running children, // therefore `finish` method will not remove it from scope - scopes.configureScope( - scope -> { - clearScope(scope, transaction); - }); + scopes.configureScope(scope -> { + clearScope(scope, transaction); + }); } } } @@ -925,13 +922,16 @@ private void finishAppStartSpan() { } private void finishAppStartSpan(final @Nullable SentryDate endDate) { + if (!performanceEnabled || options == null) { + return; + } final @Nullable SentryDate appStartEndTime = endDate != null ? endDate : AppStartMetrics.getInstance() .getAppStartTimeSpanWithFallback() .getProjectedStopTimestamp(); - if (performanceEnabled && appStartEndTime != null) { + if (appStartEndTime != null) { finishSpan(appStartSpan, appStartEndTime); if (appStartTransaction != null && !appStartTransaction.isFinished()) { appStartTransaction.finish(SpanStatus.OK, appStartEndTime); @@ -980,7 +980,7 @@ private void onHeadlessAppStart() { } final @NotNull ITransaction transaction = - createStandaloneAppStartTransaction(startTime, null, false); + createStandaloneAppStartTransaction(scopes, options, startTime, null, false); transaction.finish(SpanStatus.OK, endTime); } @@ -991,6 +991,8 @@ private void onHeadlessAppStart() { * for its children and gets a deadline so it stays open until the extended span finishes. */ private @NotNull ITransaction createStandaloneAppStartTransaction( + final @NotNull IScopes scopes, + final @NotNull SentryAndroidOptions options, final @NotNull SentryDate startTime, final @Nullable TracesSamplingDecision samplingDecision, final boolean holdOpenForExtension) { @@ -1008,10 +1010,8 @@ private void onHeadlessAppStart() { // Persist the end time (covering every finish path: user finish, first frame, deadline) so a // later ui.load can tell whether it is close enough to continue this trace; without it the // continuation window is unbounded. - txnOptions.setTransactionFinishedCallback( - finishedTransaction -> - AppStartMetrics.getInstance() - .setAppStartEndTime(finishedTransaction.getFinishDate())); + txnOptions.setTransactionFinishedCallback(finishedTransaction -> + AppStartMetrics.getInstance().setAppStartEndTime(finishedTransaction.getFinishDate())); } final @NotNull TransactionContext txnContext = @@ -1069,7 +1069,7 @@ private void onHeadlessAppStart() { metrics.setAppStartSamplingDecision(null); final @NotNull ITransaction transaction = - createStandaloneAppStartTransaction(startTime, samplingDecision, true); + createStandaloneAppStartTransaction(scopes, options, startTime, samplingDecision, true); final SpanOptions spanOptions = new SpanOptions(); setSpanOrigin(spanOptions); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java index 23a72b131fc..1793bffde09 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidContinuousProfiler.java @@ -44,7 +44,7 @@ * implementation using {@code ProfilingManager}, available on API 35+. */ @ApiStatus.Internal -public class AndroidContinuousProfiler +public final class AndroidContinuousProfiler implements IContinuousProfiler, RateLimiter.IRateLimitObserver { private static final long MAX_CHUNK_DURATION_MILLIS = 60000; @@ -52,7 +52,6 @@ public class AndroidContinuousProfiler private final @Nullable String profilingTracesDirPath; private final int profilingTracesHz; private final @NotNull LazyEvaluator.Evaluator executorServiceSupplier; - private final @NotNull BuildInfoProvider buildInfoProvider; private boolean isInitialized = false; private final @NotNull SentryFrameMetricsCollector frameMetricsCollector; private @Nullable AndroidProfiler profiler = null; @@ -82,7 +81,6 @@ public AndroidContinuousProfiler( final @NotNull LazyEvaluator.Evaluator executorServiceSupplier) { this.logger = logger; this.frameMetricsCollector = frameMetricsCollector; - this.buildInfoProvider = buildInfoProvider; this.profilingTracesDirPath = profilingTracesDirPath; this.profilingTracesHz = profilingTracesHz; this.executorServiceSupplier = executorServiceSupplier; @@ -324,6 +322,7 @@ private void stop(final boolean restartProfiler) { } } + @Override public void reevaluateSampling() { shouldSample = true; } @@ -362,27 +361,27 @@ public void close(final boolean isTerminating) { return ProfileRecordingState.UNKNOWN; } + @SuppressWarnings("FutureReturnValueIgnored") private void sendChunks(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { try { options .getExecutorService() - .submit( - () -> { - // SDK is closed, we don't send the chunks - if (isClosed.get()) { - return; - } - final ArrayList payloads = new ArrayList<>(payloadBuilders.size()); - try (final @NotNull ISentryLifecycleToken ignored = payloadLock.acquire()) { - for (ProfileChunk.Builder builder : payloadBuilders) { - payloads.add(builder.build(options)); - } - payloadBuilders.clear(); - } - for (ProfileChunk payload : payloads) { - scopes.captureProfileChunk(payload); - } - }); + .submit(() -> { + // SDK is closed, we don't send the chunks + if (isClosed.get()) { + return; + } + final ArrayList payloads = new ArrayList<>(payloadBuilders.size()); + try (final @NotNull ISentryLifecycleToken ignored = payloadLock.acquire()) { + for (ProfileChunk.Builder builder : payloadBuilders) { + payloads.add(builder.build(options)); + } + payloadBuilders.clear(); + } + for (ProfileChunk payload : payloads) { + scopes.captureProfileChunk(payload); + } + }); } catch (Throwable e) { options.getLogger().log(SentryLevel.DEBUG, "Failed to send profile chunks.", e); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidFatalLogger.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidFatalLogger.java index 76d6ba99784..3d7e46abf4d 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidFatalLogger.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidFatalLogger.java @@ -27,9 +27,9 @@ public void log( final @NotNull String message, final @Nullable Object... args) { if (args == null || args.length == 0) { - Log.println(toLogcatLevel(level), tag, message); + Log.println(Log.ASSERT, tag, message); } else { - Log.println(toLogcatLevel(level), tag, String.format(message, args)); + Log.println(Log.ASSERT, tag, String.format(message, args)); } } @@ -59,8 +59,4 @@ public void log( public boolean isEnabled(@Nullable SentryLevel level) { return true; } - - private int toLogcatLevel(final @NotNull SentryLevel sentryLevel) { - return Log.ASSERT; - } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidLoggerBatchProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidLoggerBatchProcessor.java index b81666e2f38..0eeb8bee1c8 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidLoggerBatchProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidLoggerBatchProcessor.java @@ -23,6 +23,7 @@ public void onForeground() { } @Override + @SuppressWarnings("FutureReturnValueIgnored") public void onBackground() { if (!hasAcceptedItem) { return; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidMemoryCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidMemoryCollector.java index 6775d818b4e..3410b860498 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidMemoryCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidMemoryCollector.java @@ -7,7 +7,7 @@ import org.jetbrains.annotations.NotNull; @ApiStatus.Internal -public class AndroidMemoryCollector implements IPerformanceSnapshotCollector { +public final class AndroidMemoryCollector implements IPerformanceSnapshotCollector { @Override public void setup() {} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidMetricsBatchProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidMetricsBatchProcessor.java index d92c4369139..c224231daaa 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidMetricsBatchProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidMetricsBatchProcessor.java @@ -23,6 +23,7 @@ public void onForeground() { } @Override + @SuppressWarnings("FutureReturnValueIgnored") public void onBackground() { if (!hasAcceptedItem) { return; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java index 52afab2355d..6adca10a272 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidOptionsInitializer.java @@ -1,6 +1,7 @@ package io.sentry.android.core; import static io.sentry.android.core.NdkIntegration.SENTRY_NDK_CLASS_NAME; +import static io.sentry.android.core.NdkIntegration.SENTRY_NDK_OUTPROC_CLASS_NAME; import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion; import android.annotation.SuppressLint; @@ -428,8 +429,12 @@ static void installDefaultIntegrations( // Integrations are registered in the same order. NDK before adding Watch outbox, // because sentry-native move files around and we don't want to watch that. - final Class sentryNdkClass = loadClass.loadClass(SENTRY_NDK_CLASS_NAME, options.getLogger()); - options.addIntegration(new NdkIntegration(sentryNdkClass)); + // the outproc backend builds on the inproc one, so it goes first, and quietly + Class sentryNdkClass = loadClass.loadClass(SENTRY_NDK_OUTPROC_CLASS_NAME, null); + if (sentryNdkClass == null) { + sentryNdkClass = loadClass.loadClass(SENTRY_NDK_CLASS_NAME, options.getLogger()); + } + options.addIntegration(new NdkIntegration(context, sentryNdkClass)); if (buildInfoProvider.getSdkInfoVersion() >= Build.VERSION_CODES.S) { options.addIntegration(new TombstoneIntegration(context)); @@ -492,7 +497,7 @@ static void installDefaultIntegrations( options.setReplayController(replay); } if (isDistributionAvailable) { - final DistributionIntegration distribution = new DistributionIntegration((context)); + final DistributionIntegration distribution = new DistributionIntegration(context); options.setDistributionController(distribution); options.addIntegration(distribution); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java index 8710c5d637f..69bf8805cde 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java @@ -31,8 +31,8 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class AndroidProfiler { - public static class ProfileStartData { +public final class AndroidProfiler { + public static final class ProfileStartData { public final long startNanos; public final long startCpuMillis; public final @NotNull Date startTimestamp; @@ -45,7 +45,7 @@ public ProfileStartData( } } - public static class ProfileEndData { + public static final class ProfileEndData { public final long endNanos; public final long endCpuMillis; public final @NotNull File traceFile; @@ -96,7 +96,7 @@ public ProfileEndData( timeoutExecutorServiceSupplier; private final @NotNull ILogger logger; private volatile boolean isRunning = false; - protected final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); + final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); public AndroidProfiler( final @NotNull String tracesFilesDirPath, diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AndroidxWebViewScriptInstaller.java b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidxWebViewScriptInstaller.java new file mode 100644 index 00000000000..39cff9a4b82 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AndroidxWebViewScriptInstaller.java @@ -0,0 +1,48 @@ +package io.sentry.android.core; + +import android.webkit.WebView; +import androidx.webkit.ScriptHandler; +import androidx.webkit.WebViewCompat; +import androidx.webkit.WebViewFeature; +import java.util.Set; +import org.jetbrains.annotations.NotNull; + +/** + * Installs Sentry's document-start script through androidx.webkit. All androidx.webkit references + * are isolated in this class, so it must only be loaded once {@link SentryWebViewTracing} has + * checked that androidx.webkit is available. That check deliberately lives outside of this class, + * so that it can run without linking any androidx.webkit type. + */ +final class AndroidxWebViewScriptInstaller implements WebViewScriptInstaller { + + @Override + public boolean isDocumentStartScriptSupported() { + return WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT); + } + + @Override + public void removeInstalledScript(final @NotNull WebView webView) { + final Object handler = webView.getTag(R.id.sentry_webview_trace_propagation); + // Cleared first, so a handler whose removal throws is not removed again on every later call. + webView.setTag(R.id.sentry_webview_trace_propagation, null); + // A handler only exists if the feature was supported when it was installed. + if (handler instanceof ScriptHandler + && WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { + ((ScriptHandler) handler).remove(); + } + } + + @Override + public boolean installScript( + final @NotNull WebView webView, + final @NotNull String script, + final @NotNull Set allowedOriginRules) { + if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { + return false; + } + final @NotNull ScriptHandler handler = + WebViewCompat.addDocumentStartJavaScript(webView, script, allowedOriginRules); + webView.setTag(R.id.sentry_webview_trace_propagation, handler); + return true; + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AnrIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AnrIntegration.java index 275914e3fe2..a1b3abd3906 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AnrIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AnrIntegration.java @@ -47,8 +47,7 @@ public AnrIntegration(final @NotNull Context context) { private @Nullable SentryOptions options; - protected static final @NotNull AutoClosableReentrantLock watchDogLock = - new AutoClosableReentrantLock(); + static final @NotNull AutoClosableReentrantLock watchDogLock = new AutoClosableReentrantLock(); @Override public final void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { @@ -56,6 +55,7 @@ public final void register(final @NotNull IScopes scopes, final @NotNull SentryO register(scopes, (SentryAndroidOptions) options); } + @SuppressWarnings("FutureReturnValueIgnored") private void register( final @NotNull IScopes scopes, final @NotNull SentryAndroidOptions options) { options @@ -67,14 +67,13 @@ private void register( try { options .getExecutorService() - .submit( - () -> { - try (final @NotNull ISentryLifecycleToken ignored = startLock.acquire()) { - if (!isClosed) { - startAnrWatchdog(scopes, options); - } - } - }); + .submit(() -> { + try (final @NotNull ISentryLifecycleToken ignored = startLock.acquire()) { + if (!isClosed) { + startAnrWatchdog(scopes, options); + } + } + }); } catch (Throwable e) { options .getLogger() diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java index c80ce982b95..19de22c9a87 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AnrV2Integration.java @@ -44,7 +44,7 @@ import org.jetbrains.annotations.Nullable; @SuppressLint("NewApi") // we check this in AnrIntegrationFactory -public class AnrV2Integration implements Integration, Closeable { +public final class AnrV2Integration implements Integration, Closeable { private final @NotNull Context context; private final @NotNull ICurrentDateProvider dateProvider; @@ -63,6 +63,7 @@ public AnrV2Integration(final @NotNull Context context) { } @Override + @SuppressWarnings("FutureReturnValueIgnored") public void register(@NotNull IScopes scopes, @NotNull SentryOptions options) { this.options = Objects.requireNonNull( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java index e98c0afb2db..66afe6033a3 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppComponentsBreadcrumbsIntegration.java @@ -12,7 +12,6 @@ import io.sentry.Integration; import io.sentry.SentryLevel; import io.sentry.SentryOptions; -import io.sentry.android.core.internal.util.AndroidCurrentDateProvider; import io.sentry.android.core.internal.util.Debouncer; import io.sentry.android.core.internal.util.DeviceOrientations; import io.sentry.protocol.Device; @@ -34,10 +33,7 @@ public final class AppComponentsBreadcrumbsIntegration private @Nullable IScopes scopes; private @Nullable SentryAndroidOptions options; - // TODO: JAVA-729 - @SuppressWarnings("deprecation") - private final @NotNull Debouncer trimMemoryDebouncer = - new Debouncer(AndroidCurrentDateProvider.getInstance(), DEBOUNCE_WAIT_TIME_MS, 0); + private volatile @Nullable Debouncer trimMemoryDebouncer; public AppComponentsBreadcrumbsIntegration(final @NotNull Context context) { this.context = @@ -51,6 +47,8 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions Objects.requireNonNull( (options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null, "SentryAndroidOptions is required"); + this.trimMemoryDebouncer = + new Debouncer(this.options.getMonotonicTicker(), DEBOUNCE_WAIT_TIME_MS, 0); this.options .getLogger() @@ -121,7 +119,8 @@ public void onTrimMemory(final int level) { return; } - if (trimMemoryDebouncer.checkForDebounce()) { + final @Nullable Debouncer trimMemoryDebouncer = this.trimMemoryDebouncer; + if (trimMemoryDebouncer != null && trimMemoryDebouncer.checkForDebounce()) { // if we received trim_memory within 1 minute time, ignore this call return; } @@ -169,6 +168,7 @@ private void captureConfigurationChangedBreadcrumb( } } + @SuppressWarnings("FutureReturnValueIgnored") private void executeInBackground(final @NotNull Runnable runnable) { if (options != null) { try { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java index 74522f7aaac..24562e3aa49 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/AppState.java @@ -25,7 +25,7 @@ public final class AppState implements Closeable { private static @NotNull AppState instance = new AppState(); private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); - private volatile LifecycleObserver lifecycleObserver; + private volatile @Nullable LifecycleObserver lifecycleObserver; private MainLooperHandler handler = new MainLooperHandler(); private AppState() {} @@ -49,7 +49,7 @@ public void resetInstance() { @ApiStatus.Internal @TestOnly - public LifecycleObserver getLifecycleObserver() { + public @Nullable LifecycleObserver getLifecycleObserver() { return lifecycleObserver; } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java index 79e671b4f49..63b08cb9b73 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ApplicationExitInfoEventProcessor.java @@ -242,6 +242,7 @@ private boolean sampleReplay( return true; } + @SuppressWarnings("JavaUtilDate") private void setReplayId( final @NotNull SentryEvent event, final @NotNull OptionsSource optionsSource) { @Nullable String persistedReplayId = readFromDisk(options, REPLAY_FILENAME, String.class); @@ -931,6 +932,7 @@ private void setAnrExceptions( sentryExceptionFactory.getSentryExceptionsFromThread(mainThread, mechanism, anr)); } + @SuppressWarnings("JavaUtilDate") private void applyAnrProfile( @NotNull SentryEvent event, @NotNull Backfillable hint, diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java index b189746fde6..22938712faf 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ContextUtils.java @@ -38,7 +38,7 @@ @ApiStatus.Internal public final class ContextUtils { - static class SideLoadedInfo { + static final class SideLoadedInfo { private final boolean isSideLoaded; private final @Nullable String installerStore; @@ -65,7 +65,7 @@ public boolean isSideLoaded() { } } - static class SplitApksInfo { + static final class SplitApksInfo { // https://github.com/google/bundletool/blob/master/src/main/java/com/android/tools/build/bundletool/model/AndroidManifest.java#L257-L263 static final String SPLITS_REQUIRED = "com.android.vending.splits.required"; @@ -98,45 +98,42 @@ private ContextUtils() {} */ @SuppressLint("NewApi") private static final @NotNull AndroidLazyEvaluator staticPackageInfo33 = - new AndroidLazyEvaluator<>( - context -> { - try { - return context - .getPackageManager() - .getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(0)); - } catch (Throwable e) { - return null; - } - }); + new AndroidLazyEvaluator<>(context -> { + try { + return context + .getPackageManager() + .getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(0)); + } catch (Throwable e) { + return null; + } + }); private static final @NotNull AndroidLazyEvaluator staticPackageInfo = - new AndroidLazyEvaluator<>( - context -> { - try { - return context.getPackageManager().getPackageInfo(context.getPackageName(), 0); - } catch (Throwable e) { - return null; - } - }); + new AndroidLazyEvaluator<>(context -> { + try { + return context.getPackageManager().getPackageInfo(context.getPackageName(), 0); + } catch (Throwable e) { + return null; + } + }); private static final @NotNull AndroidLazyEvaluator applicationName = - new AndroidLazyEvaluator<>( - context -> { - try { - final ApplicationInfo applicationInfo = context.getApplicationInfo(); - final int stringId = applicationInfo.labelRes; - if (stringId == 0) { - if (applicationInfo.nonLocalizedLabel != null) { - return applicationInfo.nonLocalizedLabel.toString(); - } - return context.getPackageManager().getApplicationLabel(applicationInfo).toString(); - } else { - return context.getString(stringId); - } - } catch (Throwable e) { - return null; + new AndroidLazyEvaluator<>(context -> { + try { + final ApplicationInfo applicationInfo = context.getApplicationInfo(); + final int stringId = applicationInfo.labelRes; + if (stringId == 0) { + if (applicationInfo.nonLocalizedLabel != null) { + return applicationInfo.nonLocalizedLabel.toString(); } - }); + return context.getPackageManager().getApplicationLabel(applicationInfo).toString(); + } else { + return context.getString(stringId); + } + } catch (Throwable e) { + return null; + } + }); /** * Since this applicationInfo uses the same flag (METADATA) we can assume it's static and cache it @@ -145,30 +142,28 @@ private ContextUtils() {} */ @SuppressLint("NewApi") private static final @NotNull AndroidLazyEvaluator staticAppInfo33 = - new AndroidLazyEvaluator<>( - context -> { - try { - return context - .getPackageManager() - .getApplicationInfo( - context.getPackageName(), - PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA)); - } catch (Throwable e) { - return null; - } - }); + new AndroidLazyEvaluator<>(context -> { + try { + return context + .getPackageManager() + .getApplicationInfo( + context.getPackageName(), + PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA)); + } catch (Throwable e) { + return null; + } + }); private static final @NotNull AndroidLazyEvaluator staticAppInfo = - new AndroidLazyEvaluator<>( - context -> { - try { - return context - .getPackageManager() - .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); - } catch (Throwable e) { - return null; - } - }); + new AndroidLazyEvaluator<>(context -> { + try { + return context + .getPackageManager() + .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); + } catch (Throwable e) { + return null; + } + }); /** * Return the Application's PackageInfo if possible, or null. @@ -520,6 +515,7 @@ static void setAppPackageInfo( } } } catch (Throwable e) { + // Split APK info is optional, the app context is still complete without it. } } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/CurrentActivityHolder.java b/sentry-android-core/src/main/java/io/sentry/android/core/CurrentActivityHolder.java index a7733821c05..710dbf954cf 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/CurrentActivityHolder.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/CurrentActivityHolder.java @@ -7,7 +7,7 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class CurrentActivityHolder { +public final class CurrentActivityHolder { private static final @NotNull CurrentActivityHolder instance = new CurrentActivityHolder(); @@ -26,6 +26,7 @@ private CurrentActivityHolder() {} return null; } + @SuppressWarnings("ReferenceEquality") public void setActivity(final @NotNull Activity activity) { if (currentActivity != null && currentActivity.get() == activity) { return; @@ -38,6 +39,7 @@ public void clearActivity() { currentActivity = null; } + @SuppressWarnings("ReferenceEquality") public void clearActivity(final @NotNull Activity activity) { if (currentActivity != null && currentActivity.get() != activity) { return; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java index c2139d9dcbe..5c28ccaf488 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java @@ -18,7 +18,6 @@ import io.sentry.protocol.SentryTransaction; import io.sentry.protocol.User; import io.sentry.util.HintUtils; -import io.sentry.util.LazyEvaluator; import io.sentry.util.Objects; import java.util.Collections; import java.util.List; @@ -40,8 +39,7 @@ final class DefaultAndroidEventProcessor implements SentryEventProcessor { private final @NotNull BuildInfoProvider buildInfoProvider; private final @NotNull SentryAndroidOptions options; @TestOnly final @Nullable Future deviceInfoUtil; - private final @NotNull LazyEvaluator deviceFamily = - new LazyEvaluator<>(() -> ContextUtils.getFamily(NoOpLogger.getInstance())); + private final @Nullable String deviceFamily = ContextUtils.getFamily(NoOpLogger.getInstance()); public DefaultAndroidEventProcessor( final @NotNull Context context, @@ -238,7 +236,7 @@ private void setDevice(final @NotNull SentryLogEvent event) { "device.model", new SentryLogEventAttributeValue(SentryAttributeType.STRING, Build.MODEL)); event.setAttribute( "device.family", - new SentryLogEventAttributeValue(SentryAttributeType.STRING, deviceFamily.getValue())); + new SentryLogEventAttributeValue(SentryAttributeType.STRING, deviceFamily)); } private void setOs(final @NotNull SentryLogEvent event) { @@ -256,7 +254,7 @@ private void setDevice(final @NotNull SentryMetricsEvent event) { "device.model", new SentryLogEventAttributeValue(SentryAttributeType.STRING, Build.MODEL)); event.setAttribute( "device.family", - new SentryLogEventAttributeValue(SentryAttributeType.STRING, deviceFamily.getValue())); + new SentryLogEventAttributeValue(SentryAttributeType.STRING, deviceFamily)); } private void setOs(final @NotNull SentryMetricsEvent event) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserver.java b/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserver.java index 4a3dc7a1786..b0da4dcdac6 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserver.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserver.java @@ -73,7 +73,7 @@ private static final class CachedEnvelopeHint private final long flushTimeoutMillis; private final @NotNull ILogger logger; - public CachedEnvelopeHint(final long flushTimeoutMillis, final @NotNull ILogger logger) { + CachedEnvelopeHint(final long flushTimeoutMillis, final @NotNull ILogger logger) { reset(); this.flushTimeoutMillis = flushTimeoutMillis; this.logger = Objects.requireNonNull(logger, "ILogger is required."); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java index ab95ae32daa..e81577cfd4b 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/EnvelopeFileObserverIntegration.java @@ -30,6 +30,7 @@ public abstract class EnvelopeFileObserverIntegration implements Integration, Cl } @Override + @SuppressWarnings("FutureReturnValueIgnored") public final void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { Objects.requireNonNull(scopes, "Scopes are required"); Objects.requireNonNull(options, "SentryOptions is required"); @@ -48,14 +49,13 @@ public final void register(final @NotNull IScopes scopes, final @NotNull SentryO try { options .getExecutorService() - .submit( - () -> { - try (final @NotNull ISentryLifecycleToken ignored = startLock.acquire()) { - if (!isClosed) { - startOutboxSender(scopes, options, path); - } - } - }); + .submit(() -> { + try (final @NotNull ISentryLifecycleToken ignored = startLock.acquire()) { + if (!isClosed) { + startOutboxSender(scopes, options, path); + } + } + }); } catch (Throwable e) { logger.log( SentryLevel.DEBUG, diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java index 4405cd19309..677678b2438 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/FeedbackShakeIntegration.java @@ -78,6 +78,7 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions } @Override + @SuppressWarnings("FutureReturnValueIgnored") public synchronized void enableOnShake() { final @Nullable SentryAndroidOptions options = this.options; if (enabled || options == null) { @@ -154,6 +155,7 @@ void onDialogGone(final @NotNull Dialog dialog) { } } + @SuppressWarnings("ReferenceEquality") private boolean removeDialog(final @NotNull Dialog dialog) { boolean removed = false; for (final @NotNull VisibleDialog visibleDialog : visibleDialogs) { @@ -169,6 +171,7 @@ private boolean removeDialog(final @NotNull Dialog dialog) { return removed; } + @SuppressWarnings("ReferenceEquality") private boolean hasDialogOn(final @NotNull Activity activity) { for (final @NotNull VisibleDialog visibleDialog : visibleDialogs) { if (visibleDialog.dialogRef.get() != null && visibleDialog.activityRef.get() == activity) { @@ -226,6 +229,7 @@ public void onActivityResumed(final @NotNull Activity activity) { } @Override + @SuppressWarnings("ReferenceEquality") public void onActivityPaused(final @NotNull Activity activity) { // Only stop if this is the activity we're tracking. When transitioning between // activities, B.onResume may fire before A.onPause — stopping unconditionally @@ -274,6 +278,7 @@ private void startShakeDetection(final @NotNull Activity activity) { final @Nullable WeakReference ref = currentActivityRef; final Activity active = ref != null ? ref.get() : null; final Boolean inBackground = AppState.getInstance().isInBackground(); + final @Nullable SentryAndroidOptions options = this.options; if (active == null || options == null || !enabled @@ -281,30 +286,26 @@ private void startShakeDetection(final @NotNull Activity activity) { || Boolean.TRUE.equals(inBackground)) { return; } - active.runOnUiThread( - () -> { - // Re-check on the main thread: shake-to-report may have been disabled, or an - // earlier queued shake may have shown a dialog in the meantime (the dialog reports - // itself synchronously in onStart). - if (!enabled - || hasDialogOn(active) - || active.isFinishing() - || active.isDestroyed()) { - return; - } - @Nullable Dialog dialog = null; - try { - dialog = dialogFactory.create(active); - dialog.show(); - } catch (Throwable e) { - if (dialog != null) { - onDialogGone(dialog); - } - options - .getLogger() - .log(SentryLevel.ERROR, "Failed to show feedback dialog on shake.", e); - } - }); + active.runOnUiThread(() -> { + // Re-check on the main thread: shake-to-report may have been disabled, or an + // earlier queued shake may have shown a dialog in the meantime (the dialog reports + // itself synchronously in onStart). + if (!enabled || hasDialogOn(active) || active.isFinishing() || active.isDestroyed()) { + return; + } + @Nullable Dialog dialog = null; + try { + dialog = dialogFactory.create(active); + dialog.show(); + } catch (Throwable e) { + if (dialog != null) { + onDialogGone(dialog); + } + options + .getLogger() + .log(SentryLevel.ERROR, "Failed to show feedback dialog on shake.", e); + } + }); }); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/Installation.java b/sentry-android-core/src/main/java/io/sentry/android/core/Installation.java index ba08e71342a..fcd4406a5f8 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/Installation.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/Installation.java @@ -21,8 +21,7 @@ final class Installation { private static final Charset UTF_8 = Charset.forName("UTF-8"); - protected static final @NotNull AutoClosableReentrantLock staticLock = - new AutoClosableReentrantLock(); + static final @NotNull AutoClosableReentrantLock staticLock = new AutoClosableReentrantLock(); private Installation() {} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java index 4ad11399d02..7c2e72031bb 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/InternalSentrySdk.java @@ -51,7 +51,7 @@ public final class InternalSentrySdk { /** - * @return a copy of the current scopes's topmost scope, or null in case the scopes is disabled + * Returns a copy of the current scopes's topmost scope, or null in case the scopes is disabled. */ @Nullable public static IScope getCurrentScope() { @@ -293,28 +293,24 @@ public static void updateSessionForDroppedEventNonTerminating(final boolean cras private static void updateSessionNonTerminating(final boolean unhandled) { final @NotNull IScopes scopes = ScopesAdapter.getInstance(); final @NotNull SentryOptions options = scopes.getOptions(); - scopes.configureScope( - scope -> - scope.withSession( - session -> { - if (session == null) { - options.getLogger().log(INFO, "Session is null on updateSessionNonTerminating"); - return; - } - if (session.isTerminated()) { - options - .getLogger() - .log(INFO, "Session already terminated, not recording the error."); - return; - } - final boolean recorded = - unhandled - ? session.recordNonTerminatingUnhandledError() - : session.update(null, null, true, null); - if (recorded && options.getEnvelopeDiskCache() instanceof EnvelopeCache) { - ((EnvelopeCache) options.getEnvelopeDiskCache()).persistCurrentSession(session); - } - })); + scopes.configureScope(scope -> + scope.withSession(session -> { + if (session == null) { + options.getLogger().log(INFO, "Session is null on updateSessionNonTerminating"); + return; + } + if (session.isTerminated()) { + options.getLogger().log(INFO, "Session already terminated, not recording the error."); + return; + } + final boolean recorded = + unhandled + ? session.recordNonTerminatingUnhandledError() + : session.update(null, null, true, null); + if (recorded && options.getEnvelopeDiskCache() instanceof EnvelopeCache) { + ((EnvelopeCache) options.getEnvelopeDiskCache()).persistCurrentSession(session); + } + })); } /** What the events inside an envelope amount to, from the session's point of view. */ @@ -409,16 +405,16 @@ private static void addTimeSpanToSerializedSpans(TimeSpan span, List { - deleteCurrentSessionFile(options); - }); + .submit(() -> { + deleteCurrentSessionFile(options); + }); } catch (Throwable e) { options .getLogger() @@ -449,29 +445,27 @@ private static Session updateSession( final @Nullable Session.State status, final boolean crashedOrErrored) { final @NotNull AtomicReference sessionRef = new AtomicReference<>(); - scopes.configureScope( - scope -> { - scope.withSession( - session -> { - if (session != null) { - final boolean updated = session.update(status, null, crashedOrErrored, null); - // if we have an uncaughtExceptionHint we can end the session. - if (updated) { - if (session.getStatus() == Session.State.Crashed) { - session.end(); - // Session needs to be removed from the scope, otherwise it will be send twice - // standalone and with the crash event - scope.clearSession(); - } - // fromSession serializes lazily, on the transport thread, so handing out the - // live session would race a later mutation - sessionRef.set(session.clone()); - } - } else { - options.getLogger().log(INFO, "Session is null on updateSession"); - } - }); - }); + scopes.configureScope(scope -> { + scope.withSession(session -> { + if (session != null) { + final boolean updated = session.update(status, null, crashedOrErrored, null); + // if we have an uncaughtExceptionHint we can end the session. + if (updated) { + if (session.getStatus() == Session.State.Crashed) { + session.end(); + // Session needs to be removed from the scope, otherwise it will be send twice + // standalone and with the crash event + scope.clearSession(); + } + // fromSession serializes lazily, on the transport thread, so handing out the + // live session would race a later mutation + sessionRef.set(session.clone()); + } + } else { + options.getLogger().log(INFO, "Session is null on updateSession"); + } + }); + }); return sessionRef.get(); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java b/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java index f0078bc353e..0534e9ba539 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java @@ -83,18 +83,19 @@ private void startSession() { *

TODO [MAJOR]: let a session remember the tick it started on, so this can use a {@link * Deadline} too. That tick must not be serialized. */ + // Session#getStarted() is a Date, see above. + @SuppressWarnings("JavaUtilDate") private boolean isSessionOnScopeStale() { final long nowMillis = TimeUnit.NANOSECONDS.toMillis(epochClock.now().epochNanos()); // No session, or one that never recorded a start, leaves nothing to resume. final @NotNull AtomicBoolean stale = new AtomicBoolean(true); - scopes.configureScope( - scope -> { - final @Nullable Session session = scope.getSession(); - final @Nullable Date started = session == null ? null : session.getStarted(); - if (started != null) { - stale.set(started.getTime() + sessionIntervalMillis <= nowMillis); - } - }); + scopes.configureScope(scope -> { + final @Nullable Session session = scope.getSession(); + final @Nullable Date started = session == null ? null : session.getStarted(); + if (started != null) { + stale.set(started.getTime() + sessionIntervalMillis <= nowMillis); + } + }); return stale.get(); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java b/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java index c7ea05d5f82..411546a80b5 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ManifestMetadataReader.java @@ -102,6 +102,8 @@ final class ManifestMetadataReader { static final String TRACE_PROPAGATION_TARGETS = "io.sentry.traces.trace-propagation-targets"; + static final String WEBVIEW_TRACING_ALLOWED_HOSTS = "io.sentry.webview-tracing.allowed-hosts"; + static final String ATTACH_THREADS = "io.sentry.attach-threads"; static final String PROGUARD_UUID = "io.sentry.proguard-uuid"; static final String IDLE_TIMEOUT = "io.sentry.traces.idle-timeout"; @@ -541,6 +543,12 @@ static void applyMetadata( options.setTracePropagationTargets(tracePropagationTargets); } + final @Nullable List webViewTracingAllowedHosts = + readList(metadata, logger, WEBVIEW_TRACING_ALLOWED_HOSTS); + if (webViewTracingAllowedHosts != null) { + options.getWebViewTracing().setAllowedHosts(webViewTracingAllowedHosts); + } + options.setEnableFramesTracking(readBool(metadata, logger, PERFORM_FRAMES_TRACKING, true)); options.setProguardUuid( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/MemoryLimiterIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/MemoryLimiterIntegration.java index f259250a733..83f5b680fe7 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/MemoryLimiterIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/MemoryLimiterIntegration.java @@ -107,6 +107,7 @@ public MemoryLimiterIntegration( } @Override + @SuppressWarnings("FutureReturnValueIgnored") public void register(@NotNull IScopes scopes, @NotNull SentryOptions options) { androidOptions = Objects.requireNonNull( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/NativeEventCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/NativeEventCollector.java index 69dfa9c16be..bb7811ce594 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/NativeEventCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/NativeEventCollector.java @@ -302,6 +302,7 @@ public boolean deleteNativeEventFile(final @NotNull NativeEventData nativeEventD * the fields we need and exits early once found. Uses a bounded stream to track position within * the payload and skip any unread bytes on close, avoiding allocation of the full payload. */ + @SuppressWarnings("JavaUtilDate") private @Nullable NativeEnvelopeMetadata extractMetadataFromEventPayload( final @NotNull InputStream stream, final int payloadLength, final @NotNull File file) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java index 8353a32d65d..f8c96b71459 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/NdkIntegration.java @@ -2,6 +2,7 @@ import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion; +import android.content.Context; import io.sentry.IScopes; import io.sentry.Integration; import io.sentry.SentryLevel; @@ -19,11 +20,20 @@ public final class NdkIntegration implements Integration, Closeable { public static final String SENTRY_NDK_CLASS_NAME = "io.sentry.android.ndk.SentryNdk"; + public static final String SENTRY_NDK_OUTPROC_CLASS_NAME = + "io.sentry.android.ndk.outproc.SentryNdkOutproc"; + + private final @Nullable Context context; private final @Nullable Class sentryNdkClass; private @Nullable SentryAndroidOptions options; public NdkIntegration(final @Nullable Class sentryNdkClass) { + this(null, sentryNdkClass); + } + + NdkIntegration(final @Nullable Context context, final @Nullable Class sentryNdkClass) { + this.context = context != null ? ContextUtils.getApplicationContext(context) : null; this.sentryNdkClass = sentryNdkClass; } @@ -50,9 +60,25 @@ public final void register(final @NotNull IScopes scopes, final @NotNull SentryO } try { - final Method method = sentryNdkClass.getMethod("init", SentryAndroidOptions.class); - final Object[] args = new Object[1]; - args[0] = this.options; + Method method = null; + Object[] args = null; + if (context != null) { + try { + method = sentryNdkClass.getMethod("init", Context.class, SentryAndroidOptions.class); + args = new Object[] {context, this.options}; + } catch (NoSuchMethodException e) { + // an older sentry-android-ndk + this.options + .getLogger() + .log( + SentryLevel.WARNING, + "SentryNdk.init(Context, SentryAndroidOptions) not found, using SentryNdk.init(SentryAndroidOptions)."); + } + } + if (method == null) { + method = sentryNdkClass.getMethod("init", SentryAndroidOptions.class); + args = new Object[] {this.options}; + } method.invoke(null, args); this.options.getLogger().log(SentryLevel.DEBUG, "NdkIntegration installed."); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/NetworkBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/NetworkBreadcrumbsIntegration.java index 0151c96de67..cd66efa01e8 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/NetworkBreadcrumbsIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/NetworkBreadcrumbsIntegration.java @@ -33,7 +33,6 @@ public final class NetworkBreadcrumbsIntegration implements Integration, Closeab private final @NotNull Context context; private final @NotNull BuildInfoProvider buildInfoProvider; private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); - private @Nullable SentryOptions options; @TestOnly @Nullable volatile NetworkBreadcrumbsNetworkCallback networkCallback; @@ -53,8 +52,6 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions (options instanceof SentryAndroidOptions) ? (SentryAndroidOptions) options : null, "SentryAndroidOptions is required"); - this.options = options; - options .getLogger() .log( @@ -189,7 +186,7 @@ private Breadcrumb createBreadcrumb(String action) { } } - static class NetworkBreadcrumbConnectionDetail { + static final class NetworkBreadcrumbConnectionDetail { final int downBandwidth, upBandwidth, signalStrength; private long timestampNanos; final boolean isVpn; @@ -231,7 +228,7 @@ boolean isSimilar(final @NotNull NetworkBreadcrumbConnectionDetail other) { // This means that if the new connection detail come less than 5 seconds after the previous // one, we'll report the signal and bandwidth as similar, regardless of their real value. boolean isTimestampSimilar = - DateUtils.nanosToMillis(Math.abs(timestampNanos - other.timestampNanos)) < 5000; + DateUtils.nanosToMillis((double) Math.abs(timestampNanos - other.timestampNanos)) < 5000; boolean isSignalSimilar = isTimestampSimilar || signalDiff <= 5; boolean isDownBandwidthSimilar = isTimestampSimilar || downBandwidthDiff <= Math.max(1000, Math.abs(downBandwidth) * 0.1); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoContinuousProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoContinuousProfiler.java index 15ae88f22c8..63512b7dd99 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoContinuousProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoContinuousProfiler.java @@ -73,7 +73,7 @@ */ @ApiStatus.Internal @RequiresApi(api = Build.VERSION_CODES.VANILLA_ICE_CREAM) -public class PerfettoContinuousProfiler +public final class PerfettoContinuousProfiler implements IContinuousProfiler, RateLimiter.IRateLimitObserver { private static final long MAX_CHUNK_DURATION_MILLIS = 60000; @@ -458,18 +458,17 @@ private void stopInternal(final boolean restartProfiler) { // endAndCollect is non-blocking: the listener fires when the OS delivers the trace file. // Synchronous: result already available — callback runs inline, lock is still held (re-entrant) // Asynchronous: callback runs on an OS thread — acquires lock itself for restart - currentProfiler.endAndCollect( - traceFile -> - onChunkCollected( - traceFile, - chunkProfilerId, - chunkChunkId, - chunkRecord, - measurements, - chunkTimestamp, - shouldRestart, - scopes, - options)); + currentProfiler.endAndCollect(traceFile -> + onChunkCollected( + traceFile, + chunkProfilerId, + chunkChunkId, + chunkRecord, + measurements, + chunkTimestamp, + shouldRestart, + scopes, + options)); } private void onChunkCollected( @@ -527,12 +526,14 @@ private void onChunkCollected( } } + @Override public void reevaluateSampling() { try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { shouldSample = true; } } + @SuppressWarnings("FutureReturnValueIgnored") private void sendChunk( final @NotNull ProfileChunk.Builder builder, final @NotNull IScopes scopes, @@ -568,7 +569,7 @@ private void sendChunk( * every 100ms and returned as a list on {@code stop()}. */ @VisibleForTesting - static class ChunkMeasurementCollector { + static final class ChunkMeasurementCollector { private final @NotNull SentryFrameMetricsCollector frameMetricsCollector; private @Nullable String frameMetricsListenerId = null; private @Nullable CompositePerformanceCollector performanceCollector = null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java index 627a434d6f3..4a64359aa44 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/PerfettoProfiler.java @@ -28,7 +28,7 @@ */ @ApiStatus.Internal @RequiresApi(api = Build.VERSION_CODES.VANILLA_ICE_CREAM) -public class PerfettoProfiler { +public final class PerfettoProfiler { // Bundle keys matching ProfilingManager constants private static final String KEY_DURATION_MS = "KEY_DURATION_MS"; @@ -123,6 +123,7 @@ boolean start(final @NotNull ChunkRecord chunkRecord, final long durationMs) { * error) once the OS delivers the result. The listener may be called synchronously if the result * has already arrived, or asynchronously on an OS-managed thread otherwise. */ + @SuppressWarnings("FutureReturnValueIgnored") public void endAndCollect(final @NotNull Consumer<@Nullable File> listener) { if (!started) { logger.log(SentryLevel.WARNING, "PerfettoProfiler was never started"); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/PerformanceAndroidEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/PerformanceAndroidEventProcessor.java index aff50c99340..47404d43333 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/PerformanceAndroidEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/PerformanceAndroidEventProcessor.java @@ -40,13 +40,10 @@ final class PerformanceAndroidEventProcessor implements SentryEventProcessor { private static final String APP_METRICS_ORIGIN = "auto.ui"; private static final String APP_METRICS_CONTENT_PROVIDER_OP = "contentprovider.load"; - private static final String APP_METRICS_ACTIVITIES_OP = "activity.load"; private static final String APP_METRICS_APPLICATION_OP = "application.load"; private static final String APP_METRICS_PROCESS_INIT_OP = "process.load"; private static final long MAX_PROCESS_INIT_APP_START_DIFF_MS = 10000; - private boolean sentStartMeasurement = false; - private final @NotNull SentryAndroidOptions options; private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ScreenshotEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ScreenshotEventProcessor.java index 28deaf620c6..8950b4ab091 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ScreenshotEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ScreenshotEventProcessor.java @@ -9,7 +9,6 @@ import io.sentry.Hint; import io.sentry.SentryEvent; import io.sentry.SentryLevel; -import io.sentry.android.core.internal.util.AndroidCurrentDateProvider; import io.sentry.android.core.internal.util.Debouncer; import io.sentry.android.core.internal.util.ScreenshotUtils; import io.sentry.internal.eventprocessor.SentryEventProcessor; @@ -39,8 +38,6 @@ public final class ScreenshotEventProcessor implements SentryEventProcessor { private final boolean isReplayAvailable; private final AtomicBoolean isReplayModuleAbsenceLogged = new AtomicBoolean(false); - // TODO: JAVA-729 - @SuppressWarnings("deprecation") public ScreenshotEventProcessor( final @NotNull SentryAndroidOptions options, final @NotNull BuildInfoProvider buildInfoProvider, @@ -49,10 +46,7 @@ public ScreenshotEventProcessor( this.buildInfoProvider = Objects.requireNonNull(buildInfoProvider, "BuildInfoProvider is required"); this.debouncer = - new Debouncer( - AndroidCurrentDateProvider.getInstance(), - DEBOUNCE_WAIT_TIME_MS, - DEBOUNCE_MAX_EXECUTIONS); + new Debouncer(options.getMonotonicTicker(), DEBOUNCE_WAIT_TIME_MS, DEBOUNCE_MAX_EXECUTIONS); this.isReplayAvailable = isReplayAvailable; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java index 8eea2d71047..1f3dc572792 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SendCachedEnvelopeIntegration.java @@ -89,62 +89,58 @@ private void sendCachedEnvelopes( final Future future = options .getExecutorService() - .submit( - () -> { - try { - if (isClosed.get()) { - options - .getLogger() - .log( - SentryLevel.INFO, - "SendCachedEnvelopeIntegration, not trying to send after closing."); - return; - } - - if (!isInitialized.getAndSet(true)) { - connectionStatusProvider = options.getConnectionStatusProvider(); - connectionStatusProvider.addConnectionStatusObserver(this); - - sender = factory.create(scopes, options); - } - - if (connectionStatusProvider != null - && connectionStatusProvider.getConnectionStatus() - == IConnectionStatusProvider.ConnectionStatus.DISCONNECTED) { - options - .getLogger() - .log(SentryLevel.INFO, "SendCachedEnvelopeIntegration, no connection."); - return; - } - - // in case there's rate limiting active, skip processing - final @Nullable RateLimiter rateLimiter = scopes.getRateLimiter(); - if (rateLimiter != null - && rateLimiter.isActiveForCategory(DataCategory.All)) { - options - .getLogger() - .log( - SentryLevel.INFO, - "SendCachedEnvelopeIntegration, rate limiting active."); - return; - } - - if (sender == null) { - options - .getLogger() - .log( - SentryLevel.ERROR, - "SendCachedEnvelopeIntegration factory is null."); - return; - } - - sender.send(); - } catch (Throwable e) { - options - .getLogger() - .log(SentryLevel.ERROR, "Failed trying to send cached events.", e); - } - }); + .submit(() -> { + try { + if (isClosed.get()) { + options + .getLogger() + .log( + SentryLevel.INFO, + "SendCachedEnvelopeIntegration, not trying to send after closing."); + return; + } + + if (!isInitialized.getAndSet(true)) { + connectionStatusProvider = options.getConnectionStatusProvider(); + connectionStatusProvider.addConnectionStatusObserver(this); + + sender = factory.create(scopes, options); + } + + if (connectionStatusProvider != null + && connectionStatusProvider.getConnectionStatus() + == IConnectionStatusProvider.ConnectionStatus.DISCONNECTED) { + options + .getLogger() + .log(SentryLevel.INFO, "SendCachedEnvelopeIntegration, no connection."); + return; + } + + // in case there's rate limiting active, skip processing + final @Nullable RateLimiter rateLimiter = scopes.getRateLimiter(); + if (rateLimiter != null && rateLimiter.isActiveForCategory(DataCategory.All)) { + options + .getLogger() + .log( + SentryLevel.INFO, + "SendCachedEnvelopeIntegration, rate limiting active."); + return; + } + + if (sender == null) { + options + .getLogger() + .log(SentryLevel.ERROR, "SendCachedEnvelopeIntegration factory is null."); + return; + } + + sender.send(); + } catch (Throwable e) { + options + .getLogger() + .log(SentryLevel.ERROR, "Failed trying to send cached events.", e); + } + }); // startupCrashMarkerEvaluator remains true on subsequent runs, let's ensure we only block on // the very first execution (=app start) @@ -157,6 +153,13 @@ private void sendCachedEnvelopes( options .getLogger() .log(SentryLevel.DEBUG, "Synchronous send timed out, continuing in the background."); + } catch (InterruptedException e) { + // We don't own the calling thread, so keep its interrupt for the code that does + Thread.currentThread().interrupt(); + options + .getLogger() + .log( + SentryLevel.DEBUG, "Synchronous send interrupted, continuing in the background."); } } options.getLogger().log(SentryLevel.DEBUG, "SendCachedEnvelopeIntegration installed."); 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 418a6307790..bffbf75b980 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 @@ -1,7 +1,9 @@ package io.sentry.android.core; +import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; +import android.os.Build; import android.os.Process; import android.os.SystemClock; import android.os.Trace; @@ -48,8 +50,10 @@ public final class SentryAndroid { private static final String FRAGMENT_CLASS_NAME = "androidx.fragment.app.FragmentManager$FragmentLifecycleCallbacks"; - protected static final @NotNull AutoClosableReentrantLock staticLock = - new AutoClosableReentrantLock(); + // the process of SentryNdkCrashService in sentry-android-ndk-outproc + private static final String NDK_CRASH_SERVICE_PROCESS_SUFFIX = ".sentry_ndk_crash"; + + static final @NotNull AutoClosableReentrantLock staticLock = new AutoClosableReentrantLock(); private SentryAndroid() {} @@ -95,6 +99,12 @@ public static void init( @NotNull final Context context, @NotNull ILogger logger, @NotNull Sentry.OptionsConfiguration configuration) { + if (isNdkCrashServiceProcess()) { + logger.log( + SentryLevel.DEBUG, "Skipping SentryAndroid.init in the NDK crash service process."); + return; + } + // Started before acquiring the lock so it stays balanced with the endSection() in the finally // even if acquire() throws. Trace.beginSection("SentryAndroid.init"); @@ -180,13 +190,12 @@ public static void init( // so only start a session if it's not already started // This e.g. happens on React Native, or e.g. on deferred SDK init final AtomicBoolean sessionStarted = new AtomicBoolean(false); - scopes.configureScope( - scope -> { - final @Nullable Session currentSession = scope.getSession(); - if (currentSession != null && currentSession.getStarted() != null) { - sessionStarted.set(true); - } - }); + scopes.configureScope(scope -> { + final @Nullable Session currentSession = scope.getSession(); + if (currentSession != null && currentSession.getStarted() != null) { + sessionStarted.set(true); + } + }); if (!sessionStarted.get()) { scopes.startSession(); } @@ -269,4 +278,14 @@ 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) { + return false; + } + final @Nullable String processName = Application.getProcessName(); + return processName != null && processName.endsWith(NDK_CRASH_SERVICE_PROCESS_SUFFIX); + } } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java index 46dc16e0410..5b2e94eb830 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryAndroidOptions.java @@ -325,6 +325,10 @@ public interface BeforeCaptureCallback { */ private final @NotNull SentryScreenshotOptions screenshot = new SentryScreenshotOptions(); + /** Options for connecting the app's trace with web content in a {@code WebView}. */ + private final @NotNull SentryWebViewTracingOptions webViewTracing = + new SentryWebViewTracingOptions(); + /** * Sample rate for capturing main-thread stack profiles when a foreground ANR is detected. {@code * null} disables ANR profiling (default). Values must be between {@code 0.0} and {@code 1.0}. @@ -867,8 +871,8 @@ public void setReportHistoricalMemoryLimiterExits( } /** - * @return true if standalone app start tracing is enabled. See {@link - * #setEnableStandaloneAppStartTracing(boolean)} for more details. + * Returns true if standalone app start tracing is enabled. See {@link + * #setEnableStandaloneAppStartTracing(boolean)} for more details. */ @ApiStatus.Experimental public boolean isEnableStandaloneAppStartTracing() { @@ -950,6 +954,15 @@ public void setEnableSystemEventBreadcrumbsExtras( return screenshot; } + /** + * Returns the options for connecting the app's trace with web content in a {@code WebView}. + * + * @return the WebView tracing options + */ + public @NotNull SentryWebViewTracingOptions getWebViewTracing() { + return webViewTracing; + } + /** * Returns the sample rate used when deciding whether to capture a main-thread stack profile for a * detected foreground ANR. @@ -1018,7 +1031,7 @@ public void setEnableAnrFingerprinting(final boolean enableAnrFingerprinting) { return AndroidMonotonicTicker.getInstance(); } - static class AndroidUserFeedbackFormHandler implements SentryFeedbackOptions.IFormHandler { + static final class AndroidUserFeedbackFormHandler implements SentryFeedbackOptions.IFormHandler { @Override public void showForm( final @Nullable SentryId associatedEventId, diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryFrameMetrics.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryFrameMetrics.java index cf2241757ca..2989f10c640 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryFrameMetrics.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryFrameMetrics.java @@ -91,8 +91,9 @@ public SentryFrameMetrics duplicate() { } /** + * Returns the difference between two frame metrics (this minus other). + * * @param other the other frame metrics to compare to, usually the older one - * @return the difference between two frame metrics (this minus other) */ @NotNull public SentryFrameMetrics diffTo(final @NotNull SentryFrameMetrics other) { @@ -105,8 +106,8 @@ public SentryFrameMetrics diffTo(final @NotNull SentryFrameMetrics other) { } /** - * @return true if the frame metrics contain valid data, meaning all values are greater or equal - * to 0 + * Returns true if the frame metrics contain valid data, meaning all values are greater or equal + * to 0. */ public boolean containsValidData() { return slowFrameCount >= 0 diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryFramesDelayResult.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryFramesDelayResult.java index 724d8446ea8..65e7ab8456c 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryFramesDelayResult.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryFramesDelayResult.java @@ -16,15 +16,13 @@ public SentryFramesDelayResult( } /** - * @return the total frame delay in seconds, or -1 if incalculable (e.g. no frame data available) + * Returns the total frame delay in seconds, or -1 if incalculable (e.g. no frame data available). */ public double getDelaySeconds() { return delaySeconds; } - /** - * @return the number of frames that contributed to the delay (slow + frozen frames) - */ + /** Returns the number of frames that contributed to the delay (slow + frozen frames). */ public int getFramesContributingToDelayCount() { return framesContributingToDelayCount; } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryShakeDetector.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryShakeDetector.java index 9f4f73d10f4..72c100923cd 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryShakeDetector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryShakeDetector.java @@ -114,11 +114,10 @@ public synchronized void stop() { } final @Nullable Handler h = handler; if (h != null) { - h.post( - () -> { - //noinspection Convert2MethodRef - queue.clear(); - }); + h.post(() -> { + //noinspection Convert2MethodRef + queue.clear(); + }); } } @@ -159,7 +158,7 @@ public void onAccuracyChanged(final @NotNull Sensor sensor, final int accuracy) // Not needed for shake detection. } - static class SampleQueue { + static final class SampleQueue { private static final long MAX_WINDOW_SIZE_NS = 500_000_000L; // 0.5s private static final long MIN_WINDOW_SIZE_NS = MAX_WINDOW_SIZE_NS >> 1; // 0.25s private static final int MIN_QUEUE_SIZE = 4; @@ -226,13 +225,13 @@ boolean isShaking() { } } - static class Sample { + static final class Sample { long timestamp; boolean accelerating; @Nullable Sample next; } - static class SamplePool { + static final class SamplePool { private @Nullable Sample head; @NotNull diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackForm.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackForm.java index 999fad1227e..bf49fc075d9 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackForm.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryUserFeedbackForm.java @@ -39,7 +39,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class SentryUserFeedbackForm extends Dialog { +public final class SentryUserFeedbackForm extends Dialog { private boolean isCancelable = false; private @Nullable SentryId currentReplayId; @@ -150,12 +150,11 @@ private void stopShakeDetection() { } final @Nullable Activity active = activityRef.get(); if (active != null && !active.isFinishing() && !active.isDestroyed()) { - active.runOnUiThread( - () -> { - if (!active.isFinishing() && !active.isDestroyed()) { - show(); - } - }); + active.runOnUiThread(() -> { + if (!active.isFinishing() && !active.isDestroyed()) { + show(); + } + }); } }; } @@ -179,6 +178,7 @@ private class ShakeLifecycleCallbacks implements Application.ActivityLifecycleCa } @Override + @SuppressWarnings("ReferenceEquality") public void onActivityResumed(final @NotNull Activity activity) { if (activity == activityRef.get() && shakeDetector != null) { shakeDetector.start(activity, shakeListener(activityRef)); @@ -186,6 +186,7 @@ public void onActivityResumed(final @NotNull Activity activity) { } @Override + @SuppressWarnings("ReferenceEquality") public void onActivityPaused(final @NotNull Activity activity) { if (activity == activityRef.get() && shakeDetector != null) { shakeDetector.stop(); @@ -193,6 +194,7 @@ public void onActivityPaused(final @NotNull Activity activity) { } @Override + @SuppressWarnings("ReferenceEquality") public void onActivityDestroyed(final @NotNull Activity activity) { if (activity == activityRef.get()) { stopShakeDetection(); @@ -258,33 +260,32 @@ protected void onCreate(Bundle savedInstanceState) { // The button is made visible in onStart, once the screenshot picker is registered successfully btnAddScreenshot.setVisibility(View.GONE); - btnAddScreenshot.setOnClickListener( - v -> { - if (selectedImageUri == null) { - if (screenshotPicker != null) { - try { - screenshotPicker.launch(); - } catch (LinkageError e) { - // androidx.activity is compileOnly, so the version in the app's apk may not have - // the photo picker APIs this was compiled against - Sentry.getCurrentScopes() - .getOptions() - .getLogger() - .log(SentryLevel.ERROR, "Failed to launch the screenshot picker.", e); - } catch (Throwable t) { - ExceptionUtils.rethrowIfFatal(t); - // e.g. no photo picker on the device, or the launcher is no longer registered - Sentry.getCurrentScopes() - .getOptions() - .getLogger() - .log(SentryLevel.ERROR, "Failed to launch the screenshot picker.", t); - } - } - } else { - selectedImageUri = null; - btnAddScreenshot.setText(feedbackOptions.getAddScreenshotButtonLabel()); + btnAddScreenshot.setOnClickListener(v -> { + if (selectedImageUri == null) { + if (screenshotPicker != null) { + try { + screenshotPicker.launch(); + } catch (LinkageError e) { + // androidx.activity is compileOnly, so the version in the app's apk may not have + // the photo picker APIs this was compiled against + Sentry.getCurrentScopes() + .getOptions() + .getLogger() + .log(SentryLevel.ERROR, "Failed to launch the screenshot picker.", e); + } catch (Throwable t) { + ExceptionUtils.rethrowIfFatal(t); + // e.g. no photo picker on the device, or the launcher is no longer registered + Sentry.getCurrentScopes() + .getOptions() + .getLogger() + .log(SentryLevel.ERROR, "Failed to launch the screenshot picker.", t); } - }); + } + } else { + selectedImageUri = null; + btnAddScreenshot.setText(feedbackOptions.getAddScreenshotButtonLabel()); + } + }); if (feedbackOptions.isShowBranding()) { imgLogo.setVisibility(View.VISIBLE); @@ -335,76 +336,74 @@ protected void onCreate(Bundle savedInstanceState) { lblTitle.setText(feedbackOptions.getFormTitle()); btnSend.setText(feedbackOptions.getSubmitButtonLabel()); - btnSend.setOnClickListener( - v -> { - // Gather fields and trim them - final @NotNull String name = edtName.getText().toString().trim(); - final @NotNull String email = edtEmail.getText().toString().trim(); - final @NotNull String message = edtMessage.getText().toString().trim(); - - // If a required field is missing, shows the error label - if (name.isEmpty() && feedbackOptions.isNameRequired()) { - edtName.setError(lblName.getText()); - return; - } + btnSend.setOnClickListener(v -> { + // Gather fields and trim them + final @NotNull String name = edtName.getText().toString().trim(); + final @NotNull String email = edtEmail.getText().toString().trim(); + final @NotNull String message = edtMessage.getText().toString().trim(); + + // If a required field is missing, shows the error label + if (name.isEmpty() && feedbackOptions.isNameRequired()) { + edtName.setError(lblName.getText()); + return; + } - if (email.isEmpty() && feedbackOptions.isEmailRequired()) { - edtEmail.setError(lblEmail.getText()); - return; - } + if (email.isEmpty() && feedbackOptions.isEmailRequired()) { + edtEmail.setError(lblEmail.getText()); + return; + } - if (message.isEmpty()) { - edtMessage.setError(lblMessage.getText()); - return; - } + if (message.isEmpty()) { + edtMessage.setError(lblMessage.getText()); + return; + } - // Create the feedback object - final @NotNull Feedback feedback = new Feedback(message); - feedback.setName(name); - feedback.setContactEmail(email); - if (associatedEventId != null) { - feedback.setAssociatedEventId(associatedEventId); - } - if (currentReplayId != null) { - feedback.setReplayId(currentReplayId); - } + // Create the feedback object + final @NotNull Feedback feedback = new Feedback(message); + feedback.setName(name); + feedback.setContactEmail(email); + if (associatedEventId != null) { + feedback.setAssociatedEventId(associatedEventId); + } + if (currentReplayId != null) { + feedback.setReplayId(currentReplayId); + } - // Capture the feedback. If the ID is empty, it means that the feedback was not sent - final @NotNull Hint hint = new Hint(); - maybeAddImageAttachment(hint); - final @NotNull SentryId id = Sentry.feedback().capture(feedback, hint); - if (!id.equals(SentryId.EMPTY_ID)) { - Toast.makeText( - getContext(), feedbackOptions.getSuccessMessageText(), Toast.LENGTH_SHORT) - .show(); - final @Nullable SentryFeedbackOptions.SentryFeedbackCallback onSubmitSuccess = - feedbackOptions.getOnSubmitSuccess(); - if (onSubmitSuccess != null) { - try { - onSubmitSuccess.call(feedback); - } catch (Exception e) { - Sentry.getCurrentScopes() - .getOptions() - .getLogger() - .log(SentryLevel.ERROR, "onSubmitSuccess callback threw an exception.", e); - } - } - } else { - final @Nullable SentryFeedbackOptions.SentryFeedbackCallback onSubmitError = - feedbackOptions.getOnSubmitError(); - if (onSubmitError != null) { - try { - onSubmitError.call(feedback); - } catch (Exception e) { - Sentry.getCurrentScopes() - .getOptions() - .getLogger() - .log(SentryLevel.ERROR, "onSubmitError callback threw an exception.", e); - } - } + // Capture the feedback. If the ID is empty, it means that the feedback was not sent + final @NotNull Hint hint = new Hint(); + maybeAddImageAttachment(hint); + final @NotNull SentryId id = Sentry.feedback().capture(feedback, hint); + if (!id.equals(SentryId.EMPTY_ID)) { + Toast.makeText(getContext(), feedbackOptions.getSuccessMessageText(), Toast.LENGTH_SHORT) + .show(); + final @Nullable SentryFeedbackOptions.SentryFeedbackCallback onSubmitSuccess = + feedbackOptions.getOnSubmitSuccess(); + if (onSubmitSuccess != null) { + try { + onSubmitSuccess.call(feedback); + } catch (Exception e) { + Sentry.getCurrentScopes() + .getOptions() + .getLogger() + .log(SentryLevel.ERROR, "onSubmitSuccess callback threw an exception.", e); } - cancel(); - }); + } + } else { + final @Nullable SentryFeedbackOptions.SentryFeedbackCallback onSubmitError = + feedbackOptions.getOnSubmitError(); + if (onSubmitError != null) { + try { + onSubmitError.call(feedback); + } catch (Exception e) { + Sentry.getCurrentScopes() + .getOptions() + .getLogger() + .log(SentryLevel.ERROR, "onSubmitError callback threw an exception.", e); + } + } + } + cancel(); + }); btnCancel.setText(feedbackOptions.getCancelButtonLabel()); btnCancel.setOnClickListener(v -> cancel()); @@ -418,22 +417,19 @@ public void setOnDismissListener(final @Nullable OnDismissListener listener) { final @NotNull SentryOptions options = Sentry.getCurrentScopes().getOptions(); final @Nullable Runnable onFormClose = options.getFeedbackOptions().getOnFormClose(); if (onFormClose != null) { - super.setOnDismissListener( - dialog -> { - // User-provided callback: a crash in it must not take down the app or skip the - // cleanup and the user's own dismiss listener below - try { - onFormClose.run(); - } catch (Exception e) { - options - .getLogger() - .log(SentryLevel.ERROR, "onFormClose callback threw an exception.", e); - } - currentReplayId = null; - if (delegate != null) { - delegate.onDismiss(dialog); - } - }); + super.setOnDismissListener(dialog -> { + // User-provided callback: a crash in it must not take down the app or skip the + // cleanup and the user's own dismiss listener below + try { + onFormClose.run(); + } catch (Exception e) { + options.getLogger().log(SentryLevel.ERROR, "onFormClose callback threw an exception.", e); + } + currentReplayId = null; + if (delegate != null) { + delegate.onDismiss(dialog); + } + }); } else { super.setOnDismissListener(delegate); } @@ -666,7 +662,7 @@ public void show() { super.show(); } - public static class Builder { + public static final class Builder { @Nullable OptionsConfiguration configuration; @Nullable SentryFeedbackOptions.OptionsConfigurator configurator; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracing.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracing.java new file mode 100644 index 00000000000..b96eb5d97bd --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracing.java @@ -0,0 +1,272 @@ +package io.sentry.android.core; + +import static io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion; + +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.webkit.WebView; +import androidx.annotation.MainThread; +import io.sentry.BaggageHeader; +import io.sentry.ILogger; +import io.sentry.IScopes; +import io.sentry.Sentry; +import io.sentry.SentryLevel; +import io.sentry.SentryOptions; +import io.sentry.util.ExceptionUtils; +import io.sentry.util.LoadClass; +import io.sentry.util.TracingUtils; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Connects the app's trace with the trace of web content shown in a {@link WebView}. + * + *

{@link #addTracePropagation(WebView, List)} writes the current trace into every document the + * WebView loads from an allowed host as {@code sentry-trace} and {@code baggage} meta tags, before + * any page script runs. A {@code @sentry/browser} running in the page with {@code + * browserTracingIntegration} then continues the trace on pageload. + * + *

Requires the {@code androidx.webkit:webkit} dependency and an Android System WebView that + * supports {@code WebViewFeature.DOCUMENT_START_SCRIPT}. + */ +public final class SentryWebViewTracing { + + static final @NotNull String SCRIPT_HANDLER_CLASS_NAME = "androidx.webkit.ScriptHandler"; + + private static final @NotNull String INTEGRATION_NAME = "WebViewTracePropagation"; + + /** + * Counts, per WebView, the calls that finished replacing Sentry's script on the WebView's thread. + * Weak keys, so it doesn't keep WebViews alive. + */ + private static final @NotNull Map replacements = + Collections.synchronizedMap(new WeakHashMap<>()); + + private SentryWebViewTracing() {} + + /** + * Same as {@link #addTracePropagation(WebView, List)}, using the hosts set in {@link + * SentryWebViewTracingOptions#setAllowedHosts(List)}. If none are set, no page is connected and + * this returns false. + * + * @param webView the WebView to connect + * @return true if the trace propagation script was installed + */ + @MainThread + public static boolean addTracePropagation(final @NotNull WebView webView) { + final @NotNull IScopes scopes = Sentry.getCurrentScopes(); + final @NotNull SentryOptions options = scopes.getOptions(); + final @NotNull List allowedHosts = + options instanceof SentryAndroidOptions + ? ((SentryAndroidOptions) options).getWebViewTracing().getAllowedHosts() + : Collections.emptyList(); + return addTracePropagation(webView, allowedHosts, scopes, new LoadClass()); + } + + /** + * Same as {@link #addTracePropagation(WebView, List)}. + * + * @param webView the WebView to connect + * @param allowedHosts hosts whose pages receive the trace + * @return true if the trace propagation script was installed + */ + @MainThread + public static boolean addTracePropagation( + final @NotNull WebView webView, final @NotNull String... allowedHosts) { + return addTracePropagation(webView, Arrays.asList(allowedHosts)); + } + + /** + * Installs a script that writes the current trace into documents the WebView loads from an + * allowed host. Call it on the main thread, before loading a URL: it applies to documents that + * start loading after the call. + * + *

{@code allowedHosts} is a trust boundary: only list hosts whose content you control. A page + * matches when its hostname equals an entry or is a subdomain of it, over https. Entries are + * normalized, so a scheme, a path, and a trailing dot are ignored. A port other than 443 limits + * the entry to pages served on that port (for example {@code "example.com:8443"}). + * + *

The trace is a snapshot taken when this is called. To propagate a newer trace to a later + * page load, call this again: it replaces the script Sentry installed earlier and leaves other + * scripts alone. If the call fails, no Sentry script is left on the WebView. + * + *

The root span name ({@code sentry-transaction}) is removed from {@code baggage}, as it is + * free-form text that may carry user data. + * + * @param webView the WebView to connect + * @param allowedHosts hosts whose pages receive the trace + * @return true if the script was installed; false if androidx.webkit is missing, the WebView does + * not support document-start scripts, {@code allowedHosts} has no valid entry, or there is no + * trace (for example the SDK is not initialized), or it is called off the WebView's thread + */ + @MainThread + public static boolean addTracePropagation( + final @NotNull WebView webView, final @NotNull List allowedHosts) { + return addTracePropagation(webView, allowedHosts, Sentry.getCurrentScopes(), new LoadClass()); + } + + static boolean addTracePropagation( + final @NotNull WebView webView, + final @NotNull List allowedHosts, + final @NotNull IScopes scopes, + final @NotNull LoadClass loadClass) { + // Registered on use rather than on success, like the other SDKs, so adoption counts apps that + // wired the feature up even when this call cannot install. + addIntegrationToSdkVersion(INTEGRATION_NAME); + + if (!loadClass.isClassAvailable(SCRIPT_HANDLER_CLASS_NAME, scopes.getOptions())) { + scopes + .getOptions() + .getLogger() + .log( + SentryLevel.WARNING, + "WebView trace propagation requires the androidx.webkit dependency, skipping."); + return false; + } + return install(webView, allowedHosts, scopes, new AndroidxWebViewScriptInstaller()); + } + + static boolean install( + final @NotNull WebView webView, + final @NotNull List allowedHosts, + final @NotNull IScopes scopes, + final @NotNull WebViewScriptInstaller installer) { + final @NotNull ILogger logger = scopes.getOptions().getLogger(); + + // WebView methods throw when called off the WebView's thread; fail like any other misuse. + if (!isOnWebViewThread(webView)) { + logger.log( + SentryLevel.WARNING, + "addTracePropagation must be called on the WebView's thread, skipping WebView trace propagation."); + removeOnWebViewThread(webView, installer, logger); + return false; + } + + try { + return replaceScript(webView, allowedHosts, scopes, installer, logger); + } catch (LinkageError e) { + // androidx.webkit is compileOnly, so the version in the app's apk may be older than the one + // we compiled against and lack the APIs used here. + logger.log( + SentryLevel.WARNING, + "androidx.webkit is too old for WebView trace propagation, skipping.", + e); + return false; + } finally { + // Counted once the replacement is done, so an off-thread call made while it runs doesn't + // later remove the script it installed. Only written on the WebView's thread. + replacements.put(webView, replacementsOf(webView) + 1); + } + } + + private static boolean replaceScript( + final @NotNull WebView webView, + final @NotNull List allowedHosts, + final @NotNull IScopes scopes, + final @NotNull WebViewScriptInstaller installer, + final @NotNull ILogger logger) { + // Remove Sentry's previous script first, so a failed re-add never leaves a stale trace behind. + installer.removeInstalledScript(webView); + + final @NotNull List hosts = WebViewTracePropagationScript.normalizeHosts(allowedHosts); + if (hosts.isEmpty()) { + logger.log( + SentryLevel.WARNING, + "No valid allowedHosts provided, skipping WebView trace propagation."); + return false; + } + + if (!installer.isDocumentStartScriptSupported()) { + logger.log( + SentryLevel.WARNING, + "The WebView does not support document-start scripts, skipping WebView trace propagation."); + return false; + } + + final @Nullable TracingUtils.TracingHeaders headers = + TracingUtils.trace(scopes, null, scopes.getSpan()); + if (headers == null) { + logger.log( + SentryLevel.DEBUG, + "No trace available (the SDK is disabled or not initialized), skipping WebView trace propagation."); + return false; + } + + final @Nullable BaggageHeader baggageHeader = headers.getBaggageHeader(); + final @Nullable String baggage = + WebViewTracePropagationScript.stripTransactionFromBaggage( + baggageHeader == null ? null : baggageHeader.getValue()); + final @NotNull String script = + WebViewTracePropagationScript.build( + hosts, headers.getSentryTraceHeader().getValue(), baggage); + + try { + if (!installer.installScript( + webView, script, WebViewTracePropagationScript.originRules(allowedHosts))) { + logger.log( + SentryLevel.WARNING, + "The WebView does not support document-start scripts, skipping WebView trace propagation."); + return false; + } + } catch (IllegalArgumentException e) { + logger.log( + SentryLevel.WARNING, "Invalid allowedHosts, skipping WebView trace propagation.", e); + return false; + } + + return true; + } + + /** + * A failed call must not leave a stale trace behind, but off the WebView's thread the script can + * only be removed later, on that thread. The removal is skipped if a call on the WebView's thread + * replaced this WebView's script in the meantime, so it never removes a newer script. + */ + private static void removeOnWebViewThread( + final @NotNull WebView webView, + final @NotNull WebViewScriptInstaller installer, + final @NotNull ILogger logger) { + final long replacementsSeen = replacementsOf(webView); + new Handler(webViewLooper(webView)) + .post(() -> { + if (replacementsOf(webView) != replacementsSeen) { + return; + } + // Runs outside of any app call, so only fatal errors may escape: for example, the + // WebView may have been destroyed since. + try { + installer.removeInstalledScript(webView); + } catch (LinkageError e) { + logger.log( + SentryLevel.WARNING, + "androidx.webkit is too old for WebView trace propagation, skipping.", + e); + } catch (Throwable e) { + ExceptionUtils.rethrowIfFatal(e); + logger.log( + SentryLevel.WARNING, "Failed to remove the WebView trace propagation script.", e); + } + }); + } + + private static long replacementsOf(final @NotNull WebView webView) { + final @Nullable Long count = replacements.get(webView); + return count == null ? 0 : count; + } + + private static boolean isOnWebViewThread(final @NotNull WebView webView) { + return Looper.myLooper() == webViewLooper(webView); + } + + private static @NotNull Looper webViewLooper(final @NotNull WebView webView) { + return Build.VERSION.SDK_INT >= Build.VERSION_CODES.P + ? webView.getWebViewLooper() + : Looper.getMainLooper(); + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracingOptions.java b/sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracingOptions.java new file mode 100644 index 00000000000..ffc175b7401 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SentryWebViewTracingOptions.java @@ -0,0 +1,34 @@ +package io.sentry.android.core; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.jetbrains.annotations.NotNull; + +/** Options for connecting the app's trace with web content in a {@code WebView}. */ +public final class SentryWebViewTracingOptions { + + private @NotNull List allowedHosts = Collections.emptyList(); + + /** + * Returns the hosts {@link SentryWebViewTracing#addTracePropagation(android.webkit.WebView)} + * propagates the trace to. + * + * @return the allowed hosts, empty by default + */ + public @NotNull List getAllowedHosts() { + return allowedHosts; + } + + /** + * Sets the hosts {@link SentryWebViewTracing#addTracePropagation(android.webkit.WebView)} + * propagates the trace to. This is a trust boundary: only list hosts whose content you control. + * It is separate from {@code tracePropagationTargets}, which controls outgoing HTTP requests. + * + * @param allowedHosts the allowed hosts, matched like the ones passed to {@link + * SentryWebViewTracing#addTracePropagation(android.webkit.WebView, List)} + */ + public void setAllowedHosts(final @NotNull List allowedHosts) { + this.allowedHosts = new ArrayList<>(allowedHosts); + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SpanFrameMetricsCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/SpanFrameMetricsCollector.java index 8994fba74d1..df2f6d89d83 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SpanFrameMetricsCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SpanFrameMetricsCollector.java @@ -23,7 +23,7 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class SpanFrameMetricsCollector +public final class SpanFrameMetricsCollector implements IPerformanceContinuousCollector, SentryFrameMetricsCollector.FrameMetricsCollectorListener { @@ -35,29 +35,28 @@ public class SpanFrameMetricsCollector private static final SentryNanotimeDate EMPTY_NANO_TIME = new SentryNanotimeDate(0, 0); private final boolean enabled; - protected final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); + final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); private final @NotNull SentryFrameMetricsCollector frameMetricsCollector; private volatile @Nullable String listenerId; // all running spans, sorted by span start nano time private final @NotNull SortedSet runningSpans = - new TreeSet<>( - (o1, o2) -> { - if (o1 == o2) { - return 0; - } - int timeDiff = o1.getStartDate().compareTo(o2.getStartDate()); - if (timeDiff != 0) { - return timeDiff; - } - // TreeSet uses compareTo to check for duplicates, so ensure that - // two non-equal spans with the same start date are not considered equal - return o1.getSpanContext() - .getSpanId() - .toString() - .compareTo(o2.getSpanContext().getSpanId().toString()); - }); + new TreeSet<>((o1, o2) -> { + if (o1 == o2) { + return 0; + } + int timeDiff = o1.getStartDate().compareTo(o2.getStartDate()); + if (timeDiff != 0) { + return timeDiff; + } + // TreeSet uses compareTo to check for duplicates, so ensure that + // two non-equal spans with the same start date are not considered equal + return o1.getSpanContext() + .getSpanId() + .toString() + .compareTo(o2.getSpanContext().getSpanId().toString()); + }); // all collected frames, sorted by frame end time // this is a concurrent set, as the frames are added on the main thread, diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java index 3f45a9a9fb8..b3caf622c37 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegration.java @@ -35,7 +35,6 @@ import io.sentry.Integration; import io.sentry.SentryLevel; import io.sentry.SentryOptions; -import io.sentry.android.core.internal.util.AndroidCurrentDateProvider; import io.sentry.android.core.internal.util.Debouncer; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.Objects; @@ -66,8 +65,7 @@ public final class SystemEventsBreadcrumbsIntegration private final @NotNull String[] actions; private volatile boolean isClosed = false; private volatile boolean isStopped = false; - private volatile IntentFilter filter = null; - private volatile HandlerThread handlerThread = null; + private volatile @Nullable HandlerThread handlerThread = null; private final @NotNull AtomicBoolean isReceiverRegistered = new AtomicBoolean(false); private final @NotNull AutoClosableReentrantLock receiverLock = new AutoClosableReentrantLock(); // Track previous battery state to avoid duplicate breadcrumbs when values haven't changed @@ -124,6 +122,7 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions } } + @SuppressWarnings("FutureReturnValueIgnored") private void registerReceiver( final @NotNull IScopes scopes, final @NotNull SentryAndroidOptions options) { @@ -138,55 +137,52 @@ private void registerReceiver( try { options .getExecutorService() - .submit( - () -> { - try (final @NotNull ISentryLifecycleToken ignored = receiverLock.acquire()) { - if (isClosed || isStopped || receiver != null) { - return; - } + .submit(() -> { + try (final @NotNull ISentryLifecycleToken ignored = receiverLock.acquire()) { + if (isClosed || isStopped || receiver != null) { + return; + } - receiver = new SystemEventsBroadcastReceiver(scopes, options); - if (filter == null) { - filter = new IntentFilter(); - for (String item : actions) { - filter.addAction(item); - } - } - if (customHandler == null && handlerThread == null) { + receiver = new SystemEventsBroadcastReceiver(scopes, options); + final @NotNull IntentFilter filter = new IntentFilter(); + for (String item : actions) { + filter.addAction(item); + } + try { + // registerReceiver can throw SecurityException but it's not documented in the + // official docs + + // onReceive will be called on this handler thread + @NotNull Handler handler; + if (customHandler != null) { + handler = customHandler; + } else { + if (handlerThread == null) { handlerThread = new HandlerThread( "SystemEventsReceiver", Process.THREAD_PRIORITY_BACKGROUND); handlerThread.start(); } - try { - // registerReceiver can throw SecurityException but it's not documented in the - // official docs - - // onReceive will be called on this handler thread - @NotNull Handler handler; - if (customHandler != null) { - handler = customHandler; - } else { - handler = new Handler(handlerThread.getLooper()); - } - ContextUtils.registerReceiver(context, options, receiver, filter, handler); - if (!isReceiverRegistered.getAndSet(true)) { - options - .getLogger() - .log(SentryLevel.DEBUG, "SystemEventsBreadcrumbsIntegration installed."); - addIntegrationToSdkVersion("SystemEventsBreadcrumbs"); - } - } catch (Throwable e) { - options.setEnableSystemEventBreadcrumbs(false); - options - .getLogger() - .log( - SentryLevel.ERROR, - "Failed to initialize SystemEventsBreadcrumbsIntegration.", - e); - } + handler = new Handler(handlerThread.getLooper()); + } + ContextUtils.registerReceiver(context, options, receiver, filter, handler); + if (!isReceiverRegistered.getAndSet(true)) { + options + .getLogger() + .log(SentryLevel.DEBUG, "SystemEventsBreadcrumbsIntegration installed."); + addIntegrationToSdkVersion("SystemEventsBreadcrumbs"); } - }); + } catch (Throwable e) { + options.setEnableSystemEventBreadcrumbs(false); + options + .getLogger() + .log( + SentryLevel.ERROR, + "Failed to initialize SystemEventsBreadcrumbsIntegration.", + e); + } + } + }); } catch (Throwable e) { options .getLogger() @@ -196,8 +192,12 @@ private void registerReceiver( } } - @SuppressWarnings("Convert2MethodRef") // older AGP versions do not support method references + @SuppressWarnings({ + "Convert2MethodRef", + "FutureReturnValueIgnored" + }) // older AGP versions do not support method references private void scheduleUnregisterReceiver() { + final @Nullable SentryAndroidOptions options = this.options; if (options == null) { return; } @@ -233,7 +233,6 @@ private void unregisterReceiver(final @NotNull SentryAndroidOptions options) { public void close() throws IOException { try (final @NotNull ISentryLifecycleToken ignored = receiverLock.acquire()) { isClosed = true; - filter = null; if (handlerThread != null) { handlerThread.quit(); } @@ -299,15 +298,14 @@ final class SystemEventsBroadcastReceiver extends BroadcastReceiver { private final @NotNull IScopes scopes; private final @NotNull SentryAndroidOptions options; - // TODO: JAVA-729 - @SuppressWarnings("deprecation") - private final @NotNull Debouncer batteryChangedDebouncer = - new Debouncer(AndroidCurrentDateProvider.getInstance(), DEBOUNCE_WAIT_TIME_MS, 0); + private final @NotNull Debouncer batteryChangedDebouncer; SystemEventsBroadcastReceiver( final @NotNull IScopes scopes, final @NotNull SentryAndroidOptions options) { this.scopes = scopes; this.options = options; + this.batteryChangedDebouncer = + new Debouncer(options.getMonotonicTicker(), DEBOUNCE_WAIT_TIME_MS, 0); } @Override diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java index 43de4034ec5..88f83fd2993 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/TombstoneIntegration.java @@ -49,7 +49,7 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class TombstoneIntegration implements Integration, Closeable { +public final class TombstoneIntegration implements Integration, Closeable { private final @NotNull Context context; private final @NotNull ICurrentDateProvider dateProvider; private @Nullable SentryAndroidOptions options; @@ -67,6 +67,7 @@ public TombstoneIntegration(final @NotNull Context context) { } @Override + @SuppressWarnings("FutureReturnValueIgnored") public void register(@NotNull IScopes scopes, @NotNull SentryOptions options) { this.options = Objects.requireNonNull( @@ -114,7 +115,7 @@ public void close() throws IOException { } @ApiStatus.Internal - public static class TombstonePolicy implements ApplicationExitInfoPolicy { + public static final class TombstonePolicy implements ApplicationExitInfoPolicy { private final @NotNull SentryAndroidOptions options; private final @NotNull NativeEventCollector nativeEventCollector; @@ -289,7 +290,7 @@ private void addNativeAttachmentsToTombstoneHint( } } - private void mergeNativeCrashes( + public static void mergeNativeCrashes( final @NotNull SentryEvent nativeEvent, final @NotNull SentryEvent tombstoneEvent) { // we take the event data verbatim from the Native SDK and only apply tombstone data where we // are sure that it will improve the outcome: diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java index ffd3323e601..4004310a3ff 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/ViewHierarchyEventProcessor.java @@ -13,7 +13,6 @@ import io.sentry.SentryEvent; import io.sentry.SentryLevel; import io.sentry.android.core.internal.gestures.ViewUtils; -import io.sentry.android.core.internal.util.AndroidCurrentDateProvider; import io.sentry.android.core.internal.util.AndroidThreadChecker; import io.sentry.android.core.internal.util.ClassUtil; import io.sentry.android.core.internal.util.Debouncer; @@ -47,15 +46,10 @@ public final class ViewHierarchyEventProcessor implements SentryEventProcessor { private static final long DEBOUNCE_WAIT_TIME_MS = 2000; private static final int DEBOUNCE_MAX_EXECUTIONS = 3; - // TODO: JAVA-729 - @SuppressWarnings("deprecation") public ViewHierarchyEventProcessor(final @NotNull SentryAndroidOptions options) { this.options = Objects.requireNonNull(options, "SentryAndroidOptions is required"); this.debouncer = - new Debouncer( - AndroidCurrentDateProvider.getInstance(), - DEBOUNCE_WAIT_TIME_MS, - DEBOUNCE_MAX_EXECUTIONS); + new Debouncer(options.getMonotonicTicker(), DEBOUNCE_WAIT_TIME_MS, DEBOUNCE_MAX_EXECUTIONS); if (options.isAttachViewHierarchy()) { addIntegrationToSdkVersion("ViewHierarchy"); @@ -125,7 +119,7 @@ public ViewHierarchyEventProcessor(final @NotNull SentryAndroidOptions options) return event; } - public static byte[] snapshotViewHierarchyAsData( + public static byte @Nullable [] snapshotViewHierarchyAsData( @Nullable Activity activity, @NotNull IThreadChecker threadChecker, @NotNull ISerializer serializer, @@ -191,15 +185,14 @@ public static ViewHierarchy snapshotViewHierarchy( } else { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference viewHierarchy = new AtomicReference<>(null); - activity.runOnUiThread( - () -> { - try { - viewHierarchy.set(snapshotViewHierarchy(decorView, exporters)); - latch.countDown(); - } catch (Throwable t) { - logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", t); - } - }); + activity.runOnUiThread(() -> { + try { + viewHierarchy.set(snapshotViewHierarchy(decorView, exporters)); + latch.countDown(); + } catch (Throwable t) { + logger.log(SentryLevel.ERROR, "Failed to process view hierarchy.", t); + } + }); if (latch.await(CAPTURE_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { return viewHierarchy.get(); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/WebViewScriptInstaller.java b/sentry-android-core/src/main/java/io/sentry/android/core/WebViewScriptInstaller.java new file mode 100644 index 00000000000..36d92588fbc --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/WebViewScriptInstaller.java @@ -0,0 +1,26 @@ +package io.sentry.android.core; + +import android.webkit.WebView; +import java.util.Set; +import org.jetbrains.annotations.NotNull; + +/** + * Installs Sentry's document-start script on a WebView. Declares no androidx.webkit types, so it + * can be referenced before the androidx.webkit availability check. + */ +interface WebViewScriptInstaller { + + boolean isDocumentStartScriptSupported(); + + /** Removes the script Sentry installed earlier on this WebView, if any. */ + void removeInstalledScript(@NotNull WebView webView); + + /** + * Installs the script for documents whose origin matches one of the rules. + * + * @return false if document-start scripts are not supported, in which case nothing is installed + * @throws IllegalArgumentException if an origin rule is malformed + */ + boolean installScript( + @NotNull WebView webView, @NotNull String script, @NotNull Set allowedOriginRules); +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/WebViewTracePropagationScript.java b/sentry-android-core/src/main/java/io/sentry/android/core/WebViewTracePropagationScript.java new file mode 100644 index 00000000000..5a22ea69388 --- /dev/null +++ b/sentry-android-core/src/main/java/io/sentry/android/core/WebViewTracePropagationScript.java @@ -0,0 +1,291 @@ +package io.sentry.android.core; + +import java.net.IDN; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Builds the script that writes the native trace into a WebView document as {@code sentry-trace} + * and {@code baggage} meta tags, plus the origin rules that gate where it runs. Has no androidx + * dependency so it can be used before the androidx.webkit availability check. + */ +final class WebViewTracePropagationScript { + + /** + * {@code baggage} key carrying the root span's name. It is free-form text and can contain user + * data (for example a parameterized URL), so it is removed before it reaches the WebView page. + */ + private static final @NotNull String SENTRY_TRANSACTION_BAGGAGE_KEY = "sentry-transaction"; + + private static final @NotNull Pattern SCHEME = + Pattern.compile("^[a-z][a-z0-9+.-]*://", Pattern.CASE_INSENSITIVE); + private static final @NotNull Pattern PORT = Pattern.compile(":\\d+$"); + private static final @NotNull Pattern IPV4 = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}$"); + + private WebViewTracePropagationScript() {} + + /** + * Normalizes each entry with {@link #normalizeHost(String)}, dropping blank entries and + * duplicates. + */ + static @NotNull List normalizeHosts(final @NotNull Collection allowedHosts) { + final @NotNull Set normalized = new LinkedHashSet<>(); + for (final @Nullable String host : allowedHosts) { + if (host == null) { + continue; + } + final @NotNull String normalizedHost = normalizeHost(host); + if (!normalizedHost.isEmpty()) { + normalized.add(normalizedHost); + } + } + return new ArrayList<>(normalized); + } + + /** + * Normalizes an {@code allowedHosts} entry to a bare lowercase hostname so it can be compared + * against the page's {@code location.hostname}. Tolerates surrounding whitespace, a scheme, a + * path, a port, a trailing dot, and a leading subdomain wildcard (e.g. {@code " + * https://*.App.Example.com:8080/x "} becomes {@code "app.example.com"}). IPv6 literals are + * bracketed to match {@code location.hostname} ({@code "::1"} becomes {@code "[::1]"}), and + * internationalized hostnames are converted to punycode ({@code "münchen.de"} becomes {@code + * "xn--mnchen-3ya.de"}). + */ + static @NotNull String normalizeHost(final @NotNull String host) { + String hostAndPort = SCHEME.matcher(host.trim()).replaceFirst(""); + + final int pathStart = indexOfAny(hostAndPort, "/?#"); + if (pathStart != -1) { + hostAndPort = hostAndPort.substring(0, pathStart); + } + + // Strip the port without mistaking an IPv6 hextet for one. + final int closingBracket = hostAndPort.indexOf(']'); + if (closingBracket != -1) { + hostAndPort = hostAndPort.substring(0, closingBracket + 1); + } else if (hostAndPort.indexOf(':') != hostAndPort.lastIndexOf(':')) { + hostAndPort = "[" + hostAndPort + "]"; + } else { + hostAndPort = PORT.matcher(hostAndPort).replaceFirst(""); + } + + if (hostAndPort.endsWith(".")) { + hostAndPort = hostAndPort.substring(0, hostAndPort.length() - 1); + } + // Subdomains always match, so a subdomain wildcard is redundant. Kept, it would never match + // the page's hostname and would make the origin rules invalid. + while (hostAndPort.startsWith("*.")) { + hostAndPort = hostAndPort.substring(2); + } + return toAscii(hostAndPort.toLowerCase(Locale.ROOT)); + } + + /** + * Converts an internationalized hostname to the ASCII (punycode) form the page's {@code + * location.hostname} uses, e.g. {@code "münchen.de"} becomes {@code "xn--mnchen-3ya.de"}. Returns + * an empty string, so the entry is dropped, if the hostname cannot be converted. + */ + private static @NotNull String toAscii(final @NotNull String host) { + if (isAscii(host)) { + return host; + } + try { + return IDN.toASCII(host, IDN.ALLOW_UNASSIGNED).toLowerCase(Locale.ROOT); + } catch (IllegalArgumentException e) { + return ""; + } + } + + private static boolean isAscii(final @NotNull String value) { + for (int i = 0; i < value.length(); i++) { + if (value.charAt(i) > 0x7f) { + return false; + } + } + return true; + } + + /** + * Origin rules for {@code WebViewCompat.addDocumentStartJavaScript}: each host and its subdomains + * over https. IP literals cannot take a subdomain wildcard. A rule without a port only matches + * port 443, so a non-default port given in an entry is kept and limits the rule to that port. + */ + static @NotNull Set originRules(final @NotNull Collection allowedHosts) { + final @NotNull Set rules = new LinkedHashSet<>(); + for (final @Nullable String entry : allowedHosts) { + if (entry == null) { + continue; + } + final @NotNull String host = normalizeHost(entry); + if (host.isEmpty()) { + continue; + } + final @Nullable String port = port(entry); + final @NotNull String portSuffix = port == null || "443".equals(port) ? "" : ":" + port; + rules.add("https://" + host + portSuffix); + if (!isIpLiteral(host)) { + rules.add("https://*." + host + portSuffix); + } + } + return rules; + } + + /** Returns the port of an {@code allowedHosts} entry, or null if it has none. */ + private static @Nullable String port(final @NotNull String entry) { + String hostAndPort = SCHEME.matcher(entry.trim()).replaceFirst(""); + final int pathStart = indexOfAny(hostAndPort, "/?#"); + if (pathStart != -1) { + hostAndPort = hostAndPort.substring(0, pathStart); + } + + final int closingBracket = hostAndPort.indexOf(']'); + final @NotNull String afterHost; + if (closingBracket != -1) { + afterHost = hostAndPort.substring(closingBracket + 1); + } else if (hostAndPort.indexOf(':') != hostAndPort.lastIndexOf(':')) { + // An unbracketed IPv6 literal has no port. + return null; + } else { + final int colon = hostAndPort.indexOf(':'); + afterHost = colon == -1 ? "" : hostAndPort.substring(colon); + } + final @NotNull Matcher matcher = PORT.matcher(afterHost); + return matcher.matches() ? afterHost.substring(1) : null; + } + + /** + * Removes the {@code sentry-transaction} entry from a {@code baggage} header, keeping every other + * entry. Returns null when nothing is left to propagate. + */ + static @Nullable String stripTransactionFromBaggage(final @Nullable String baggage) { + if (baggage == null) { + return null; + } + final @NotNull StringBuilder result = new StringBuilder(); + for (final @NotNull String entry : baggage.split(",", -1)) { + final @NotNull String trimmed = entry.trim(); + if (trimmed.isEmpty()) { + continue; + } + final int separator = trimmed.indexOf('='); + final @NotNull String key = separator == -1 ? trimmed : trimmed.substring(0, separator); + if (SENTRY_TRANSACTION_BAGGAGE_KEY.equals(key.trim())) { + continue; + } + if (result.length() > 0) { + result.append(','); + } + result.append(trimmed); + } + return result.length() == 0 ? null : result.toString(); + } + + /** + * Builds the script run at document start. Values are embedded as escaped string literals so any + * character in them stays inert. The script only writes the tags in the main frame of a page + * whose hostname is (a subdomain of) an allowed host, and does nothing if a {@code sentry-trace} + * meta tag already exists. + */ + static @NotNull String build( + final @NotNull List normalizedHosts, + final @NotNull String sentryTrace, + final @Nullable String baggage) { + final @NotNull StringBuilder allowed = new StringBuilder("["); + for (int i = 0; i < normalizedHosts.size(); i++) { + if (i > 0) { + allowed.append(','); + } + allowed.append(toJsStringLiteral(normalizedHosts.get(i))); + } + allowed.append(']'); + + return "(function(){try{\n" + + "if(window.top!==window)return;\n" + + "var allowed=" + + allowed + + ";\n" + + "var host=(window.location&&window.location.hostname||'').toLowerCase();\n" + + "if(!host)return;\n" + + "if(!allowed.some(function(h){return host===h||host.slice(-(h.length+1))==='.'+h;}))return;\n" + + "if(document.querySelector('meta[name=\"sentry-trace\"]'))return;\n" + + "var head=document.head||document.documentElement;\n" + + "if(!head)return;\n" + + "var set=function(n,c){if(!c)return;var m=document.createElement('meta');" + + "m.setAttribute('name',n);m.setAttribute('content',c);head.appendChild(m);};\n" + + "set('sentry-trace'," + + toJsStringLiteral(sentryTrace) + + ");\n" + + "set('baggage'," + + (baggage == null ? "null" : toJsStringLiteral(baggage)) + + ");\n" + + "}catch(e){}})();"; + } + + /** + * Escapes a value as a double-quoted JavaScript string literal, like {@code JSON.stringify}. + * Additionally escapes U+2028/U+2029 (line terminators in pre-ES2019 engines) and {@code <} so + * the literal stays inert in any embedding context. + */ + static @NotNull String toJsStringLiteral(final @NotNull String value) { + final @NotNull StringBuilder sb = new StringBuilder(value.length() + 2); + sb.append('"'); + for (int i = 0; i < value.length(); i++) { + final char c = value.charAt(i); + switch (c) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + case '<': + case '
': + case '
': + appendUnicodeEscape(sb, c); + break; + default: + if (c < 0x20) { + appendUnicodeEscape(sb, c); + } else { + sb.append(c); + } + } + } + sb.append('"'); + return sb.toString(); + } + + private static void appendUnicodeEscape(final @NotNull StringBuilder sb, final char c) { + sb.append(String.format(Locale.ROOT, "\\u%04x", (int) c)); + } + + private static boolean isIpLiteral(final @NotNull String host) { + return host.startsWith("[") || IPV4.matcher(host).matches(); + } + + private static int indexOfAny(final @NotNull String value, final @NotNull String chars) { + for (int i = 0; i < value.length(); i++) { + if (chars.indexOf(value.charAt(i)) != -1) { + return i; + } + } + return -1; + } +} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AggregatedStackTrace.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AggregatedStackTrace.java index 99eeeb7e004..aeb73c51cd3 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AggregatedStackTrace.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AggregatedStackTrace.java @@ -5,7 +5,7 @@ import org.jetbrains.annotations.NotNull; @ApiStatus.Internal -public class AggregatedStackTrace { +public final class AggregatedStackTrace { // the number of frames of the stacktrace final int depth; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrCulpritIdentifier.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrCulpritIdentifier.java index 447cb106ce1..31169b8be91 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrCulpritIdentifier.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrCulpritIdentifier.java @@ -10,7 +10,7 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class AnrCulpritIdentifier { +public final class AnrCulpritIdentifier { // common Java and Android packages who are less relevant for being the actual culprit private static final List systemAndFrameworkPackages = new ArrayList<>(11); @@ -89,8 +89,9 @@ public boolean equals(final Object obj) { } /** + * Returns the most common occurring stacktrace identified as the culprit. + * * @param stacks a list of stack traces to analyze - * @return the most common occurring stacktrace identified as the culprit */ @Nullable public static AggregatedStackTrace identify(final @NotNull List stacks) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfile.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfile.java index 19999683905..728b02d80de 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfile.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfile.java @@ -7,7 +7,7 @@ import org.jetbrains.annotations.NotNull; @ApiStatus.Internal -public class AnrProfile { +public final class AnrProfile { public final List stacks; public final long startTimeMs; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java index 7e3e1fd514e..dd3cffc3ffc 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileManager.java @@ -20,7 +20,7 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class AnrProfileManager implements AutoCloseable { +public final class AnrProfileManager implements AutoCloseable { private static final int MAX_NUM_STACKTRACES = (int) ((THRESHOLD_ANR_MS / POLLING_INTERVAL_MS) * 2); @@ -61,7 +61,7 @@ public AnrProfileManager(final @NotNull SentryOptions options, final @NotNull Fi queueFile, new ObjectQueue.Converter() { @Override - public AnrStackTrace from(final byte[] source) throws IOException { + public @Nullable AnrStackTrace from(final byte[] source) throws IOException { // no need to close the streams since they are backed by byte arrays and don't // hold any resources final @NotNull ByteArrayInputStream bis = new ByteArrayInputStream(source); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java index 761309f1670..204d4c5c650 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfileRotationHelper.java @@ -10,7 +10,7 @@ * concurrent access to the same QueueFile. */ @ApiStatus.Internal -public class AnrProfileRotationHelper { +public final class AnrProfileRotationHelper { private static final String RECORDING_FILE_NAME = "anr_profile"; private static final String OLD_FILE_NAME = "anr_profile_old"; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java index 1a8552c51a8..018fd49f6fd 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrProfilingIntegration.java @@ -37,7 +37,7 @@ *

Enable via {@link SentryAndroidOptions#setAnrProfilingSampleRate(Double)} or the {@code * io.sentry.anr.profiling.sample-rate} manifest metadata. */ -public class AnrProfilingIntegration +public final class AnrProfilingIntegration implements Integration, Closeable, AppState.AppStateListener, Runnable { public static final long POLLING_INTERVAL_MS = 66; @@ -103,6 +103,7 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions } @Override + @SuppressWarnings("FutureReturnValueIgnored") public void close() throws IOException { enabled.set(false); AppState.getInstance().removeAppStateListener(this); @@ -131,18 +132,17 @@ public void close() throws IOException { if (opts != null) { try { opts.getExecutorService() - .submit( - () -> { - if (pm == null) { - return; - } - - try { - pm.close(); - } catch (IOException e) { - logger.log(SentryLevel.WARNING, "Failed to close AnrProfileManager"); - } - }); + .submit(() -> { + if (pm == null) { + return; + } + + try { + pm.close(); + } catch (IOException e) { + logger.log(SentryLevel.WARNING, "Failed to close AnrProfileManager"); + } + }); } catch (Throwable e) { logger.log(SentryLevel.WARNING, "Failed to submit AnrProfileManager close"); } @@ -229,7 +229,7 @@ public void run() { } @ApiStatus.Internal - protected void checkMainThread(final @NotNull Thread mainThread) throws IOException { + void checkMainThread(final @NotNull Thread mainThread) throws IOException { if (debugManager != null && debugManager.isDebuggerConnected()) { // The main thread can sit at a breakpoint for a long time, which is not an ANR. Reset the // timestamp, so the paused time does not count against us after the debugger detaches. @@ -303,13 +303,13 @@ protected void checkMainThread(final @NotNull Thread mainThread) throws IOExcept @TestOnly @NotNull - protected MainThreadState getState() { + MainThreadState getState() { return mainThreadState; } @TestOnly @NotNull - protected AnrProfileManager getProfileManager() { + AnrProfileManager getProfileManager() { try (final @NotNull ISentryLifecycleToken ignored = profileManagerLock.acquire()) { if (profileManager == null) { final @NotNull SentryOptions opts = diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrStackTrace.java b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrStackTrace.java index 2d165c501bf..b8dfbdeec0f 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrStackTrace.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/anr/AnrStackTrace.java @@ -16,10 +16,17 @@ public final class AnrStackTrace implements Comparable { public final StackTraceElement[] stack; public final long timestampMs; + public final @Nullable Thread.State state; public AnrStackTrace(final long timestampMs, final StackTraceElement[] stack) { + this(timestampMs, stack, null); + } + + public AnrStackTrace( + final long timestampMs, final StackTraceElement[] stack, final @Nullable Thread.State state) { this.timestampMs = timestampMs; this.stack = stack; + this.state = state; } @Override @@ -27,9 +34,32 @@ public int compareTo(final @NotNull AnrStackTrace o) { return Long.compare(timestampMs, o.timestampMs); } + /** + * Writes this sample in format version 2. All numbers are big-endian, and strings use the + * modified UTF-8 of {@link DataOutputStream#writeUTF(String)}. + * + *

+   * short   version (2)
+   * long    timestampMs
+   * boolean isStateNull
+   * UTF     state name, or "" if isStateNull
+   * int     number of frames
+   * for each frame:
+   *   UTF     className
+   *   UTF     methodName
+   *   boolean isFileNameNull
+   *   UTF     fileName, or "" if isFileNameNull
+   *   int     lineNumber
+   * 
+ * + *

Version 1 is the same without the two state fields. {@link #deserialize(DataInputStream)} + * reads both versions. + */ public void serialize(final @NotNull DataOutputStream dos) throws IOException { - dos.writeShort(1); // version + dos.writeShort(2); // version dos.writeLong(timestampMs); + dos.writeBoolean(state == null); + dos.writeUTF(state == null ? "" : state.name()); dos.writeInt(stack.length); for (final @NotNull StackTraceElement element : stack) { dos.writeUTF(StringUtils.getOrEmpty(element.getClassName())); @@ -46,8 +76,20 @@ public void serialize(final @NotNull DataOutputStream dos) throws IOException { public static AnrStackTrace deserialize(final @NotNull DataInputStream dis) throws IOException { try { final short version = dis.readShort(); - if (version == 1) { + if (version == 1 || version == 2) { final long timestampMs = dis.readLong(); + @Nullable Thread.State state = null; + if (version == 2) { + final boolean isStateNull = dis.readBoolean(); + final @NotNull String stateName = dis.readUTF(); + if (!isStateNull) { + try { + state = Thread.State.valueOf(stateName); + } catch (IllegalArgumentException e) { + // written by a runtime with a state this one does not know + } + } + } final int stackLength = dis.readInt(); if (stackLength < 0 || stackLength > MAX_STACK_LENGTH) { return null; @@ -67,7 +109,7 @@ public static AnrStackTrace deserialize(final @NotNull DataInputStream dis) thro stack[i] = element; } - return new AnrStackTrace(timestampMs, stack); + return new AnrStackTrace(timestampMs, stack, state); } else { // unsupported future version return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/cache/AndroidEnvelopeCache.java b/sentry-android-core/src/main/java/io/sentry/android/core/cache/AndroidEnvelopeCache.java index 81af4f4f828..3a9fe794301 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/cache/AndroidEnvelopeCache.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/cache/AndroidEnvelopeCache.java @@ -256,7 +256,7 @@ void handle(final @NotNull Hint hint, final @NotNull SentryAndroidOptions option HintUtils.runIfHasType( hint, type, - (typedHint) -> { + typedHint -> { final @NotNull Long timestamp = timestampProvider.extract(typedHint); options .getLogger() diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/AndroidViewGestureTargetLocator.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/AndroidViewGestureTargetLocator.java index 5f6187cd39a..5799f262ecb 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/AndroidViewGestureTargetLocator.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/AndroidViewGestureTargetLocator.java @@ -40,7 +40,7 @@ && isViewScrollable(view, isAndroidXAvailable.getValue())) { return null; } - private UiElement createUiElement(final @NotNull View targetView) { + private @Nullable UiElement createUiElement(final @NotNull View targetView) { final @Nullable String resourceName = ViewUtils.getResourceIdOrNull(targetView); if (resourceName == null) { return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryGestureListener.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryGestureListener.java index 61a32b675db..b7891743c51 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryGestureListener.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/gestures/SentryGestureListener.java @@ -144,7 +144,7 @@ public boolean onScroll( } else { options .getLogger() - .log(SentryLevel.DEBUG, "Scroll target found: " + target.getIdentifier()); + .log(SentryLevel.DEBUG, "Scroll target found: %s", target.getIdentifier()); } scrollState.setTarget(target); @@ -226,9 +226,8 @@ private void startTracing(final @NotNull UiElement target, final @NotNull Gestur .getLogger() .log( SentryLevel.DEBUG, - "The view with id: " - + viewIdentifier - + " already has an ongoing transaction assigned. Rescheduling finish"); + "The view with id: %s already has an ongoing transaction assigned. Rescheduling finish", + viewIdentifier); final Long idleTimeout = options.getIdleTimeout(); if (idleTimeout != null) { @@ -280,10 +279,9 @@ private void startTracing(final @NotNull UiElement target, final @NotNull Gestur scopes.startTransaction( new TransactionContext(name, TransactionNameSource.COMPONENT, op), transactionOptions); - scopes.configureScope( - scope -> { - applyScope(scope, transaction); - }); + scopes.configureScope(scope -> { + applyScope(scope, transaction); + }); activeTransaction = transaction; activeUiElement = target; @@ -300,12 +298,11 @@ void stopTracing(final @NotNull SpanStatus status) { activeTransaction.finish(); } } - scopes.configureScope( - scope -> { - // avoid method refs on Android due to some issues with older AGP setups - // noinspection Convert2MethodRef - clearScope(scope); - }); + scopes.configureScope(scope -> { + // avoid method refs on Android due to some issues with older AGP setups + // noinspection Convert2MethodRef + clearScope(scope); + }); activeTransaction = null; if (activeUiElement != null) { activeUiElement = null; @@ -314,31 +311,30 @@ void stopTracing(final @NotNull SpanStatus status) { } @VisibleForTesting + @SuppressWarnings("ReferenceEquality") void clearScope(final @NotNull IScope scope) { - scope.withTransaction( - transaction -> { - if (transaction == activeTransaction) { - scope.clearTransaction(); - } - }); + scope.withTransaction(transaction -> { + if (transaction == activeTransaction) { + scope.clearTransaction(); + } + }); } @VisibleForTesting void applyScope(final @NotNull IScope scope, final @NotNull ITransaction transaction) { - scope.withTransaction( - scopeTransaction -> { - // we'd not like to overwrite existent transactions bound to the Scope manually - if (scopeTransaction == null) { - scope.setTransaction(transaction); - } else { - options - .getLogger() - .log( - SentryLevel.DEBUG, - "Transaction '%s' won't be bound to the Scope since there's one already in there.", - transaction.getName()); - } - }); + scope.withTransaction(scopeTransaction -> { + // we'd not like to overwrite existent transactions bound to the Scope manually + if (scopeTransaction == null) { + scope.setTransaction(transaction); + } else { + options + .getLogger() + .log( + SentryLevel.DEBUG, + "Transaction '%s' won't be bound to the Scope since there's one already in there.", + transaction.getName()); + } + }); } private @NotNull String getActivityName(final @NotNull Activity activity) { @@ -350,7 +346,7 @@ void applyScope(final @NotNull IScope scope, final @NotNull ITransaction transac if (activity == null) { options .getLogger() - .log(SentryLevel.DEBUG, "Activity is null in " + caller + ". No breadcrumb captured."); + .log(SentryLevel.DEBUG, "Activity is null in %s. No breadcrumb captured.", caller); return null; } @@ -358,7 +354,7 @@ void applyScope(final @NotNull IScope scope, final @NotNull ITransaction transac if (window == null) { options .getLogger() - .log(SentryLevel.DEBUG, "Window is null in " + caller + ". No breadcrumb captured."); + .log(SentryLevel.DEBUG, "Window is null in %s. No breadcrumb captured.", caller); return null; } @@ -366,7 +362,7 @@ void applyScope(final @NotNull IScope scope, final @NotNull ITransaction transac if (decorView == null) { options .getLogger() - .log(SentryLevel.DEBUG, "DecorView is null in " + caller + ". No breadcrumb captured."); + .log(SentryLevel.DEBUG, "DecorView is null in %s. No breadcrumb captured.", caller); return null; } return decorView; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/modules/AssetsModulesLoader.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/modules/AssetsModulesLoader.java index 1aa8a89f8fc..27619febb2f 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/modules/AssetsModulesLoader.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/modules/AssetsModulesLoader.java @@ -18,6 +18,7 @@ public final class AssetsModulesLoader extends ModulesLoader { private final @NotNull Context context; + @SuppressWarnings("FutureReturnValueIgnored") public AssetsModulesLoader(final @NotNull Context context, final @NotNull SentryOptions options) { super(options.getLogger()); this.context = ContextUtils.getApplicationContext(context); @@ -26,10 +27,9 @@ public AssetsModulesLoader(final @NotNull Context context, final @NotNull Sentry try { options .getExecutorService() - .submit( - () -> { - getOrLoadModules(); - }); + .submit(() -> { + getOrLoadModules(); + }); } catch (Throwable e) { options.getLogger().log(SentryLevel.ERROR, "AssetsModulesLoader submit failed", e); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/Lines.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/Lines.java index 5c314e1b23f..8adeff66401 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/Lines.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/Lines.java @@ -23,6 +23,7 @@ import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; +import java.util.List; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -32,7 +33,7 @@ */ @ApiStatus.Internal public final class Lines { - private final @NotNull ArrayList mList; + private final @NotNull List mList; private final int mMin; private final int mMax; @@ -61,7 +62,7 @@ public static Lines readLines(final @NotNull BufferedReader in) throws IOExcepti } /** Construct with a list of lines. */ - public Lines(final @NotNull ArrayList list) { + public Lines(final @NotNull List list) { this.mList = list; mMin = 0; mMax = mList.size(); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/ThreadDumpParser.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/ThreadDumpParser.java index bfb829ce1a9..d64d5518804 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/ThreadDumpParser.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/threaddump/ThreadDumpParser.java @@ -38,7 +38,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class ThreadDumpParser { +public final class ThreadDumpParser { private static final Pattern BEGIN_MANAGED_THREAD_RE = Pattern.compile("\"(.*)\" (.*) ?prio=(\\d+)\\s+tid=(\\d+)\\s*(.*)"); @@ -178,7 +178,7 @@ public void parse(final @NotNull Lines lines) { markThreads(); } - private SentryThread parseThread(final @NotNull Lines lines) { + private @Nullable SentryThread parseThread(final @NotNull Lines lines) { final SentryThread sentryThread = new SentryThread(); final Matcher beginManagedThreadRe = BEGIN_MANAGED_THREAD_RE.matcher(""); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/tombstone/TombstoneParser.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/tombstone/TombstoneParser.java index b6ac22b12ef..244d3b4e74a 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/tombstone/TombstoneParser.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/tombstone/TombstoneParser.java @@ -32,7 +32,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class TombstoneParser implements Closeable { +public final class TombstoneParser implements Closeable { @Nullable private final InputStream tombstoneStream; @NotNull private final List inAppIncludes; @@ -316,6 +316,7 @@ void extendTo(final @NotNull MemoryMapping mapping) { this.previousOffset = mapping.offset; } + @Nullable DebugImage toDebugImage() { if (buildId.isEmpty()) { return null; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java index a5ff05e27d5..de5a90c9067 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProvider.java @@ -9,6 +9,7 @@ import android.net.NetworkCapabilities; import android.os.Build; import android.os.Handler; +import android.telephony.TelephonyManager; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import io.sentry.IConnectionStatusProvider; @@ -22,19 +23,62 @@ import io.sentry.time.Deadline; import io.sentry.time.MonotonicTicker; import io.sentry.util.AutoClosableReentrantLock; -import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; /** - * Note: ConnectivityManager sometimes throws SecurityExceptions on Android 11. Hence all relevant - * calls are guarded with try/catch. see https://issuetracker.google.com/issues/175055271 for more - * details + * Primary source of network connectivity info for the Android SDK. Reports the status and type of + * the app's default + * network, plus cellular network generation when available. + * + *

Clients can either: + * + *

    + *
  • register callbacks to be notified of network updates as they occur (see {@link + * #addNetworkCallback} and {@link #addConnectionStatusObserver}), or + *
  • request network info synchronously (see, e.g., {@link #getConnection}). + *
+ * + * Note: Synchronous reads may make system calls on the calling thread if they're not backed by + * cached data or if their cached data has gone stale. + * + *

Exception policy + * + *

The provider sources its network info from {@link ConnectivityManager}, which sometimes throws + * SecurityExceptions on Android 11. Hence all relevant calls are guarded with try/catch. See here for more details. + * + *

Threading policy + * + *

Public methods may be called from any thread. Client registrations are added and removed + * synchronously using thread-safe lists; they do not wait for this provider's own callbacks + * to be registered with {@link ConnectivityManager} or {@link TelephonyManager}. Registration and + * unregistration of those system callbacks run asynchronously on the {@link + * SentryOptions#getExecutorService() SDK executor}. + * + *

The main thread queries this provider during {@code SentryAndroid.init} and whenever an event + * is captured. To avoid blocking the main thread, be sure to: + * + *

    + *
  • Never lock the connection cache. Instead, replace the whole {@link ConnectionSnapshot} via + * a compare-and-set operation, and read it once per operation. + *
  • Never hold a lock while notifying observers or child network callbacks. Both run SDK code + * that could invoke user callbacks such as {@code beforeBreadcrumb}, and those callbacks can + * block or deadlock. + *
  • Only acquire {@link #registrationLock} on the SDK executor. It's held across network + * callback registration, which can be long-lasting. + *
  • Check from the SDK executor whether the callbacks are registered, not from the calling + * thread. The executor runs tasks in submission order, so it's guaranteed to see the latest + * registration state. + *
*/ @ApiStatus.Internal public final class AndroidConnectionStatusProvider @@ -44,19 +88,45 @@ public final class AndroidConnectionStatusProvider private final @NotNull SentryOptions options; private final @NotNull BuildInfoProvider buildInfoProvider; private final @NotNull MonotonicTicker ticker; - private final @NotNull List connectionStatusObservers; + + /** + * Registered client observers. Provider notifies them about the network's {@link + * ConnectionStatus}. + * + *

Used by SDK integrations, including Session Replay and integrations that send cached + * envelopes. + */ + private final @NotNull List connectionStatusObservers = + new CopyOnWriteArrayList<>(); + private final @NotNull CellularNetworkTechnologyProvider cellularNetworkTechnologyProvider; private final @Nullable Handler handler; - private final @NotNull AutoClosableReentrantLock lock = new AutoClosableReentrantLock(); + + /** + * Serializes registration and unregistration of the callbacks this provider's passes to {@link + * ConnectivityManager} and {@link TelephonyManager}. + * + *

Note: The callbacks registered with ConnectivityManager and TelephonyManager, which are + * guarded by this lock, are distinct from the {@link #connectionStatusObservers} and {@link + * #childCallbacks} registered by this provider's own clients. (The latter are made thread-safe + * via {@link CopyOnWriteArrayList}s.) + */ + private final @NotNull AutoClosableReentrantLock registrationLock = + new AutoClosableReentrantLock(); + private volatile @Nullable NetworkCallback networkCallback; private static final @NotNull AutoClosableReentrantLock connectivityManagerLock = new AutoClosableReentrantLock(); private static volatile @Nullable ConnectivityManager connectivityManager; - private static final @NotNull AutoClosableReentrantLock childCallbacksLock = - new AutoClosableReentrantLock(); - private static final @NotNull List childCallbacks = new ArrayList<>(); + /** + * Registered client callbacks. Provider invokes them to forward network connectivity events + * emitted by {@link ConnectivityManager}. + * + *

Used by SDK integrations, including network breadcrumbs. + */ + private static final @NotNull List childCallbacks = new CopyOnWriteArrayList<>(); private static final int[] transports = { NetworkCapabilities.TRANSPORT_WIFI, @@ -65,13 +135,44 @@ public final class AndroidConnectionStatusProvider NetworkCapabilities.TRANSPORT_BLUETOOTH }; - private static final int[] capabilities = new int[2]; + /** + * IDs of {@link NetworkCapabilities} whose status can affect whether a network is considered + * connected. + * + *

The relevant capabilities vary by Android API level. + */ + private final int[] capabilityIds; - private volatile @Nullable NetworkCapabilities cachedNetworkCapabilities; - private volatile @Nullable Network currentNetwork; - private volatile @NotNull Deadline cacheFreshUntil; private static final long CACHE_TTL_MINUTES = 2; - private final @NotNull AtomicBoolean isConnected = new AtomicBoolean(false); + + /** + * Flag for ensuring {@link #childCallbacks child callbacks} don't get more than one {@link + * NetworkCallback#onAvailable} invocation per connection. + * + *

Reset when the network is lost or unavailable. + */ + private final @NotNull AtomicBoolean onAvailableForwarded = new AtomicBoolean(false); + + /** + * Cache of the latest network connection info. + * + *

Threading policy + * + *

This container and the snapshots it wraps are shared across threads. Updates publish a new + * snapshot via the atomic reference. Synchronous requests for network info store the system's + * response with compare-and-set, and discard it only if another update publishes a fresh snapshot + * while the request runs. + */ + private final @NotNull AtomicReference snapshot; + + /** + * True if this provider has been {@link #close closed}, and therefore must permanently stop + * monitoring network connectivity. + * + *

If true, further callback registration and foreground refreshes are skipped. Existing + * observers and callbacks may be awaiting cleanup, as cleanup runs asynchronously. + */ + private volatile boolean closed; public AndroidConnectionStatusProvider( @NotNull Context context, @@ -92,14 +193,15 @@ public AndroidConnectionStatusProvider( this.options = options; this.buildInfoProvider = buildInfoProvider; this.ticker = ticker; - this.cacheFreshUntil = Deadline.passed(ticker); + this.snapshot = new AtomicReference<>(ConnectionSnapshot.unknown(ticker)); this.handler = handler; - this.connectionStatusObservers = new ArrayList<>(); this.cellularNetworkTechnologyProvider = new CellularNetworkTechnologyProvider(this.context, options.getLogger(), buildInfoProvider); - capabilities[0] = NetworkCapabilities.NET_CAPABILITY_INTERNET; - capabilities[1] = NetworkCapabilities.NET_CAPABILITY_VALIDATED; + this.capabilityIds = + new int[] { + NetworkCapabilities.NET_CAPABILITY_INTERNET, NetworkCapabilities.NET_CAPABILITY_VALIDATED + }; // Register network callback immediately for caching //noinspection Convert2MethodRef @@ -138,10 +240,14 @@ private boolean isNetworkEffectivelyConnected( return false; } - /** Get connection status from cached NetworkCapabilities or fallback to legacy method. */ - private @NotNull ConnectionStatus getConnectionStatusFromCache() { - if (cachedNetworkCapabilities != null) { - return isNetworkEffectivelyConnected(cachedNetworkCapabilities) + /** + * Returns the connection status of a snapshot, or of the legacy {@link ConnectivityManager} query + * if the snapshot has no {@link ConnectionSnapshot#capabilities capabilities}. + */ + private @NotNull ConnectionStatus statusOf(final @NotNull ConnectionSnapshot snapshot) { + final @Nullable NetworkCapabilities capabilities = snapshot.capabilities; + if (capabilities != null) { + return isNetworkEffectivelyConnected(capabilities) ? ConnectionStatus.CONNECTED : ConnectionStatus.DISCONNECTED; } @@ -156,9 +262,14 @@ private boolean isNetworkEffectivelyConnected( return ConnectionStatus.UNKNOWN; } - /** Get connection type from cached NetworkCapabilities or fallback to legacy method. */ - private @Nullable String getConnectionTypeFromCache() { - final NetworkCapabilities capabilities = cachedNetworkCapabilities; + /** + * Returns the {@link #getConnectionType(NetworkCapabilities) connection type} of a snapshot, or + * of the {@link #getConnectionType(Context, ILogger, BuildInfoProvider) legacy + * ConnectivityManager query} if the snapshot has no {@link ConnectionSnapshot#capabilities + * capabilities}. + */ + private @Nullable String typeOf(final @NotNull ConnectionSnapshot snapshot) { + final @Nullable NetworkCapabilities capabilities = snapshot.capabilities; if (capabilities != null) { return getConnectionType(capabilities); } @@ -169,15 +280,9 @@ private boolean isNetworkEffectivelyConnected( /** * The connection type and, for cellular connections, the generation of the network technology. - * - *

Both are derived from one cache read, so they always describe the same network instead of - * straddling a connectivity change. */ public @NotNull NetworkConnection getConnection() { - if (!isCacheValid()) { - updateCache(null); - } - final @Nullable String connectionType = getConnectionTypeFromCache(); + final @Nullable String connectionType = typeOf(freshSnapshot()); if (!"cellular".equals(connectionType)) { return new NetworkConnection(connectionType, null); } @@ -186,6 +291,10 @@ private boolean isNetworkEffectivelyConnected( } private void ensureNetworkCallbackRegistered() { + if (closed) { + return; + } + if (!ContextUtils.isForegroundImportance()) { return; } @@ -194,8 +303,11 @@ private void ensureNetworkCallbackRegistered() { return; // Already registered } - try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { - if (networkCallback != null) { + final boolean registered; + try (final @NotNull ISentryLifecycleToken ignored = registrationLock.acquire()) { + // Registration and unregistration share this lock. Rechecking the closed flag here ensures + // that closing the provider prevents registration and cleans up the registered callbacks. + if (closed || networkCallback != null) { return; } @@ -203,16 +315,16 @@ private void ensureNetworkCallbackRegistered() { new NetworkCallback() { @Override public void onAvailable(final @NotNull Network network) { - currentNetwork = network; - - // have to only dispatch this on first registration + when the connection got - // re-established - // otherwise it would've been dispatched on every foreground - if (!isConnected.getAndSet(true)) { - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - for (final @NotNull NetworkCallback cb : childCallbacks) { - cb.onAvailable(network); - } + @NotNull ConnectionSnapshot current; + do { + current = currentSnapshot(); + } while (!snapshot.compareAndSet(current, current.withNetwork(network))); + + // Only forward the call on first registration + when the connection is + // re-established – not on every foreground. + if (!onAvailableForwarded.getAndSet(true)) { + for (final @NotNull NetworkCallback cb : childCallbacks) { + cb.onAvailable(network); } } } @@ -222,99 +334,90 @@ public void onAvailable(final @NotNull Network network) { public void onUnavailable() { clearCacheAndNotifyObservers(); - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - for (final @NotNull NetworkCallback cb : childCallbacks) { - cb.onUnavailable(); - } + for (final @NotNull NetworkCallback cb : childCallbacks) { + cb.onUnavailable(); } } @Override public void onLost(final @NotNull Network network) { - if (!network.equals(currentNetwork)) { + if (!network.equals(currentSnapshot().network)) { return; } clearCacheAndNotifyObservers(); - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - for (final @NotNull NetworkCallback cb : childCallbacks) { - cb.onLost(network); - } + for (final @NotNull NetworkCallback cb : childCallbacks) { + cb.onLost(network); } } private void clearCacheAndNotifyObservers() { - isConnected.set(false); - // Clear cached capabilities and network reference atomically - try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { - cachedNetworkCapabilities = null; - currentNetwork = null; - cacheFreshUntil = Deadline.after(ticker, CACHE_TTL_MINUTES, TimeUnit.MINUTES); - - options - .getLogger() - .log(SentryLevel.DEBUG, "Cache cleared - network lost/unavailable"); - - // Notify all observers with DISCONNECTED status directly - // No need to query ConnectivityManager - we know the network is gone - for (final @NotNull IConnectionStatusObserver observer : - connectionStatusObservers) { - observer.onConnectionStatusChanged(ConnectionStatus.DISCONNECTED); - } + onAvailableForwarded.set(false); + snapshot.set(ConnectionSnapshot.lost(ticker)); + + options + .getLogger() + .log(SentryLevel.DEBUG, "Cache cleared - network lost/unavailable"); + + // Notify all observers with DISCONNECTED status directly + // No need to query ConnectivityManager - we know the network is gone + for (final @NotNull IConnectionStatusObserver observer : connectionStatusObservers) { + observer.onConnectionStatusChanged(ConnectionStatus.DISCONNECTED); } } @Override public void onCapabilitiesChanged( @NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) { - if (!network.equals(currentNetwork)) { + if (!network.equals(currentSnapshot().network)) { return; } - updateCacheAndNotifyObservers(network, networkCapabilities); + updateCacheAndNotifyObservers(networkCapabilities); - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - for (final @NotNull NetworkCallback cb : childCallbacks) { - cb.onCapabilitiesChanged(network, networkCapabilities); - } + for (final @NotNull NetworkCallback cb : childCallbacks) { + cb.onCapabilitiesChanged(network, networkCapabilities); } } + /* + * Caches the capabilities and notifies observers. + * + *

No-ops unless the incoming {@code networkCapabilities} differ from the stored ones + * in a way relevant to the connection status or type. + */ private void updateCacheAndNotifyObservers( - @Nullable Network network, @Nullable NetworkCapabilities networkCapabilities) { - // Check if this change is meaningful before notifying observers - final boolean shouldUpdate = isSignificantChange(networkCapabilities); - - // Only notify observers if something meaningful changed - if (shouldUpdate) { - updateCache(networkCapabilities); - - final @NotNull ConnectionStatus status = getConnectionStatusFromCache(); - try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { - for (final @NotNull IConnectionStatusObserver observer : - connectionStatusObservers) { - observer.onConnectionStatusChanged(status); - } + final @NotNull NetworkCapabilities networkCapabilities) { + @NotNull ConnectionSnapshot current; + @NotNull ConnectionSnapshot updated; + do { + current = currentSnapshot(); + if (!isSignificantChange(current.capabilities, networkCapabilities)) { + return; } + updated = + current.withCapabilities( + networkCapabilities, + Deadline.after(ticker, CACHE_TTL_MINUTES, TimeUnit.MINUTES)); + } while (!snapshot.compareAndSet(current, updated)); + + final @NotNull ConnectionStatus status = statusOf(updated); + for (final @NotNull IConnectionStatusObserver observer : connectionStatusObservers) { + observer.onConnectionStatusChanged(status); } } - /** + /* * Check if NetworkCapabilities change is significant for our observers. Only notify for * changes that affect connectivity status or connection type. */ - private boolean isSignificantChange(@Nullable NetworkCapabilities newCapabilities) { - final NetworkCapabilities oldCapabilities = cachedNetworkCapabilities; - - // Always significant if transitioning between null and non-null - if ((oldCapabilities == null) != (newCapabilities == null)) { + private boolean isSignificantChange( + final @Nullable NetworkCapabilities oldCapabilities, + final @NotNull NetworkCapabilities newCapabilities) { + // Always significant when capabilities first become available + if (oldCapabilities == null) { return true; } - // If both null, no change - if (oldCapabilities == null && newCapabilities == null) { - return false; - } - // Check significant capability changes if (hasSignificantCapabilityChanges(oldCapabilities, newCapabilities)) { return true; @@ -328,13 +431,12 @@ private boolean isSignificantChange(@Nullable NetworkCapabilities newCapabilitie return false; } - /** Check if capabilities that affect connectivity status changed. */ + /* Check if capabilities that affect connectivity status changed. */ private boolean hasSignificantCapabilityChanges( @NotNull NetworkCapabilities old, @NotNull NetworkCapabilities new_) { // Check capabilities we care about for connectivity determination - for (int capability : capabilities) { - if (capability != 0 - && old.hasCapability(capability) != new_.hasCapability(capability)) { + for (int capabilityId : capabilityIds) { + if (old.hasCapability(capabilityId) != new_.hasCapability(capabilityId)) { return true; } } @@ -342,7 +444,7 @@ private boolean hasSignificantCapabilityChanges( return false; } - /** Check if transport types that affect connection type changed. */ + /* Check if transport types that affect connection type changed. */ private boolean hasSignificantTransportChanges( @NotNull NetworkCapabilities old, @NotNull NetworkCapabilities new_) { // Check transports we care about for connection type determination @@ -356,115 +458,149 @@ private boolean hasSignificantTransportChanges( } }; - if (registerNetworkCallback( - context, options.getLogger(), buildInfoProvider, handler, callback)) { + registered = + registerNetworkCallback( + context, options.getLogger(), buildInfoProvider, handler, callback); + if (registered) { networkCallback = callback; // Only start listening once the network callback is registered, because unregistering is // skipped while there is no network callback, which would leave the listener running. cellularNetworkTechnologyProvider.register(); - options.getLogger().log(SentryLevel.DEBUG, "Network callback registered successfully"); - } else { - options.getLogger().log(SentryLevel.WARNING, "Failed to register network callback"); } } + if (registered) { + options.getLogger().log(SentryLevel.DEBUG, "Network callback registered successfully"); + } else { + options.getLogger().log(SentryLevel.WARNING, "Failed to register network callback"); + } } - @SuppressLint("MissingPermission") - private void updateCache(@Nullable NetworkCapabilities networkCapabilities) { - try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { - try { - if (networkCapabilities != null) { - cachedNetworkCapabilities = networkCapabilities; - } else { - if (!Permissions.hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) { - options - .getLogger() - .log( - SentryLevel.INFO, - "No permission (ACCESS_NETWORK_STATE) to check network status."); - cachedNetworkCapabilities = null; - cacheFreshUntil = Deadline.after(ticker, CACHE_TTL_MINUTES, TimeUnit.MINUTES); - return; - } + // NullAway treats AtomicReference.get() as nullable, but the snapshot is never set to null. + @SuppressWarnings("NullAway") + private @NotNull ConnectionSnapshot currentSnapshot() { + return snapshot.get(); + } - // Fallback: query current active network - final ConnectivityManager connectivityManager = - getConnectivityManager(context, options.getLogger()); - if (connectivityManager != null) { - final Network activeNetwork = connectivityManager.getActiveNetwork(); - - cachedNetworkCapabilities = - activeNetwork != null - ? connectivityManager.getNetworkCapabilities(activeNetwork) - : null; - } else { - cachedNetworkCapabilities = - null; // Clear cached capabilities if connectivity manager is null - } - } - cacheFreshUntil = Deadline.after(ticker, CACHE_TTL_MINUTES, TimeUnit.MINUTES); + /** The current snapshot, refreshed first if it's stale. */ + private @NotNull ConnectionSnapshot freshSnapshot() { + final @NotNull ConnectionSnapshot current = currentSnapshot(); + return current.isFresh() ? current : refresh(current); + } - options - .getLogger() - .log( - SentryLevel.DEBUG, - "Cache updated - Status: " - + getConnectionStatusFromCache() - + ", Type: " - + getConnectionTypeFromCache()); - } catch (Throwable t) { - options.getLogger().log(SentryLevel.WARNING, "Failed to update connection status cache", t); - cachedNetworkCapabilities = null; - cacheFreshUntil = Deadline.after(ticker, CACHE_TTL_MINUTES, TimeUnit.MINUTES); + /** + * Queries the active network and stores its {@link NetworkCapabilities capabilities}. + * + *

If another thread, such as a network callback, replaces the snapshot during the query, the + * result is still stored as long as the newer snapshot is stale, keeping that snapshot's network. + * For example, {@code onAvailable} only swaps in the network during a network handover. A fresh + * newer snapshot has more recent capabilities, or records a lost network, so it's kept instead. + * + * @param before the snapshot the refresh request replaces + * @return the stored snapshot, or the fresh snapshot another thread stored during the query + */ + private @NotNull ConnectionSnapshot refresh(final @NotNull ConnectionSnapshot before) { + final @Nullable NetworkCapabilities capabilities = queryActiveNetworkCapabilities(); + final @NotNull Deadline freshUntil = + Deadline.after(ticker, CACHE_TTL_MINUTES, TimeUnit.MINUTES); + @NotNull ConnectionSnapshot current = before; + @NotNull ConnectionSnapshot refreshed; + while (true) { + refreshed = current.withCapabilities(capabilities, freshUntil); + if (snapshot.compareAndSet(current, refreshed)) { + break; + } + current = currentSnapshot(); + if (current.isFresh()) { + return current; } } + + // Without capabilities, statusOf and typeOf query the ConnectivityManager, so we only build the + // message if it'll be logged. + if (options.getLogger().isEnabled(SentryLevel.DEBUG)) { + options + .getLogger() + .log( + SentryLevel.DEBUG, + "Cache updated - Status: " + statusOf(refreshed) + ", Type: " + typeOf(refreshed)); + } + return refreshed; } - private boolean isCacheValid() { - return !cacheFreshUntil.hasPassed(); + /** + * Queries the capabilities of the active network from the {@link ConnectivityManager}. + * + * @return the capabilities, or {@code null} if they can't be read (i.e., without permission, + * without an active network, or when the query fails) + */ + @SuppressLint("MissingPermission") + private @Nullable NetworkCapabilities queryActiveNetworkCapabilities() { + try { + if (!Permissions.hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE)) { + options + .getLogger() + .log(SentryLevel.INFO, "No permission (ACCESS_NETWORK_STATE) to check network status."); + return null; + } + + final ConnectivityManager connectivityManager = + getConnectivityManager(context, options.getLogger()); + if (connectivityManager == null) { + return null; + } + final Network activeNetwork = connectivityManager.getActiveNetwork(); + return activeNetwork != null + ? connectivityManager.getNetworkCapabilities(activeNetwork) + : null; + } catch (Throwable t) { + options.getLogger().log(SentryLevel.WARNING, "Failed to update connection status cache", t); + return null; + } } @Override public @NotNull ConnectionStatus getConnectionStatus() { - if (!isCacheValid()) { - updateCache(null); - } - return getConnectionStatusFromCache(); + return statusOf(freshSnapshot()); } @Override public @Nullable String getConnectionType() { - if (!isCacheValid()) { - updateCache(null); - } - return getConnectionTypeFromCache(); + return typeOf(freshSnapshot()); } + /** + * Adds an observer synchronously and makes sure the network callback is registered + * asynchronously. + * + *

The observer is added immediately. Registering the network callback calls into system + * services that can be slow, so it's scheduled on the SDK executor instead of making the caller + * wait for it. (The caller is often the main thread during {@code Sentry.init}.) + * + * @return always {@code true}, because the observer is added even if registering the network + * callback is still pending or fails + */ @Override public boolean addConnectionStatusObserver(final @NotNull IConnectionStatusObserver observer) { - try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { - connectionStatusObservers.add(observer); - } - ensureNetworkCallbackRegistered(); - - // Network callback is already registered during initialization - return networkCallback != null; + connectionStatusObservers.add(observer); + // The executor drops tasks when its queue is full, which would skip this registration. That's + // unlikely, and onForeground() registers the callback again the next time the app is shown. + //noinspection Convert2MethodRef + submitSafe(() -> ensureNetworkCallbackRegistered()); + return true; } @Override public void removeConnectionStatusObserver(final @NotNull IConnectionStatusObserver observer) { - try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { - connectionStatusObservers.remove(observer); - // Keep the callback registered for caching even if no observers - } + connectionStatusObservers.remove(observer); + // Keep the callback registered for caching even if no observers } private void unregisterNetworkCallback(final boolean clearObservers) { - try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { - if (clearObservers) { - connectionStatusObservers.clear(); - } + if (clearObservers) { + connectionStatusObservers.clear(); + } + try (final @NotNull ISentryLifecycleToken ignored = registrationLock.acquire()) { final @Nullable NetworkCallback callbackRef = networkCallback; networkCallback = null; @@ -472,10 +608,7 @@ private void unregisterNetworkCallback(final boolean clearObservers) { unregisterNetworkCallback(context, options.getLogger(), callbackRef); } cellularNetworkTechnologyProvider.unregister(); - // Clear cached state - cachedNetworkCapabilities = null; - currentNetwork = null; - cacheFreshUntil = Deadline.passed(ticker); + snapshot.set(ConnectionSnapshot.unknown(ticker)); } options.getLogger().log(SentryLevel.DEBUG, "Network callback unregistered"); } @@ -483,79 +616,82 @@ private void unregisterNetworkCallback(final boolean clearObservers) { /** Clean up resources - should be called when the provider is no longer needed */ @Override public void close() { - submitSafe( - () -> { - unregisterNetworkCallback(/* clearObservers= */ true); - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - childCallbacks.clear(); - } - try (final @NotNull ISentryLifecycleToken ignored = connectivityManagerLock.acquire()) { - connectivityManager = null; - } - AppState.getInstance().removeAppStateListener(this); - }); + closed = true; + + submitSafe(() -> { + unregisterNetworkCallback(/* clearObservers= */ true); + childCallbacks.clear(); + try (final @NotNull ISentryLifecycleToken ignored = connectivityManagerLock.acquire()) { + connectivityManager = null; + } + AppState.getInstance().removeAppStateListener(this); + }); } + /** + * Schedules a task to refresh the cache, notify observers and register the network callback. The + * task does nothing if the callback is already registered or the provider is closed. + */ @Override public void onForeground() { - if (networkCallback != null) { - return; - } - - submitSafe( - () -> { - // proactively update cache and notify observers on foreground to ensure connectivity - // state is not stale - updateCache(null); + submitSafe(() -> { + // Check on the executor so any earlier background unregistration runs before we decide + // whether registration is needed. Checking before submission could leave the callback + // unregistered after a quick return to the foreground. + if (closed || networkCallback != null) { + return; + } - final @NotNull ConnectionStatus status = getConnectionStatusFromCache(); - if (status == ConnectionStatus.DISCONNECTED) { - // onLost is not called retroactively when we registerNetworkCallback (as opposed to - // onAvailable), so we have to do it manually for the DISCONNECTED case - isConnected.set(false); - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - for (final @NotNull NetworkCallback cb : childCallbacks) { - //noinspection DataFlowIssue - cb.onLost(null); - } - } - } - try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { - for (final @NotNull IConnectionStatusObserver observer : connectionStatusObservers) { - observer.onConnectionStatusChanged(status); - } - } + // proactively update cache and notify observers on foreground to ensure connectivity + // state is not stale + final @NotNull ConnectionStatus status = statusOf(refresh(currentSnapshot())); + if (status == ConnectionStatus.DISCONNECTED) { + // onLost is not called retroactively when we registerNetworkCallback (as opposed to + // onAvailable), so we have to do it manually for the DISCONNECTED case + onAvailableForwarded.set(false); + for (final @NotNull NetworkCallback cb : childCallbacks) { + //noinspection DataFlowIssue + cb.onLost(null); + } + } + for (final @NotNull IConnectionStatusObserver observer : connectionStatusObservers) { + observer.onConnectionStatusChanged(status); + } - // this will ONLY do the necessary parts like registerNetworkCallback and onAvailable, but - // it won't updateCache and notify observes because we just did it above and the cached - // capabilities will be the same - ensureNetworkCallbackRegistered(); - }); + // this will ONLY do the necessary parts like registerNetworkCallback and onAvailable, but + // it won't refresh the cache and notify observers because we just did it above and the + // cached capabilities will be the same + ensureNetworkCallbackRegistered(); + }); } + /** + * Schedules unregistration of the network callback and the cellular technology listener, if + * registered. + */ @Override public void onBackground() { - if (networkCallback == null) { - return; - } - - submitSafe( - () -> { - //noinspection Convert2MethodRef - unregisterNetworkCallback(/* clearObservers= */ false); - }); + submitSafe(() -> { + // Check on the executor so any earlier registration finishes before we decide whether + // to unregister. Checking before submission could miss a pending registration and leave + // the callbacks registered in the background. + if (networkCallback == null) { + return; + } + unregisterNetworkCallback(/* clearObservers= */ false); + }); } /** - * Get the cached NetworkCapabilities for advanced use cases. Returns null if cache is stale or no - * capabilities are available. + * Get the cached NetworkCapabilities for advanced use cases. Returns whatever the current + * snapshot holds, even if it is stale, or null if it has no capabilities. * * @return cached NetworkCapabilities or null */ @TestOnly @Nullable public NetworkCapabilities getCachedNetworkCapabilities() { - return cachedNetworkCapabilities; + return currentSnapshot().capabilities; } /** @@ -711,16 +847,12 @@ public static boolean addNetworkCallback( return false; } - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - childCallbacks.add(networkCallback); - } + childCallbacks.add(networkCallback); return true; } public static void removeNetworkCallback(final @NotNull NetworkCallback networkCallback) { - try (final @NotNull ISentryLifecycleToken ignored = childCallbacksLock.acquire()) { - childCallbacks.remove(networkCallback); - } + childCallbacks.remove(networkCallback); } @SuppressLint({"MissingPermission", "NewApi"}) @@ -785,6 +917,123 @@ public static List getChildCallbacks() { return childCallbacks; } + /** + * An atomically publishable snapshot of cached network connection info, obtained from {@link + * ConnectivityManager}. + * + *

Note: This class's {@link #network} and {@link #capabilities} fields are updated + * independently and can describe different networks during handover (e.g., from cellular to + * Wi-Fi). That behavior predates this class and - for now – isn't problematic, as no caller + * requires the two fields to describe the same network. (Current readers use {@code network} to + * filter callbacks and {@code capabilities} to derive connection info.) + */ + private static final class ConnectionSnapshot { + + /** Info about the network of interest, or {@code null} if nothing is known. */ + private final @Nullable Network network; + + /** + * The capabilities of the network. {@code null} if they're unknown or there's no known network. + */ + private final @Nullable NetworkCapabilities capabilities; + + /** When this snapshot becomes stale and {@link ConnectivityManager} should be requeried. */ + private final @NotNull Deadline freshUntil; + + private ConnectionSnapshot( + final @Nullable Network network, + final @Nullable NetworkCapabilities capabilities, + final @NotNull Deadline freshUntil) { + this.network = network; + this.capabilities = capabilities; + this.freshUntil = freshUntil; + } + + /** Returns {@code true} if this snapshot has yet to go stale. */ + boolean isFresh() { + return !freshUntil.hasPassed(); + } + + /** Indicates that nothing is known about the network. */ + static @NotNull ConnectionSnapshot unknown(final @NotNull MonotonicTicker ticker) { + return new ConnectionSnapshot(null, null, Deadline.passed(ticker)); + } + + /** Indicates that the network has been lost. */ + static @NotNull ConnectionSnapshot lost(final @NotNull MonotonicTicker ticker) { + return new ConnectionSnapshot( + null, null, Deadline.after(ticker, CACHE_TTL_MINUTES, TimeUnit.MINUTES)); + } + + /** Returns a copy of this snapshot with the provided {@code network}. */ + @NotNull + ConnectionSnapshot withNetwork(final @NotNull Network network) { + return new ConnectionSnapshot(network, capabilities, freshUntil); + } + + /** Returns a copy of this snapshot with the provided {@code capabilities} and deadline. */ + @NotNull + ConnectionSnapshot withCapabilities( + final @Nullable NetworkCapabilities capabilities, final @NotNull Deadline freshUntil) { + return new ConnectionSnapshot(network, capabilities, freshUntil); + } + + /** + * For debugging. Summarizes the capabilities this provider reads instead of printing them in + * full because {@link NetworkCapabilities#toString()} can include the Wi-Fi SSID on API 29+. + */ + @SuppressLint("InlinedApi") + @Override + public @NotNull String toString() { + final @NotNull StringBuilder sb = new StringBuilder("ConnectionSnapshot{network="); + sb.append(network).append(", capabilities="); + + if (capabilities == null) { + sb.append("none"); + } else { + sb.append("[transports="); + boolean anyTransport = false; + + for (final int transport : transports) { + if (capabilities.hasTransport(transport)) { + sb.append(anyTransport ? "|" : "").append(transportName(transport)); + anyTransport = true; + } + } + + if (!anyTransport) { + sb.append("none"); + } + sb.append(", internet=") + .append(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) + .append(", validated=") + .append(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) + .append(']'); + } + + final long remainingMs = freshUntil.remaining(TimeUnit.MILLISECONDS); + sb.append(", ").append(remainingMs > 0 ? "fresh for " + remainingMs + "ms" : "stale"); + + return sb.append('}').toString(); + } + + private static @NotNull String transportName(final int transport) { + switch (transport) { + case NetworkCapabilities.TRANSPORT_WIFI: + return "wifi"; + case NetworkCapabilities.TRANSPORT_CELLULAR: + return "cellular"; + case NetworkCapabilities.TRANSPORT_ETHERNET: + return "ethernet"; + case NetworkCapabilities.TRANSPORT_BLUETOOTH: + return "bluetooth"; + default: + return String.valueOf(transport); + } + } + } + + @SuppressWarnings("FutureReturnValueIgnored") private void submitSafe(@NotNull Runnable r) { try { options.getExecutorService().submit(r); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/BreadcrumbFactory.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/BreadcrumbFactory.java deleted file mode 100644 index 04cabc9430e..00000000000 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/BreadcrumbFactory.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.sentry.android.core.internal.util; - -import io.sentry.Breadcrumb; -import io.sentry.SentryLevel; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.NotNull; - -@ApiStatus.Internal -public class BreadcrumbFactory { - - public static @NotNull Breadcrumb forSession(@NotNull String state) { - final Breadcrumb breadcrumb = new Breadcrumb(); - breadcrumb.setType("session"); - breadcrumb.setData("state", state); - breadcrumb.setCategory("app.lifecycle"); - breadcrumb.setLevel(SentryLevel.INFO); - return breadcrumb; - } -} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ClassUtil.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ClassUtil.java index 8b730e267ae..fc62749601b 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ClassUtil.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ClassUtil.java @@ -4,7 +4,7 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class ClassUtil { +public final class ClassUtil { public static @Nullable String getClassName(final @Nullable Object object) { if (object == null) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/Debouncer.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/Debouncer.java index 8808947c0cc..4a2787e18bc 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/Debouncer.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/Debouncer.java @@ -1,40 +1,43 @@ package io.sentry.android.core.internal.util; -import io.sentry.transport.ICurrentDateProvider; +import io.sentry.time.Deadline; +import io.sentry.time.MonotonicTicker; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -/** A simple time-based debouncing mechanism */ +/** + * A simple time-based debouncing mechanism. + * + *

The window is measured on a {@link MonotonicTicker}, which on Android keeps counting through + * deep sleep, so a window that expired while the device slept is treated as expired. + */ @ApiStatus.Internal -public class Debouncer { +public final class Debouncer { + private final @NotNull MonotonicTicker ticker; private final long waitTimeMs; - private final @NotNull ICurrentDateProvider timeProvider; - private final @NotNull AtomicInteger executions = new AtomicInteger(0); private final int maxExecutions; - - private final @NotNull AtomicLong lastExecutionTime = new AtomicLong(0); + private final @NotNull AtomicInteger executions = new AtomicInteger(0); + private volatile @NotNull Deadline windowEnd; public Debouncer( - final @NotNull ICurrentDateProvider timeProvider, - final long waitTimeMs, - final int maxExecutions) { - this.timeProvider = timeProvider; + final @NotNull MonotonicTicker ticker, final long waitTimeMs, final int maxExecutions) { + this.ticker = ticker; this.waitTimeMs = waitTimeMs; this.maxExecutions = maxExecutions <= 0 ? 1 : maxExecutions; + this.windowEnd = Deadline.passed(ticker); } /** - * @return true if the execution should be debounced due to maxExecutions executions being made - * within waitTimeMs, otherwise false. + * Returns true if the execution should be debounced due to maxExecutions executions being made + * within waitTimeMs, otherwise false. */ public boolean checkForDebounce() { - final long now = timeProvider.getCurrentTimeMillis(); - if (lastExecutionTime.get() == 0 || (lastExecutionTime.get() + waitTimeMs) <= now) { + if (windowEnd.hasPassed()) { executions.set(0); - lastExecutionTime.set(now); + windowEnd = Deadline.after(ticker, waitTimeMs, TimeUnit.MILLISECONDS); return false; } if (executions.incrementAndGet() < maxExecutions) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/FirstDrawDoneListener.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/FirstDrawDoneListener.java index 533739d51d8..749ec178f32 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/FirstDrawDoneListener.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/FirstDrawDoneListener.java @@ -36,7 +36,7 @@ * OnDrawListener that unregisters itself and invokes callback when the next draw is done. This API * 16+ implementation is an approximation of the initial-display-time defined by Android Vitals. */ -public class FirstDrawDoneListener implements ViewTreeObserver.OnDrawListener { +public final class FirstDrawDoneListener implements ViewTreeObserver.OnDrawListener { private final @NotNull Handler mainThreadHandler = new Handler(Looper.getMainLooper()); private final @NotNull AtomicReference viewReference; private final @NotNull Runnable callback; @@ -111,13 +111,12 @@ public void onDraw() { } // OnDrawListeners cannot be removed within onDraw. Posting the removal instead of waiting for // the next global layout guarantees it happens, even if no layout pass follows the draw. - mainThreadHandler.post( - () -> { - final ViewTreeObserver observer = view.getViewTreeObserver(); - if (observer.isAlive()) { - observer.removeOnDrawListener(this); - } - }); + mainThreadHandler.post(() -> { + final ViewTreeObserver observer = view.getViewTreeObserver(); + if (observer.isAlive()) { + observer.removeOnDrawListener(this); + } + }); mainThreadHandler.postAtFrontOfQueue(callback); } diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/NativeEventUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/NativeEventUtils.java index f72a19641a8..c7f008adff0 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/NativeEventUtils.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/NativeEventUtils.java @@ -12,7 +12,7 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class NativeEventUtils { +public final class NativeEventUtils { public static byte[] readBytes(final @NotNull InputStream stream) throws IOException { try (final ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotMasking.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotMasking.java index 4d3e2d15955..896fda9f72d 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotMasking.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotMasking.java @@ -79,14 +79,13 @@ public static boolean isAvailable(final @NotNull ILogger logger) { final CountDownLatch latch = new CountDownLatch(1); try { - activity.runOnUiThread( - () -> { - try { - result.set(buildViewHierarchy(activity, screenshotOptions, logger)); - } finally { - latch.countDown(); - } - }); + activity.runOnUiThread(() -> { + try { + result.set(buildViewHierarchy(activity, screenshotOptions, logger)); + } finally { + latch.countDown(); + } + }); if (!latch.await(MASKING_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { logger.log( diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java index 76700beaf4a..1b17f28d5ed 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java @@ -24,14 +24,12 @@ import org.jetbrains.annotations.NotNull; @ApiStatus.Internal -public class ScreenshotUtils { +public final class ScreenshotUtils { private static final long CAPTURE_TIMEOUT_MS = 1000; // Used by Hybrid SDKs - /** - * @noinspection unused - */ + @SuppressWarnings("unused") public static @Nullable byte[] takeScreenshot( final @NotNull Activity activity, final @NotNull ILogger logger, @@ -40,6 +38,10 @@ public class ScreenshotUtils { } // Used by Hybrid SDKs + // Lint infers a UI-thread constraint from the View calls in captureScreenshot, which clashes with + // Bitmap.compress's @WorkerThread. captureScreenshot is safe from any thread, as it posts the + // view draw to the UI thread when it isn't already on it. + @SuppressLint("ThreadConstraint") public static @Nullable byte[] takeScreenshot( final @NotNull Activity activity, final @NotNull IThreadChecker threadChecker, @@ -57,8 +59,8 @@ public class ScreenshotUtils { * same way {@link io.sentry.android.core.ScreenshotEventProcessor} does for native errors. * * @see #captureMaskedScreenshot(Activity, SentryAndroidOptions, BuildInfoProvider, boolean) - * @noinspection unused */ + @SuppressWarnings("unused") public static @Nullable byte[] takeMaskedScreenshot( final @NotNull Activity activity, final @NotNull SentryAndroidOptions options, @@ -200,16 +202,15 @@ public class ScreenshotUtils { view.draw(canvas); latch.countDown(); } else { - activity.runOnUiThread( - () -> { - try { - view.draw(canvas); - } catch (Throwable e) { - logger.log(SentryLevel.ERROR, "Taking screenshot failed (view.draw).", e); - } finally { - latch.countDown(); - } - }); + activity.runOnUiThread(() -> { + try { + view.draw(canvas); + } catch (Throwable e) { + logger.log(SentryLevel.ERROR, "Taking screenshot failed (view.draw).", e); + } finally { + latch.countDown(); + } + }); } if (!latch.await(CAPTURE_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java index e618fea6883..80d0ea08c1f 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/SentryFrameMetricsCollector.java @@ -125,29 +125,26 @@ public SentryFrameMetricsCollector( // The Choreographer instance should be initialized asynchronously on the main thread to avoid // reflection during SDK init. new Handler(Looper.getMainLooper()) - .post( - () -> { - try { - choreographer = Choreographer.getInstance(); - } catch (Throwable e) { - logger.log( - SentryLevel.ERROR, - "Error retrieving Choreographer instance. Slow and frozen frames will not be reported.", - e); - } + .post(() -> { + try { + choreographer = Choreographer.getInstance(); + } catch (Throwable e) { + logger.log( + SentryLevel.ERROR, + "Error retrieving Choreographer instance. Slow and frozen frames will not be reported.", + e); + } - // Let's get the last frame timestamp from the choreographer private field - try { - choreographerLastFrameTimeField = - Choreographer.class.getDeclaredField("mLastFrameTimeNanos"); - choreographerLastFrameTimeField.setAccessible(true); - } catch (NoSuchFieldException e) { - logger.log( - SentryLevel.ERROR, - "Unable to get the frame timestamp from the choreographer: ", - e); - } - }); + // Let's get the last frame timestamp from the choreographer private field + try { + choreographerLastFrameTimeField = + Choreographer.class.getDeclaredField("mLastFrameTimeNanos"); + choreographerLastFrameTimeField.setAccessible(true); + } catch (NoSuchFieldException e) { + logger.log( + SentryLevel.ERROR, "Unable to get the frame timestamp from the choreographer: ", e); + } + }); frameMetricsAvailableListener = (window, frameMetrics, dropCountSinceLastInvocation) -> { @@ -264,6 +261,7 @@ public void onActivityResumed(@NotNull Activity activity) {} public void onActivityPaused(@NotNull Activity activity) {} @Override + @SuppressWarnings("ReferenceEquality") public void onActivityStopped(@NotNull Activity activity) { stopTrackingWindow(activity.getWindow()); if (currentWindow != null && currentWindow.get() == activity.getWindow()) { @@ -351,21 +349,21 @@ public void stopCollection(final @Nullable String listenerId) { private void stopTrackingWindow(final @NotNull Window window) { new Handler(Looper.getMainLooper()) - .post( - () -> { - try { - // Re-check if we should still remove the listener for this window - // in case trackCurrentWindow was called in the meantime - if (trackedWindows.remove(window)) { - windowFrameMetricsManager.removeOnFrameMetricsAvailableListener( - window, frameMetricsAvailableListener); - } - } catch (Throwable e) { - logger.log(SentryLevel.ERROR, "Failed to remove frameMetricsAvailableListener", e); - } - }); + .post(() -> { + try { + // Re-check if we should still remove the listener for this window + // in case trackCurrentWindow was called in the meantime + if (trackedWindows.remove(window)) { + windowFrameMetricsManager.removeOnFrameMetricsAvailableListener( + window, frameMetricsAvailableListener); + } + } catch (Throwable e) { + logger.log(SentryLevel.ERROR, "Failed to remove frameMetricsAvailableListener", e); + } + }); } + @SuppressWarnings("ReferenceEquality") private void setCurrentWindow(final @NotNull Window window) { if (currentWindow != null && currentWindow.get() == window) { return; @@ -389,23 +387,20 @@ private void trackCurrentWindow() { if (handler != null) { // Ensure the addOnFrameMetricsAvailableListener is called on the main thread new Handler(Looper.getMainLooper()) - .post( - () -> { - if (trackedWindows.add(window)) { - try { - windowFrameMetricsManager.addOnFrameMetricsAvailableListener( - window, frameMetricsAvailableListener, handler); - } catch (Throwable e) { - logger.log(SentryLevel.ERROR, "Failed to add frameMetricsAvailableListener", e); - } - } - }); + .post(() -> { + if (trackedWindows.add(window)) { + try { + windowFrameMetricsManager.addOnFrameMetricsAvailableListener( + window, frameMetricsAvailableListener, handler); + } catch (Throwable e) { + logger.log(SentryLevel.ERROR, "Failed to add frameMetricsAvailableListener", e); + } + } + }); } } - /** - * @return the last known time a frame was started, according to the Choreographer - */ + /** Returns the last known time a frame was started, according to the Choreographer. */ public long getLastKnownFrameStartTimeNanos() { // Let's read the choreographer private field to get start timestamp of the frame, which // uses System.nanoTime() under the hood @@ -417,6 +412,7 @@ public long getLastKnownFrameStartTimeNanos() { return choreographerFrameStartTime; } } catch (IllegalAccessException ignored) { + // The frame start time is unknown then, same as when the field is missing. } } return -1; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter.java index c7a449d1ef8..a4533456be2 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleCallbacksAdapter.java @@ -6,7 +6,8 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; -public class ActivityLifecycleCallbacksAdapter implements Application.ActivityLifecycleCallbacks { +public abstract class ActivityLifecycleCallbacksAdapter + implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {} diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleSpanHelper.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleSpanHelper.java index 61ee186bc99..5ed64e47e73 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleSpanHelper.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleSpanHelper.java @@ -14,7 +14,7 @@ import org.jetbrains.annotations.Nullable; @ApiStatus.Internal -public class ActivityLifecycleSpanHelper { +public final class ActivityLifecycleSpanHelper { private static final String APP_METRICS_ACTIVITIES_OP = "activity.load"; private final @NotNull String activityName; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleTimeSpan.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleTimeSpan.java index 52688a28567..61fe322cb5e 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleTimeSpan.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/ActivityLifecycleTimeSpan.java @@ -4,7 +4,7 @@ import org.jetbrains.annotations.NotNull; @ApiStatus.Internal -public class ActivityLifecycleTimeSpan implements Comparable { +public final class ActivityLifecycleTimeSpan implements Comparable { private final @NotNull TimeSpan onCreate = new TimeSpan(); private final @NotNull TimeSpan onStart = new TimeSpan(); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java index e49bada831a..2eff6ffc787 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/AppStartMetrics.java @@ -53,7 +53,7 @@ // public API. @SuppressWarnings("this-escape") @ApiStatus.Internal -public class AppStartMetrics extends ActivityLifecycleCallbacksAdapter { +public final class AppStartMetrics extends ActivityLifecycleCallbacksAdapter { public interface HeadlessAppStartListener { void onHeadlessAppStart(); } @@ -120,16 +120,16 @@ public AppStartMetrics() { } /** - * @return the app start span Uses Process.getStartUptimeMillis() as start timestamp, which - * requires API level 24+ + * Returns the app start span. It uses Process.getStartUptimeMillis() as start timestamp, which + * requires API level 24+. */ public @NotNull TimeSpan getAppStartTimeSpan() { return appStartSpan; } /** - * @return the app start span Uses Process.getStartUptimeMillis() as start timestamp, which - * requires API level 24+ + * Returns the app start span. It uses Process.getStartUptimeMillis() as start timestamp, which + * requires API level 24+. */ public @NotNull TimeSpan createProcessInitSpan() { // AppStartSpan and CLASS_LOADED_UPTIME_MS can be modified at any time. @@ -144,11 +144,12 @@ public AppStartMetrics() { } /** - * @return the SDK init time span. Uses ContentProvider/Sdk init time as start timestamp. It's the - * app start fallback below API 24, where the process start time isn't available. - *

Data is filled by either {@link io.sentry.android.core.SentryPerformanceProvider} with a - * fallback to {@link io.sentry.android.core.SentryAndroid}. At least the start timestamp - * should always be set. + * Returns the SDK init time span. Uses ContentProvider/Sdk init time as start timestamp. It's the + * app start fallback below API 24, where the process start time isn't available. + * + *

Data is filled by either {@link io.sentry.android.core.SentryPerformanceProvider} with a + * fallback to {@link io.sentry.android.core.SentryAndroid}. At least the start timestamp should + * always be set. */ public @NotNull TimeSpan getSdkInitTimeSpan() { return sdkInitTimeSpan; @@ -338,8 +339,8 @@ public long getClassLoadedUptimeMs() { } /** - * @return the app start time span if it was started, falls back to the sdk init time span - * otherwise + * Returns the app start time span if it was started, falls back to the sdk init time span + * otherwise. */ public @NotNull TimeSpan getAppStartTimeSpanWithFallback() { // If the app start type was never determined or app wasn't launched in foreground, @@ -464,8 +465,8 @@ public void setCachedStartInfo(final @Nullable ApplicationStartInfo cachedStartI * Called by instrumentation * * @param application The application object where onCreate was called on - * @noinspection unused */ + @SuppressWarnings("unused") public static void onApplicationCreate(final @NotNull Application application) { final long now = SystemClock.uptimeMillis(); @@ -480,8 +481,8 @@ public static void onApplicationCreate(final @NotNull Application application) { * Called by instrumentation * * @param application The application object where onCreate was called on - * @noinspection unused */ + @SuppressWarnings("unused") public static void onApplicationPostCreate(final @NotNull Application application) { final long now = SystemClock.uptimeMillis(); @@ -552,13 +553,12 @@ private void scheduleHeadlessAppStartCheckOnMain() { } Looper.getMainLooper() .getQueue() - .addIdleHandler( - () -> { - firstIdle = SystemClock.uptimeMillis(); - headlessAppStartCheckPending.set(false); - handleHeadlessAppStartIfNeededOnMain(); - return false; - }); + .addIdleHandler(() -> { + firstIdle = SystemClock.uptimeMillis(); + headlessAppStartCheckPending.set(false); + handleHeadlessAppStartIfNeededOnMain(); + return false; + }); } /** @@ -738,8 +738,8 @@ public void onActivityDestroyed(@NonNull Activity activity) { * Called by instrumentation * * @param contentProvider The content provider where onCreate was called on - * @noinspection unused */ + @SuppressWarnings("unused") public static void onContentProviderCreate(final @NotNull ContentProvider contentProvider) { final long now = SystemClock.uptimeMillis(); @@ -752,8 +752,8 @@ public static void onContentProviderCreate(final @NotNull ContentProvider conten * Called by instrumentation * * @param contentProvider The content provider where onCreate was called on - * @noinspection unused */ + @SuppressWarnings("unused") public static void onContentProviderPostCreate(final @NotNull ContentProvider contentProvider) { final long now = SystemClock.uptimeMillis(); diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/TimeSpan.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/TimeSpan.java index 5ea785165dc..b97a6527028 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/TimeSpan.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/TimeSpan.java @@ -17,7 +17,7 @@ * the time span. */ @ApiStatus.Internal -public class TimeSpan implements Comparable { +public final class TimeSpan implements Comparable { private @Nullable String description; private long startUnixTimeMs; @@ -36,6 +36,8 @@ public void setup( } /** + * Starts the time span at the given uptime. + * * @param uptimeMs the uptime in ms, provided by {@link SystemClock#uptimeMillis()} */ public void setStartedAt(final long uptimeMs) { @@ -52,6 +54,8 @@ public void stop() { } /** + * Stops the time span at the given uptime. + * * @param uptimeMs the uptime in ms, provided by {@link SystemClock#uptimeMillis()} */ public void setStoppedAt(final long uptimeMs) { @@ -75,23 +79,17 @@ public boolean hasNotStopped() { return stopUptimeMs == 0; } - /** - * @return the start timestamp of this measurement, as uptime, in ms - */ + /** Returns the start timestamp of this measurement, as uptime, in ms. */ public long getStartUptimeMs() { return startUptimeMs; } - /** - * @return the start timestamp of this measurement, unix time, in ms - */ + /** Returns the start timestamp of this measurement, unix time, in ms. */ public long getStartTimestampMs() { return startUnixTimeMs; } - /** - * @return the start timestamp of this measurement, unix time - */ + /** Returns the start timestamp of this measurement, unix time. */ public @Nullable SentryDate getStartTimestamp() { if (hasStarted()) { return new SentryLongDate(DateUtils.millisToNanos(getStartTimestampMs())); @@ -99,17 +97,15 @@ public long getStartTimestampMs() { return null; } - /** - * @return the start timestamp of this measurement, unix time, in seconds - */ + /** Returns the start timestamp of this measurement, unix time, in seconds. */ public double getStartTimestampSecs() { - return DateUtils.millisToSeconds(startUnixTimeMs); + return DateUtils.millisToSeconds((double) startUnixTimeMs); } /** - * @return the projected stop timestamp of this measurement, based on the start timestamp and the - * duration. If the time span was not started 0 is returned, if the time span was not stopped - * the start timestamp is returned. + * Returns the projected stop timestamp of this measurement, based on the start timestamp and the + * duration. If the time span was not started 0 is returned, if the time span was not stopped the + * start timestamp is returned. */ public long getProjectedStopTimestampMs() { if (hasStarted()) { @@ -119,15 +115,17 @@ public long getProjectedStopTimestampMs() { } /** - * @return the projected stop timestamp + * Returns the projected stop timestamp of this measurement, unix time, in seconds. + * * @see #getProjectedStopTimestampMs() */ public double getProjectedStopTimestampSecs() { - return DateUtils.millisToSeconds(getProjectedStopTimestampMs()); + return DateUtils.millisToSeconds((double) getProjectedStopTimestampMs()); } /** - * @return the projected stop timestamp + * Returns the projected stop timestamp of this measurement, or null if it was not stopped. + * * @see #getProjectedStopTimestampMs() */ public @Nullable SentryDate getProjectedStopTimestamp() { @@ -137,9 +135,7 @@ public double getProjectedStopTimestampSecs() { return null; } - /** - * @return the duration of this measurement, in ms, or 0 if no end time is set - */ + /** Returns the duration of this measurement, in ms, or 0 if no end time is set. */ public long getDurationMs() { if (hasStopped()) { return stopUptimeMs - startUptimeMs; diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/performance/WindowContentChangedCallback.java b/sentry-android-core/src/main/java/io/sentry/android/core/performance/WindowContentChangedCallback.java index 79180a7bd5a..09b4f6eafb6 100644 --- a/sentry-android-core/src/main/java/io/sentry/android/core/performance/WindowContentChangedCallback.java +++ b/sentry-android-core/src/main/java/io/sentry/android/core/performance/WindowContentChangedCallback.java @@ -4,7 +4,7 @@ import io.sentry.android.core.internal.gestures.WindowCallbackAdapter; import org.jetbrains.annotations.NotNull; -public class WindowContentChangedCallback extends WindowCallbackAdapter { +public final class WindowContentChangedCallback extends WindowCallbackAdapter { private final @NotNull Runnable callback; diff --git a/sentry-android-core/src/main/res/values/ids.xml b/sentry-android-core/src/main/res/values/ids.xml new file mode 100644 index 00000000000..5b6125d18e5 --- /dev/null +++ b/sentry-android-core/src/main/res/values/ids.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt index 71f477b24a1..fa0f8a7b2fa 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ANRWatchDogTest.kt @@ -60,7 +60,7 @@ class ANRWatchDogTest { es.submit { sut.run() } assertTrue( - latch.await(10L, TimeUnit.SECONDS) + latch.await(10L, TimeUnit.SECONDS), ) // Wait until worker posts the job for the "UI thread" var waitCount = 0 do { @@ -159,7 +159,7 @@ class ANRWatchDogTest { es.submit { sut.run() } assertTrue( - latch.await(10L, TimeUnit.SECONDS) + latch.await(10L, TimeUnit.SECONDS), ) // Wait until worker posts the job for the "UI thread" var waitCount = 0 do { @@ -215,7 +215,7 @@ class ANRWatchDogTest { es.submit { sut.run() } assertTrue( - latch.await(10L, TimeUnit.SECONDS) + latch.await(10L, TimeUnit.SECONDS), ) // Wait until worker posts the job for the "UI thread" var waitCount = 0 do { diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ActivityLifecycleIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ActivityLifecycleIntegrationTest.kt index d2a8f05b996..1e0d43f00dd 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ActivityLifecycleIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ActivityLifecycleIntegrationTest.kt @@ -261,7 +261,7 @@ class ActivityLifecycleIntegrationTest { contexts.any { it.operation == ActivityLifecycleIntegration.APP_START_COLD || it.operation == ActivityLifecycleIntegration.APP_START_WARM - } + }, ) } @@ -329,7 +329,7 @@ class ActivityLifecycleIntegrationTest { assertTrue( appStartTransaction.children.any { it.operation == ActivityLifecycleIntegration.APP_START_EXTENDED_OP - } + }, ) assertTrue(AppStartMetrics.getInstance().appStartExtension.isActive) assertNotNull(AppStartMetrics.getInstance().appStartExtension.extendedAppStartSpan) @@ -461,7 +461,7 @@ class ActivityLifecycleIntegrationTest { assertTrue( transaction.children.any { it.operation == ActivityLifecycleIntegration.APP_START_EXTENDED_OP - } + }, ) assertFalse(transaction.isFinished) @@ -868,7 +868,7 @@ class ActivityLifecycleIntegrationTest { it.tracesSampleRate = 1.0 it.isEnableTimeToFullDisplayTracing = true it.idleTimeout = 100 - } + }, ) // the transaction idle timeout is scheduled on the dedicated timer executor fixture.options.timerExecutorService = SentryExecutorService() @@ -939,7 +939,7 @@ class ActivityLifecycleIntegrationTest { initializer = { it.tracesSampleRate = 1.0 it.isEnableActivityLifecycleTracingAutoFinish = false - } + }, ) sut.register(fixture.scopes, fixture.options) val activity = mock() @@ -1422,7 +1422,7 @@ class ActivityLifecycleIntegrationTest { uiLoadTransaction.children.any { it.operation == ActivityLifecycleIntegration.APP_START_COLD || it.operation == ActivityLifecycleIntegration.APP_START_WARM - } + }, ) sut.onActivityPostCreated(activity, fixture.bundle) @@ -1627,7 +1627,7 @@ class ActivityLifecycleIntegrationTest { assertFalse( fixture.capturedContexts.drop(1).any { it.operation == ActivityLifecycleIntegration.STANDALONE_APP_START_OP - } + }, ) assertEquals(appStartTransaction.spanContext.traceId, uiLoadContext.traceId) // siblings, not parent/child: ui.load has no parent span id @@ -1656,7 +1656,7 @@ class ActivityLifecycleIntegrationTest { assertTrue( fixture.createdTransactions.single().children.any { it.operation == ActivityLifecycleIntegration.APP_START_COLD - } + }, ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidContinuousProfilerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidContinuousProfilerTest.kt index 0d137789c81..766e487ced7 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidContinuousProfilerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidContinuousProfilerTest.kt @@ -213,7 +213,7 @@ class AndroidContinuousProfilerTest { assertContains(it.measurements, ProfileMeasurement.ID_CPU_USAGE) assertContains(it.measurements, ProfileMeasurement.ID_MEMORY_FOOTPRINT) assertContains(it.measurements, ProfileMeasurement.ID_MEMORY_NATIVE_FOOTPRINT) - } + }, ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidLoggerBatchProcessorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidLoggerBatchProcessorTest.kt index d9f9b1e3edd..3463daf1819 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidLoggerBatchProcessorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidLoggerBatchProcessorTest.kt @@ -110,7 +110,7 @@ class AndroidLoggerBatchProcessorTest { val sut = fixture.getSut() sut.close(false) - assertTrue(AppState.getInstance().lifecycleObserver.listeners.isEmpty()) + assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) } @Test @@ -118,6 +118,6 @@ class AndroidLoggerBatchProcessorTest { val sut = fixture.getSut() sut.close(true) - assertTrue(AppState.getInstance().lifecycleObserver.listeners.isEmpty()) + assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidMetricsBatchProcessorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidMetricsBatchProcessorTest.kt index 7648a2b3bab..a8309a03b94 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidMetricsBatchProcessorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidMetricsBatchProcessorTest.kt @@ -109,7 +109,7 @@ class AndroidMetricsBatchProcessorTest { val sut = fixture.getSut() sut.close(false) - assertTrue(AppState.getInstance().lifecycleObserver.listeners.isEmpty()) + assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) } @Test @@ -117,6 +117,6 @@ class AndroidMetricsBatchProcessorTest { val sut = fixture.getSut() sut.close(true) - assertTrue(AppState.getInstance().lifecycleObserver.listeners.isEmpty()) + assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt index fc965c8782b..8fe3a9cb0da 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidOptionsInitializerTest.kt @@ -53,6 +53,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import org.junit.runner.RunWith 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 @@ -123,6 +124,7 @@ class AndroidOptionsInitializerTest { fun initSutWithClassLoader( classesToLoad: List = emptyList(), + loadedClasses: Map> = emptyMap(), isFragmentAvailable: Boolean = false, isTimberAvailable: Boolean = false, isReplayAvailable: Boolean = false, @@ -136,6 +138,9 @@ class AndroidOptionsInitializerTest { sentryOptions.isDebug = true val buildInfo = createBuildInfo() val loadClass = createClassMock(classesToLoad) + loadedClasses.forEach { (name, clazz) -> + whenever(loadClass.loadClass(eq(name), anyOrNull())).thenReturn(clazz) + } AndroidOptionsInitializer.loadDefaultAndMetadataOptions( sentryOptions, @@ -269,8 +274,8 @@ class AndroidOptionsInitializerTest { assertTrue( fixture.sentryOptions.cacheDirPath?.endsWith( - "${File.separator}cache${File.separator}sentry" - )!! + "${File.separator}cache${File.separator}sentry", + )!!, ) } @@ -280,7 +285,7 @@ class AndroidOptionsInitializerTest { assertTrue( AndroidOptionsInitializer.getCacheDir(fixture.context) .path - .endsWith("${File.separator}cache${File.separator}sentry") + .endsWith("${File.separator}cache${File.separator}sentry"), ) } @@ -290,8 +295,8 @@ class AndroidOptionsInitializerTest { assertTrue( fixture.sentryOptions.profilingTracesDirPath?.endsWith( - "${File.separator}cache${File.separator}sentry${File.separator}profiling_traces" - )!! + "${File.separator}cache${File.separator}sentry${File.separator}profiling_traces", + )!!, ) assertFalse(File(fixture.sentryOptions.profilingTracesDirPath!!).exists()) } @@ -302,8 +307,8 @@ class AndroidOptionsInitializerTest { assertTrue( fixture.sentryOptions.outboxPath?.endsWith( - "${File.separator}cache${File.separator}sentry${File.separator}outbox" - )!! + "${File.separator}cache${File.separator}sentry${File.separator}outbox", + )!!, ) } @@ -365,7 +370,7 @@ class AndroidOptionsInitializerTest { assertTrue(fixture.sentryOptions.transportGate is AndroidTransportGate) } - @Config(sdk = [Build.VERSION_CODES.N_MR1]) + @Config(sdk = [Build.VERSION_CODES.N]) @Test fun `init on API 25 and lower sets SSLSocketFactory with bundled Sentry root CAs`() { fixture.initSut(configureOptions = { dsn = SAAS_DSN }) @@ -373,7 +378,7 @@ class AndroidOptionsInitializerTest { assertIs(fixture.sentryOptions.sslSocketFactory) } - @Config(sdk = [Build.VERSION_CODES.N_MR1]) + @Config(sdk = [Build.VERSION_CODES.N]) @Test fun `init on API 25 and lower does not set SSLSocketFactory for self-hosted DSN`() { fixture.initSut(configureOptions = { dsn = "https://key@sentry.example.com/1" }) @@ -381,7 +386,7 @@ class AndroidOptionsInitializerTest { assertNull(fixture.sentryOptions.sslSocketFactory) } - @Config(sdk = [Build.VERSION_CODES.O]) + @Config(sdk = [30]) @Test fun `init on API 26 and higher does not set SSLSocketFactory`() { fixture.initSut(configureOptions = { dsn = SAAS_DSN }) @@ -389,7 +394,7 @@ class AndroidOptionsInitializerTest { assertNull(fixture.sentryOptions.sslSocketFactory) } - @Config(sdk = [Build.VERSION_CODES.N_MR1]) + @Config(sdk = [Build.VERSION_CODES.N]) @Test fun `init on API 25 and lower keeps user provided SSLSocketFactory`() { val sslSocketFactory = mock() @@ -397,7 +402,7 @@ class AndroidOptionsInitializerTest { configureOptions = { dsn = SAAS_DSN this.sslSocketFactory = sslSocketFactory - } + }, ) assertEquals(sslSocketFactory, fixture.sentryOptions.sslSocketFactory) @@ -428,11 +433,11 @@ class AndroidOptionsInitializerTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("PerfettoContinuousProfiling") + .contains("PerfettoContinuousProfiling"), ) } - @Config(sdk = [34]) + @Config(sdk = [33]) @Test fun `init below API 35 does not report PerfettoContinuousProfiling integration`() { SentryIntegrationPackageStorage.getInstance().clearStorage() @@ -441,18 +446,18 @@ class AndroidOptionsInitializerTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("PerfettoContinuousProfiling") + .contains("PerfettoContinuousProfiling"), ) } - @Config(sdk = [34]) + @Config(sdk = [33]) @Test fun `init below API 35 with enableLegacyProfiling true sets AndroidContinuousProfiler`() { fixture.initSut(configureOptions = { isEnableLegacyProfiling = true }) assertTrue(fixture.sentryOptions.continuousProfiler is AndroidContinuousProfiler) } - @Config(sdk = [34]) + @Config(sdk = [33]) @Test fun `init below API 35 with enableLegacyProfiling false noops profiler`() { fixture.initSut(configureOptions = { isEnableLegacyProfiling = false }) @@ -492,7 +497,7 @@ class AndroidOptionsInitializerTest { configureOptions = { profilesSampleRate = 1.0 isEnableLegacyProfiling = false - } + }, ) assertEquals(NoOpTransactionProfiler.getInstance(), fixture.sentryOptions.transactionProfiler) @@ -505,7 +510,7 @@ class AndroidOptionsInitializerTest { configureOptions = { profilesSampler = mock() isEnableLegacyProfiling = false - } + }, ) assertEquals(NoOpTransactionProfiler.getInstance(), fixture.sentryOptions.transactionProfiler) @@ -520,7 +525,7 @@ class AndroidOptionsInitializerTest { configureOptions = { profilesSampleRate = 1.0 isEnableLegacyProfiling = false - } + }, ) assertEquals(NoOpTransactionProfiler.getInstance(), fixture.sentryOptions.transactionProfiler) @@ -628,13 +633,24 @@ class AndroidOptionsInitializerTest { @Test fun `NdkIntegration will load SentryNdk class and add to the integration list`() { fixture.initSutWithClassLoader( - classesToLoad = listOfNotNull(NdkIntegration.SENTRY_NDK_CLASS_NAME) + classesToLoad = listOfNotNull(NdkIntegration.SENTRY_NDK_CLASS_NAME), ) val actual = fixture.sentryOptions.integrations.firstOrNull { it is NdkIntegration } assertNotNull((actual as NdkIntegration).sentryNdkClass) } + @Test + fun `NdkIntegration prefers the outproc backend class`() { + fixture.initSutWithClassLoader( + classesToLoad = listOfNotNull(NdkIntegration.SENTRY_NDK_CLASS_NAME), + loadedClasses = mapOf(NdkIntegration.SENTRY_NDK_OUTPROC_CLASS_NAME to Any::class.java), + ) + + val actual = fixture.sentryOptions.integrations.firstOrNull { it is NdkIntegration } + assertEquals(Any::class.java, (actual as NdkIntegration).sentryNdkClass) + } + @Test fun `NdkIntegration won't be enabled, if class not found`() { fixture.initSutWithClassLoader(classesToLoad = emptyList()) @@ -848,7 +864,7 @@ class AndroidOptionsInitializerTest { listOf( AndroidOptionsInitializer.COMPOSE_CLASS_NAME, AndroidOptionsInitializer.SENTRY_COMPOSE_GESTURE_INTEGRATION_CLASS_NAME, - ) + ), ) assertTrue { fixture.sentryOptions.gestureTargetLocators.size == 2 } @@ -884,7 +900,7 @@ class AndroidOptionsInitializerTest { fixture.initSut() assertIs( - fixture.sentryOptions.compositePerformanceCollector + fixture.sentryOptions.compositePerformanceCollector, ) } @@ -1016,7 +1032,7 @@ class AndroidOptionsInitializerTest { AndroidOptionsInitializer.getCacheDir(fixture.context), PersistingScopeObserver.SCOPE_CACHE, ) - .exists() + .exists(), ) } @@ -1032,7 +1048,7 @@ class AndroidOptionsInitializerTest { threadChecker = mock() setSocketTagger(mock()) compositePerformanceCollector = mock() - } + }, ) assertFalse { fixture.sentryOptions.transportGate is AndroidTransportGate } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidProfilerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidProfilerTest.kt index b208a471f48..88608d9a922 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidProfilerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidProfilerTest.kt @@ -151,12 +151,12 @@ class AndroidProfilerTest { assertFailsWith { ctor.newInstance( - arrayOf(null, 0, mock(), { mock() }, mock()) + arrayOf(null, 0, mock(), { mock() }, mock()), ) } assertFailsWith { ctor.newInstance( - arrayOf("mock", 0, null, { mock() }, mock()) + arrayOf("mock", 0, null, { mock() }, mock()), ) } assertFailsWith { diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidTransportGateTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidTransportGateTest.kt index 24817c85bdf..b275eaad8d2 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AndroidTransportGateTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AndroidTransportGateTest.kt @@ -31,14 +31,14 @@ class AndroidTransportGateTest { @Test fun `isConnected returns false if connection is not connected`() { assertFalse( - fixture.getSut().isConnected(IConnectionStatusProvider.ConnectionStatus.DISCONNECTED) + fixture.getSut().isConnected(IConnectionStatusProvider.ConnectionStatus.DISCONNECTED), ) } @Test fun `isConnected returns false if no permission`() { assertTrue( - fixture.getSut().isConnected(IConnectionStatusProvider.ConnectionStatus.NO_PERMISSION) + fixture.getSut().isConnected(IConnectionStatusProvider.ConnectionStatus.NO_PERMISSION), ) } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt index e41d5778a7f..5d43c28ede3 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AnrV2IntegrationTest.kt @@ -79,7 +79,7 @@ class AnrV2IntegrationTest : ApplicationExitIntegrationTestBase() { Cmd line: com.example.app:mainProcess """ .trimIndent() - .byteInputStream() + .byteInputStream(), ) } else { whenever(mock.traceInputStream) @@ -115,7 +115,7 @@ class AnrV2IntegrationTest : ApplicationExitIntegrationTestBase() { (no managed stack frames) """ .trimIndent() - .byteInputStream() + .byteInputStream(), ) } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AppLifecycleIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AppLifecycleIntegrationTest.kt index 896673085c2..eb417ee34bd 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AppLifecycleIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AppLifecycleIntegrationTest.kt @@ -69,9 +69,9 @@ class AppLifecycleIntegrationTest { assertNotNull(sut.watcher) Thread { - sut.close() - latch.countDown() - } + sut.close() + latch.countDown() + } .start() latch.await() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AppStartExtensionTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AppStartExtensionTest.kt index 38f7f29e7df..20d4dc0b194 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AppStartExtensionTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AppStartExtensionTest.kt @@ -49,9 +49,9 @@ class AppStartExtensionTest { val done = CountDownLatch(1) val run = { Thread { - call() - done.countDown() - } + call() + done.countDown() + } .start() succeeded.set(done.await(2, TimeUnit.SECONDS)) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/AppStateTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/AppStateTest.kt index 4fe39b20f2e..27a8604950c 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/AppStateTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/AppStateTest.kt @@ -331,9 +331,9 @@ class AppStateTest { // Add listeners concurrently listeners.forEach { listener -> Thread { - sut.addAppStateListener(listener) - latch.countDown() - } + sut.addAppStateListener(listener) + latch.countDown() + } .start() } latch.await() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoCrossIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoCrossIntegrationTest.kt index 8aceb6784e8..104e0f6b3bc 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoCrossIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoCrossIntegrationTest.kt @@ -35,7 +35,7 @@ import org.robolectric.shadows.ShadowActivityManager.ApplicationExitInfoBuilder // Our current Robolectric version (4.15) caps at API 35. All ApplicationExitInfo code paths we // exercise are at API 31 or below, so we use the latter. @RunWith(AndroidJUnit4::class) -@Config(sdk = [31]) +@Config(sdk = [33]) class ApplicationExitInfoCrossIntegrationTest { @get:Rule val tmpDir = TemporaryFolder() @@ -105,7 +105,7 @@ class ApplicationExitInfoCrossIntegrationTest { at android.os.Looper.loop(Looper.java:313) """ .trimIndent() - .byteInputStream() + .byteInputStream(), ) } shadowActivityManager.addApplicationExitInfo(exitInfo) @@ -121,8 +121,8 @@ class ApplicationExitInfoCrossIntegrationTest { whenever(mock.traceInputStream) .thenReturn( GZIPInputStream( - TombstoneIntegrationTest::class.java.getResourceAsStream("/tombstone.pb.gz") - ) + TombstoneIntegrationTest::class.java.getResourceAsStream("/tombstone.pb.gz"), + ), ) } shadowActivityManager.addApplicationExitInfo(exitInfo) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoEventProcessorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoEventProcessorTest.kt index 12c1bf08429..595e8bc28f1 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoEventProcessorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitInfoEventProcessorTest.kt @@ -820,7 +820,7 @@ class ApplicationExitInfoEventProcessorTest { brand = "Pixel" model = "3XL" memorySize = 4096 - } + }, ) platform = "NotAndroid" @@ -837,7 +837,7 @@ class ApplicationExitInfoEventProcessorTest { DebugImage().apply { type = DebugImage.PROGUARD uuid = "uuid1" - } + }, ) } user = @@ -893,7 +893,7 @@ class ApplicationExitInfoEventProcessorTest { lineno = 777 module = "io.sentry.samples.MainActivity" function = "run" - } + }, ) } @@ -905,7 +905,7 @@ class ApplicationExitInfoEventProcessorTest { name = "main" id = 13 this.stacktrace = stacktrace - } + }, ) } @@ -947,7 +947,7 @@ class ApplicationExitInfoEventProcessorTest { SentryThread().apply { name = "main" stacktrace = SentryStackTrace() - } + }, ) } @@ -966,7 +966,7 @@ class ApplicationExitInfoEventProcessorTest { SentryThread().apply { name = "main" stacktrace = SentryStackTrace() - } + }, ) } @@ -988,10 +988,10 @@ class ApplicationExitInfoEventProcessorTest { SentryStackFrame().apply { module = "io.sentry.samples.MainActivity" function = "run" - } - ) + }, + ), ) - } + }, ) } assertEquals(listOf("{{ default }}", "background-anr"), processedBackground.fingerprints) @@ -1008,10 +1008,10 @@ class ApplicationExitInfoEventProcessorTest { SentryStackFrame().apply { module = "io.sentry.samples.MainActivity" function = "run" - } - ) + }, + ), ) - } + }, ) } assertEquals(listOf("{{ default }}", "foreground-anr"), processedForeground.fingerprints) @@ -1026,7 +1026,7 @@ class ApplicationExitInfoEventProcessorTest { NoOpLogger.getInstance(), 0, true, - ) + ), ) val processed = @@ -1054,7 +1054,7 @@ class ApplicationExitInfoEventProcessorTest { NoOpLogger.getInstance(), 1_000, true, - ) + ), ) val processed = @@ -1074,7 +1074,7 @@ class ApplicationExitInfoEventProcessorTest { type = "MemoryLimitExceeded" value = expectedMessage mechanism = Mechanism().apply { type = "AppExitInfo" } - } + }, ) } @@ -1113,10 +1113,10 @@ class ApplicationExitInfoEventProcessorTest { module = "java.lang" filename = "Thread.java" function = "run" - } + }, ) } - } + }, ) } @@ -1142,10 +1142,10 @@ class ApplicationExitInfoEventProcessorTest { module = "java.lang" filename = "Thread.java" function = "run" - } + }, ) } - } + }, ) } @@ -1170,10 +1170,10 @@ class ApplicationExitInfoEventProcessorTest { SentryStackFrame().apply { module = "com.example.MyApp" function = "onCreate" - } + }, ) } - } + }, ) } @@ -1197,10 +1197,10 @@ class ApplicationExitInfoEventProcessorTest { SentryStackFrame().apply { module = "com.example.MyApp" function = "onCreate" - } + }, ) } - } + }, ) } assertNull(processed.contexts.profile) @@ -1237,7 +1237,7 @@ class ApplicationExitInfoEventProcessorTest { ), StackTraceElement("android.os.Handler", "dispatchMessage", "Handler.java", 5678), ), - ) + ), ) close() } @@ -1290,7 +1290,7 @@ class ApplicationExitInfoEventProcessorTest { StackTraceElement("com.example.MyApp", "blocked", "MyApp.java", 42), StackTraceElement("android.os.Handler", "dispatchMessage", "Handler.java", 5678), ), - ) + ), ) close() } @@ -1473,7 +1473,7 @@ class ApplicationExitInfoEventProcessorTest { timestamp, shouldEnrich, mechanism == "anr_background", - ) + ), ) } @@ -1487,7 +1487,7 @@ class ApplicationExitInfoEventProcessorTest { NoOpLogger.getInstance(), timestamp, shouldEnrich, - ) + ), ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitIntegrationTestBase.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitIntegrationTestBase.kt index 7db354ea64c..30214fe52c1 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitIntegrationTestBase.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ApplicationExitIntegrationTestBase.kt @@ -27,7 +27,6 @@ import org.junit.Rule import org.junit.rules.TemporaryFolder import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull -import org.mockito.kotlin.anyVararg import org.mockito.kotlin.argThat import org.mockito.kotlin.atMost import org.mockito.kotlin.check @@ -172,7 +171,7 @@ abstract class ApplicationExitIntegrationTestBase { verify(fixture.scopes).captureEvent(any(), anyOrNull()) verify(fixture.logger, never()) - .log(any(), argThat { startsWith(config.flushLogPrefix) }, anyVararg()) + .log(any(), argThat { startsWith(config.flushLogPrefix) }, any(), any()) } @Test @@ -185,7 +184,7 @@ abstract class ApplicationExitIntegrationTestBase { verify(fixture.scopes).captureEvent(any(), anyOrNull()) verify(fixture.logger, never()) - .log(any(), argThat { startsWith(config.flushLogPrefix) }, anyVararg()) + .log(any(), argThat { startsWith(config.flushLogPrefix) }, any(), any()) } @Test @@ -317,7 +316,6 @@ abstract class ApplicationExitIntegrationTestBase { .log( any(), argThat { startsWith("Timed out waiting to flush previous session to its own file.") }, - anyVararg(), ) } @@ -338,7 +336,6 @@ abstract class ApplicationExitIntegrationTestBase { .log( any(), argThat { startsWith("Timed out waiting to flush previous session to its own file.") }, - anyVararg(), ) verify(fixture.scopes).captureEvent(any(), any()) } @@ -355,7 +352,6 @@ abstract class ApplicationExitIntegrationTestBase { .log( any(), argThat { startsWith("Timed out waiting to flush previous session to its own file.") }, - anyVararg(), ) assertTrue((fixture.options.envelopeDiskCache as EnvelopeCache).waitPreviousSessionFlush()) } @@ -407,7 +403,7 @@ abstract class ApplicationExitIntegrationTestBase { ) protected class ApplicationExitTestFixture( - private val config: IntegrationTestConfig + private val config: IntegrationTestConfig, ) { lateinit var context: Context lateinit var shadowActivityManager: ShadowActivityManager diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ContextUtilsTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ContextUtilsTest.kt index 2e540ee13df..b0787b0b9a8 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ContextUtilsTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ContextUtilsTest.kt @@ -139,12 +139,12 @@ class ContextUtilsTest { mockedPackageManager.getApplicationInfo( any(), any(), - ) + ), ) .thenReturn(mockedApplicationInfo) whenever( - mockedPackageManager.getPackageInfo(any(), any()) + mockedPackageManager.getPackageInfo(any(), any()), ) .thenReturn(mockedPackageInfo) @@ -200,7 +200,7 @@ class ContextUtilsTest { availMem = 128 totalMem = 2048 lowMemory = true - } + }, ) val memInfo = ContextUtils.getMemInfo(context, logger) assertEquals(128, memInfo!!.availMem) @@ -257,8 +257,8 @@ class ContextUtilsTest { processName = "io.sentry.android.core.test" pid = Process.myPid() importance = RunningAppProcessInfo.IMPORTANCE_TOP_SLEEPING - } - ) + }, + ), ) assertFalse(ContextUtils.isForegroundImportance()) } @@ -299,18 +299,18 @@ class ContextUtilsTest { assertTrue( ContextUtils.appIsLibraryForComposePreview( - getMockContext("com.example.library.test", "androidx.compose.ui.tooling.PreviewActivity") - ) + getMockContext("com.example.library.test", "androidx.compose.ui.tooling.PreviewActivity"), + ), ) assertFalse( ContextUtils.appIsLibraryForComposePreview( - getMockContext("com.example.library.test", "com.example.HomeActivity") - ) + getMockContext("com.example.library.test", "com.example.HomeActivity"), + ), ) assertFalse( ContextUtils.appIsLibraryForComposePreview( - getMockContext("com.example.library", "androidx.compose.ui.tooling.PreviewActivity") - ) + getMockContext("com.example.library", "androidx.compose.ui.tooling.PreviewActivity"), + ), ) } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ContextUtilsTestHelper.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ContextUtilsTestHelper.kt index cd09d280d1a..9d18a4fd405 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ContextUtilsTestHelper.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ContextUtilsTestHelper.kt @@ -23,7 +23,10 @@ object ContextUtilsTestHelper { whenever(mockContext.packageName).thenReturn("io.sentry.sample.test") whenever(mockContext.packageManager).thenReturn(mockPackageManager) whenever( - mockPackageManager.getApplicationInfo(mockContext.packageName, PackageManager.GET_META_DATA) + mockPackageManager.getApplicationInfo( + mockContext.packageName, + PackageManager.GET_META_DATA, + ), ) .thenReturn(mockApplicationInfo) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/DefaultAndroidEventProcessorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/DefaultAndroidEventProcessorTest.kt index 460e0bbec1d..3badbdbd853 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/DefaultAndroidEventProcessorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/DefaultAndroidEventProcessorTest.kt @@ -194,7 +194,7 @@ class DefaultAndroidEventProcessorTest { SentryThread().apply { id = 10L isCurrent = true - } + }, ) } @@ -582,8 +582,8 @@ class DefaultAndroidEventProcessorTest { function = "onCreate" module = "com.example.Application" filename = "Application.java" - } - ) + }, + ), ) }, SentryException().apply { @@ -598,8 +598,8 @@ class DefaultAndroidEventProcessorTest { function = "run" module = "com.android.internal.os.RuntimeInit\$MethodAndArgsCaller" filename = "RuntimeInit.java" - } - ) + }, + ), ) }, ) @@ -629,8 +629,8 @@ class DefaultAndroidEventProcessorTest { function = "onCreate" module = "com.example.Application" filename = "Application.java" - } - ) + }, + ), ) }, SentryException().apply { @@ -643,8 +643,8 @@ class DefaultAndroidEventProcessorTest { function = "onCreate" module = "com.example.Application" filename = "Application.java" - } - ) + }, + ), ) }, ) @@ -689,7 +689,7 @@ class DefaultAndroidEventProcessorTest { DateUtils.dateToSeconds(DateUtils.getDateTime("2004-04-10T18:24:03.000Z")), "message", SentryLogLevel.WARN, - ) + ), ) assertNotNull(processedEvent?.attributes?.get("device.brand")) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/DeviceInfoUtilTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/DeviceInfoUtilTest.kt index fffdf6257ea..5d75ae983cc 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/DeviceInfoUtilTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/DeviceInfoUtilTest.kt @@ -32,7 +32,7 @@ class DeviceInfoUtilTest { context.sendStickyBroadcast( Intent(Intent.ACTION_BATTERY_CHANGED) .putExtra(BatteryManager.EXTRA_LEVEL, 75) - .putExtra(BatteryManager.EXTRA_PLUGGED, 0) + .putExtra(BatteryManager.EXTRA_PLUGGED, 0), ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/EnvelopeFileObserverIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/EnvelopeFileObserverIntegrationTest.kt index 0b13f4ca4d8..fb2c23fff9c 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/EnvelopeFileObserverIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/EnvelopeFileObserverIntegrationTest.kt @@ -31,7 +31,7 @@ class EnvelopeFileObserverIntegrationTest { val logger = mock() fun getSut( - optionConfiguration: (SentryAndroidOptions) -> Unit = {} + optionConfiguration: (SentryAndroidOptions) -> Unit = {}, ): EnvelopeFileObserverIntegration { options = SentryAndroidOptions() options.setLogger(logger) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/FeedbackShakeIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/FeedbackShakeIntegrationTest.kt index f2118fb76de..82f7964bf04 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/FeedbackShakeIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/FeedbackShakeIntegrationTest.kt @@ -472,7 +472,7 @@ class FeedbackShakeIntegrationTest { val intervalNs = 20_000_000L for (i in 0 until 20) { listener.onSensorChanged( - createSensorEvent(floatArrayOf(20f, 0f, 0f), baseTimestamp + i * intervalNs) + createSensorEvent(floatArrayOf(20f, 0f, 0f), baseTimestamp + i * intervalNs), ) } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt index 031df4c523c..baa46fdd3bb 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/InternalSentrySdkTest.kt @@ -160,10 +160,10 @@ class InternalSentrySdkTest { metrics.appStartType = AppStartMetrics.AppStartType.WARM metrics.appStartTimeSpan.setStartedAt( - 20 + 20, ) // Can't be 0, as that's the default value if not set metrics.appStartTimeSpan.setStartUnixTimeMs( - 20 + 20, ) // The order matters, unix time must be set after started at in tests to avoid overwrite metrics.appStartTimeSpan.setStoppedAt(200) metrics.classLoadedUptimeMs = 100 @@ -171,29 +171,29 @@ class InternalSentrySdkTest { AppStartMetrics.onApplicationCreate(mock()) metrics.applicationOnCreateTimeSpan.description = "Application created" metrics.applicationOnCreateTimeSpan.setStartedAt( - 30 + 30, ) // Can't be 0, as that's the default value if not set metrics.applicationOnCreateTimeSpan.setStartUnixTimeMs( - 30 + 30, ) // The order matters, unix time must be set after started at in tests to avoid overwrite metrics.applicationOnCreateTimeSpan.setStoppedAt(40) val activityLifecycleSpan = ActivityLifecycleTimeSpan() activityLifecycleSpan.onCreate.description = "Test Activity Lifecycle onCreate" activityLifecycleSpan.onCreate.setStartedAt( - 50 + 50, ) // Can't be 0, as that's the default value if not set activityLifecycleSpan.onCreate.setStartUnixTimeMs( - 50 + 50, ) // The order matters, unix time must be set after started at in tests to avoid overwrite activityLifecycleSpan.onCreate.setStoppedAt(60) activityLifecycleSpan.onStart.description = "Test Activity Lifecycle onStart" activityLifecycleSpan.onStart.setStartedAt( - 70 + 70, ) // Can't be 0, as that's the default value if not set activityLifecycleSpan.onStart.setStartUnixTimeMs( - 70 + 70, ) // The order matters, unix time must be set after started at in tests to avoid overwrite activityLifecycleSpan.onStart.setStoppedAt(80) metrics.addActivityLifecycleTimeSpans(activityLifecycleSpan) @@ -214,10 +214,10 @@ class InternalSentrySdkTest { metrics.appStartType = AppStartMetrics.AppStartType.WARM metrics.appStartTimeSpan.setStartedAt( - 20 + 20, ) // Can't be 0, as that's the default value if not set metrics.appStartTimeSpan.setStartUnixTimeMs( - 20 + 20, ) // The order matters, unix time must be set after started at in tests to avoid overwrite metrics.appStartTimeSpan.setStoppedAt(200) metrics.classLoadedUptimeMs = 100 @@ -225,10 +225,10 @@ class InternalSentrySdkTest { AppStartMetrics.onApplicationCreate(mock()) metrics.applicationOnCreateTimeSpan.description = "Application created" metrics.applicationOnCreateTimeSpan.setStartedAt( - 30 + 30, ) // Can't be 0, as that's the default value if not set metrics.applicationOnCreateTimeSpan.setStartUnixTimeMs( - 30 + 30, ) // The order matters, unix time must be set after started at in tests to avoid overwrite metrics.applicationOnCreateTimeSpan.setStoppedAt(40) } @@ -239,10 +239,10 @@ class InternalSentrySdkTest { metrics.appStartType = AppStartMetrics.AppStartType.WARM metrics.appStartTimeSpan.setStartedAt( - 20 + 20, ) // Can't be 0, as that's the default value if not set metrics.appStartTimeSpan.setStartUnixTimeMs( - 20 + 20, ) // The order matters, unix time must be set after started at in tests to avoid overwrite metrics.appStartTimeSpan.setStoppedAt(200) metrics.classLoadedUptimeMs = 100 @@ -250,7 +250,7 @@ class InternalSentrySdkTest { AppStartMetrics.onApplicationCreate(mock()) metrics.applicationOnCreateTimeSpan.description = "Application created" metrics.applicationOnCreateTimeSpan.setStartedAt( - 30 + 30, ) // Can't be 0, as that's the default value if not set val activityLifecycleSpan = @@ -400,7 +400,7 @@ class InternalSentrySdkTest { val serializedScope = InternalSentrySdk.serializeScope(context, options, scope) assertTrue( - ((serializedScope["contexts"] as Map<*, *>)["app"] as Map<*, *>).containsKey("app_name") + ((serializedScope["contexts"] as Map<*, *>)["app"] as Map<*, *>).containsKey("app_name"), ) } @@ -478,7 +478,7 @@ class InternalSentrySdkTest { val capturedNewSessionStart = fixture.options.serializer.deserialize( InputStreamReader( - ByteArrayInputStream(capturedStartSessionEnvelope.items.toList()[0].data) + ByteArrayInputStream(capturedStartSessionEnvelope.items.toList()[0].data), ), Session::class.java, )!! @@ -518,7 +518,7 @@ class InternalSentrySdkTest { // when capture envelope is called with an unhandled event through the non-terminating API fixture.captureEnvelopeNonTerminatingWithEvent( - fixture.createSentryEventWithUnhandledException() + fixture.createSentryEventWithUnhandledException(), ) // then only the original event envelope is captured, without a session item @@ -577,7 +577,7 @@ class InternalSentrySdkTest { fixture.init(context) fixture.captureEnvelopeNonTerminatingWithEvent( - fixture.createSentryEventWithUnhandledException() + fixture.createSentryEventWithUnhandledException(), ) fixture.capturedEnvelopes.clear() @@ -606,7 +606,7 @@ class InternalSentrySdkTest { fixture.init(context) fixture.captureEnvelopeNonTerminatingWithEvent( - fixture.createSentryEventWithUnhandledException() + fixture.createSentryEventWithUnhandledException(), ) val unhandledSession = AtomicReference() Sentry.configureScope { scope -> unhandledSession.set(scope.session) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/LifecycleWatcherTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/LifecycleWatcherTest.kt index ba8b97d1fcf..80535311608 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/LifecycleWatcherTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/LifecycleWatcherTest.kt @@ -204,7 +204,7 @@ class LifecycleWatcherTest { assertEquals("navigation", it.type) assertEquals(SentryLevel.INFO, it.level) // cant assert data, its not a public API - } + }, ) } @@ -227,7 +227,7 @@ class LifecycleWatcherTest { assertEquals("navigation", it.type) assertEquals(SentryLevel.INFO, it.level) // cant assert data, its not a public API - } + }, ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt index dbd22609467..f9698cfdf2d 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ManifestMetadataReaderTest.kt @@ -1171,7 +1171,8 @@ class ManifestMetadataReaderTest { // Arrange val bundle = bundleOf( - ManifestMetadataReader.TRACE_PROPAGATION_TARGETS to """localhost,^(http|https)://api\..*$""" + ManifestMetadataReader.TRACE_PROPAGATION_TARGETS to + """localhost,^(http|https)://api\..*$""", ) val context = fixture.getContext(metaData = bundle) @@ -1185,6 +1186,32 @@ class ManifestMetadataReaderTest { ) } + @Test + fun `applyMetadata reads webView tracing allowed hosts to options`() { + // Arrange + val bundle = + bundleOf(ManifestMetadataReader.WEBVIEW_TRACING_ALLOWED_HOSTS to "example.com,other.com") + val context = fixture.getContext(metaData = bundle) + + // Act + ManifestMetadataReader.applyMetadata(context, fixture.options, fixture.buildInfoProvider) + + // Assert + assertEquals(listOf("example.com", "other.com"), fixture.options.webViewTracing.allowedHosts) + } + + @Test + fun `applyMetadata keeps webView tracing allowed hosts empty by default`() { + // Arrange + val context = fixture.getContext() + + // Act + ManifestMetadataReader.applyMetadata(context, fixture.options, fixture.buildInfoProvider) + + // Assert + assertTrue(fixture.options.webViewTracing.allowedHosts.isEmpty()) + } + @Test fun `applyMetadata reads null tracePropagationTargets and sets empty list`() { // Arrange @@ -1686,7 +1713,7 @@ class ManifestMetadataReaderTest { val bundle = bundleOf( ManifestMetadataReader.SENTRY_GRADLE_PLUGIN_INTEGRATIONS to - "Database Instrumentation,OkHttp Instrumentation" + "Database Instrumentation,OkHttp Instrumentation", ) val context = fixture.getContext(metaData = bundle) @@ -1964,13 +1991,13 @@ class ManifestMetadataReaderTest { // Assert assertTrue( fixture.options.sessionReplay.unmaskViewClasses.contains( - SentryReplayOptions.IMAGE_VIEW_CLASS_NAME - ) + SentryReplayOptions.IMAGE_VIEW_CLASS_NAME, + ), ) assertTrue( fixture.options.sessionReplay.unmaskViewClasses.contains( - SentryReplayOptions.TEXT_VIEW_CLASS_NAME - ) + SentryReplayOptions.TEXT_VIEW_CLASS_NAME, + ), ) } @@ -1985,13 +2012,13 @@ class ManifestMetadataReaderTest { // Assert assertTrue( fixture.options.sessionReplay.maskViewClasses.contains( - SentryReplayOptions.IMAGE_VIEW_CLASS_NAME - ) + SentryReplayOptions.IMAGE_VIEW_CLASS_NAME, + ), ) assertTrue( fixture.options.sessionReplay.maskViewClasses.contains( - SentryReplayOptions.TEXT_VIEW_CLASS_NAME - ) + SentryReplayOptions.TEXT_VIEW_CLASS_NAME, + ), ) } @@ -2067,7 +2094,7 @@ class ManifestMetadataReaderTest { val bundle = bundleOf( ManifestMetadataReader.IGNORED_ERRORS_FOR_DEDUPLICATION to - "example.FirstException,example.SecondException" + "example.FirstException,example.SecondException", ) val context = fixture.getContext(metaData = bundle) @@ -2107,7 +2134,7 @@ class ManifestMetadataReaderTest { // Arrange val bundle = bundleOf( - ManifestMetadataReader.IN_APP_INCLUDES to "com.example.package1,com.example.package2" + ManifestMetadataReader.IN_APP_INCLUDES to "com.example.package1,com.example.package2", ) val context = fixture.getContext(metaData = bundle) @@ -2138,7 +2165,7 @@ class ManifestMetadataReaderTest { // Arrange val bundle = bundleOf( - ManifestMetadataReader.IN_APP_EXCLUDES to "com.example.excluded1,com.example.excluded2" + ManifestMetadataReader.IN_APP_EXCLUDES to "com.example.excluded1,com.example.excluded2", ) val context = fixture.getContext(metaData = bundle) @@ -2748,7 +2775,7 @@ class ManifestMetadataReaderTest { val bundle = bundleOf( ManifestMetadataReader.REPLAYS_NETWORK_DETAIL_ALLOW_URLS to - " https://api.example.com/.* , https://cdn.example.com/.* " + " https://api.example.com/.* , https://cdn.example.com/.* ", ) val context = fixture.getContext(metaData = bundle) @@ -2768,7 +2795,7 @@ class ManifestMetadataReaderTest { val bundle = bundleOf( ManifestMetadataReader.REPLAYS_NETWORK_REQUEST_HEADERS to - " Authorization , X-Custom-Header " + " Authorization , X-Custom-Header ", ) val context = fixture.getContext(metaData = bundle) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/NdkIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/NdkIntegrationTest.kt index ae73a394050..29bdf7ddd88 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/NdkIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/NdkIntegrationTest.kt @@ -1,5 +1,6 @@ package io.sentry.android.core +import android.content.Context import io.sentry.ILogger import io.sentry.IScopes import io.sentry.SentryLevel @@ -18,6 +19,8 @@ class NdkIntegrationTest { val logger = mock() fun getSut(clazz: Class<*>? = SentryNdk::class.java): NdkIntegration = NdkIntegration(clazz) + + fun getSut(context: Context, clazz: Class<*>): NdkIntegration = NdkIntegration(context, clazz) } private val fixture = Fixture() @@ -95,6 +98,20 @@ class NdkIntegrationTest { assertFalse(options.isEnableScopeSync) } + @Test + fun `NdkIntegration falls back to init without context`() { + val integration = fixture.getSut(mock(), SentryNdk::class.java) + + val options = getOptions() + + integration.register(fixture.scopes, options) + + verify(fixture.logger).log(eq(SentryLevel.WARNING), any()) + verify(fixture.logger, never()).log(eq(SentryLevel.ERROR), any(), any()) + assertTrue(options.isEnableNdk) + assertTrue(options.isEnableScopeSync) + } + @Test fun `NdkIntegration won't close if close method is not available`() { val integration = fixture.getSut(SentryNdkNoClose::class.java) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/NetworkBreadcrumbsIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/NetworkBreadcrumbsIntegrationTest.kt index 8085189b029..370db8de182 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/NetworkBreadcrumbsIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/NetworkBreadcrumbsIntegrationTest.kt @@ -120,7 +120,7 @@ class NetworkBreadcrumbsIntegrationTest { assertEquals("network.event", it.category) assertEquals(SentryLevel.INFO, it.level) assertEquals("NETWORK_AVAILABLE", it.data["action"]) - } + }, ) } @@ -142,7 +142,7 @@ class NetworkBreadcrumbsIntegrationTest { assertEquals("network.event", it.category) assertEquals(SentryLevel.INFO, it.level) assertEquals("NETWORK_LOST", it.data["action"]) - } + }, ) } @@ -436,7 +436,7 @@ class NetworkBreadcrumbsIntegrationTest { } private fun KInOrder.verifyBreadcrumbInOrder( - check: (detail: NetworkBreadcrumbConnectionDetail) -> Unit + check: (detail: NetworkBreadcrumbConnectionDetail) -> Unit, ) { verify(fixture.scopes, times(1)) .addBreadcrumb( diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoContinuousProfilerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoContinuousProfilerTest.kt index 3bafc29be3d..cc0d63bb6a1 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoContinuousProfilerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoContinuousProfilerTest.kt @@ -80,7 +80,7 @@ class PerfettoContinuousProfilerTest { } fun getSut( - optionConfig: ((options: SentryAndroidOptions) -> Unit) = {} + optionConfig: ((options: SentryAndroidOptions) -> Unit) = {}, ): PerfettoContinuousProfiler { options.executorService = executor optionConfig(options) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoProfilerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoProfilerTest.kt index a21ca435b6a..a745143a38e 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoProfilerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/PerfettoProfilerTest.kt @@ -151,7 +151,7 @@ class PerfettoProfilerTest { val result = AtomicReference(File("sentinel")) capturedCallback.accept( - mockResult(errorCode = ProfilingResult.ERROR_UNKNOWN, errorMessage = "unknown error") + mockResult(errorCode = ProfilingResult.ERROR_UNKNOWN, errorMessage = "unknown error"), ) profiler.endAndCollect { result.set(it) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/PerformanceAndroidEventProcessorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/PerformanceAndroidEventProcessorTest.kt index c4f1a73c8a4..652f38ba743 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/PerformanceAndroidEventProcessorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/PerformanceAndroidEventProcessorTest.kt @@ -281,7 +281,7 @@ class PerformanceAndroidEventProcessorTest { emptyMap(), emptyMap(), null, - ) + ), ) tr.spans.add( SentrySpan( @@ -297,7 +297,7 @@ class PerformanceAndroidEventProcessorTest { emptyMap(), emptyMap(), null, - ) + ), ) tr.spans.add( SentrySpan( @@ -313,7 +313,7 @@ class PerformanceAndroidEventProcessorTest { emptyMap(), emptyMap(), null, - ) + ), ) tr = sut.process(tr, Hint()) @@ -606,7 +606,7 @@ class PerformanceAndroidEventProcessorTest { assertTrue(tr.spans.any { "process.load" == it.op && appStartSpan.spanId == it.parentSpanId }) assertTrue( - tr.spans.any { "contentprovider.load" == it.op && appStartSpan.spanId == it.parentSpanId } + tr.spans.any { "contentprovider.load" == it.op && appStartSpan.spanId == it.parentSpanId }, ) assertTrue(tr.spans.any { "application.load" == it.op }) @@ -707,7 +707,7 @@ class PerformanceAndroidEventProcessorTest { "contentprovider.load" == it.op || "application.load" == it.op || "activity.load" == it.op - } + }, ) } @@ -758,7 +758,7 @@ class PerformanceAndroidEventProcessorTest { "contentprovider.load" == it.op || "application.load" == it.op || "activity.load" == it.op - } + }, ) } @@ -1228,7 +1228,7 @@ class PerformanceAndroidEventProcessorTest { } private fun createUiLoadTransactionWithAppStartChildSpan( - coldStart: Boolean = true + coldStart: Boolean = true, ): SentryTransaction = createUiLoadTransaction().also { txn -> txn.spans.add(createAppStartSpan(txn.contexts.trace!!.traceId, coldStart)) @@ -1237,7 +1237,7 @@ class PerformanceAndroidEventProcessorTest { private fun createUiLoadTransaction(): SentryTransaction = createTransaction(UI_LOAD_OP) private fun createStandaloneAppStartTransaction( - appStartScreen: String? = null + appStartScreen: String? = null, ): SentryTransaction = createTransaction(STANDALONE_APP_START_OP).also { txn -> if (appStartScreen != null) { diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/ScreenshotEventProcessorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/ScreenshotEventProcessorTest.kt index e875e7845a0..468934e770c 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/ScreenshotEventProcessorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/ScreenshotEventProcessorTest.kt @@ -602,7 +602,7 @@ private class EllipsizedTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Ellipsize middle @@ -618,7 +618,7 @@ private class EllipsizedTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Ellipsize start @@ -634,7 +634,7 @@ private class EllipsizedTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Non-ellipsized text for comparison @@ -648,7 +648,7 @@ private class EllipsizedTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) setContentView(linearLayout) @@ -785,7 +785,7 @@ private class MultiLineTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Multi-line text with maxLines = 3 (wraps but capped) @@ -800,7 +800,7 @@ private class MultiLineTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) // Short single-line text for comparison @@ -814,7 +814,7 @@ private class MultiLineTextActivity : Activity() { LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply { setMargins(0, 8, 0, 0) } - } + }, ) setContentView(linearLayout) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SendCachedEnvelopeIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SendCachedEnvelopeIntegrationTest.kt index df9ce60883e..46df2ee227c 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SendCachedEnvelopeIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SendCachedEnvelopeIntegrationTest.kt @@ -1,5 +1,6 @@ package io.sentry.android.core +import com.google.common.truth.Truth.assertThat import io.sentry.IConnectionStatusProvider import io.sentry.IConnectionStatusProvider.ConnectionStatus import io.sentry.ILogger @@ -62,7 +63,7 @@ class SendCachedEnvelopeIntegrationTest { sender } else { null - } + }, ) return SendCachedEnvelopeIntegration(factory, LazyEvaluator { hasStartupCrashMarker }) @@ -137,6 +138,27 @@ class SendCachedEnvelopeIntegrationTest { verify(fixture.sender).send() } + @Test + fun `when interrupted while awaiting the task, keeps the interrupt and continues in the background`() { + // the delay keeps the task running, so the wait for it sees the interrupt + val sut = fixture.getSut(hasStartupCrashMarker = true, delaySend = 500) + + Thread.currentThread().interrupt() + try { + sut.register(fixture.scopes, fixture.options) + + assertThat(Thread.currentThread().isInterrupted).isTrue() + } finally { + // don't leak the interrupt into other tests + Thread.interrupted() + } + verify(fixture.logger) + .log(eq(DEBUG), eq("Synchronous send interrupted, continuing in the background.")) + + await.untilFalse(fixture.flag) + verify(fixture.sender).send() + } + @Test fun `registers for network connection changes`() { val sut = diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt index a68d892fe90..0ee138be148 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryAndroidOptionsTest.kt @@ -34,13 +34,13 @@ class SentryAndroidOptionsTest { assertTrue( sdkVersion.packageSet.any { it.name == "maven:io.sentry:sentry-android-core" && it.version == BuildConfig.VERSION_NAME - } + }, ) assertTrue( sdkVersion.packageSet.any { it.name == "maven:io.sentry:sentry" && it.version == BuildConfig.VERSION_NAME - } + }, ) } @@ -195,7 +195,7 @@ class SentryAndroidOptionsTest { fun `ndk handler strategy option can be changed`() { val sentryOptions = SentryAndroidOptions() sentryOptions.setNativeHandlerStrategy( - NdkHandlerStrategy.SENTRY_HANDLER_STRATEGY_CHAIN_AT_START + NdkHandlerStrategy.SENTRY_HANDLER_STRATEGY_CHAIN_AT_START, ) assertEquals( NdkHandlerStrategy.SENTRY_HANDLER_STRATEGY_CHAIN_AT_START.value, @@ -271,6 +271,18 @@ class SentryAndroidOptionsTest { assertEquals(10000L, sentryOptions.tombstoneMergeTimeThresholdMillis) } + @Test + fun `webView tracing allowed hosts are empty by default and copied when set`() { + val sentryOptions = SentryAndroidOptions() + assertTrue(sentryOptions.webViewTracing.allowedHosts.isEmpty()) + + val hosts = mutableListOf("example.com") + sentryOptions.webViewTracing.allowedHosts = hosts + hosts.add("other.com") + + assertEquals(listOf("example.com"), sentryOptions.webViewTracing.allowedHosts) + } + private class CustomDebugImagesLoader : IDebugImagesLoader { override fun loadDebugImages(): List? = 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 8c0ee5f7fe4..dc2472e6a6d 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 @@ -85,6 +85,7 @@ import org.robolectric.annotation.Config import org.robolectric.shadow.api.Shadow import org.robolectric.shadows.ShadowActivityManager import org.robolectric.shadows.ShadowActivityManager.ApplicationExitInfoBuilder +import org.robolectric.shadows.ShadowApplication import timber.log.Timber @RunWith(AndroidJUnit4::class) @@ -164,7 +165,7 @@ class SentryAndroidTest { (no managed stack frames) """ .trimIndent() - .byteInputStream() + .byteInputStream(), ) } shadowActivityManager.addApplicationExitInfo(exitInfo) @@ -292,14 +293,14 @@ class SentryAndroidTest { minEventLevel = FATAL, minBreadcrumbLevel = DEBUG, logsEnabled = false, - ) + ), ) it.addIntegration( SystemEventsBreadcrumbsIntegration( ApplicationProvider.getApplicationContext(), CustomHandler(Looper.getMainLooper()), - ) + ), ) refOptions = it } @@ -398,7 +399,7 @@ class SentryAndroidTest { } @Test - @Config(sdk = [26]) + @Config(sdk = [30]) fun `init starts session replay if app is in foreground`() { initSentryWithForegroundImportance(true) { _ -> Shadows.shadowOf(Looper.getMainLooper()).idle() @@ -407,7 +408,7 @@ class SentryAndroidTest { } @Test - @Config(sdk = [26]) + @Config(sdk = [30]) fun `init does not start session replay if the app is in background`() { initSentryWithForegroundImportance(false) { _ -> Shadows.shadowOf(Looper.getMainLooper()).idle() @@ -502,7 +503,7 @@ class SentryAndroidTest { } await .withAlias( - "Failed because of BeforeSend callback above, but we swallow BeforeSend exceptions, hence the timeout" + "Failed because of BeforeSend callback above, but we swallow BeforeSend exceptions, hence the timeout", ) .untilTrue(asserted) @@ -620,6 +621,18 @@ class SentryAndroidTest { assertTrue(optionsRef.eventProcessors.any { it is ApplicationExitInfoEventProcessor }) } + @Test + @Config(sdk = [30]) + fun `init does nothing in the NDK crash service process`() { + ShadowApplication.setProcessName("${context.packageName}.sentry_ndk_crash") + var configured = false + + fixture.initSut { configured = true } + + assertFalse(configured) + assertFalse(Sentry.isEnabled()) + } + 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-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt index bff6cdfad37..f5a6bfcd919 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt @@ -148,7 +148,7 @@ class SentryPerformanceProviderTest { .log( eq(SentryLevel.WARNING), eq( - "Unable to deserialize the SentryAppStartProfilingOptions. App start profiling will not start." + "Unable to deserialize the SentryAppStartProfilingOptions. App start profiling will not start.", ), ) } @@ -163,7 +163,7 @@ class SentryPerformanceProviderTest { .log( eq(SentryLevel.WARNING), eq( - "Unable to deserialize the SentryAppStartProfilingOptions. App start profiling will not start." + "Unable to deserialize the SentryAppStartProfilingOptions. App start profiling will not start.", ), ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryRootCaSslSocketFactoryTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryRootCaSslSocketFactoryTest.kt index e55eb5508fc..81734a37053 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryRootCaSslSocketFactoryTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryRootCaSslSocketFactoryTest.kt @@ -35,7 +35,7 @@ class SentryRootCaSslSocketFactoryTest { assertThat(fingerprints) .containsExactly( // ISRG Root X1 - ISRG_ROOT_X1_SHA256 + ISRG_ROOT_X1_SHA256, ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryScreenshotOptionsTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryScreenshotOptionsTest.kt index ed7562d5323..cf6da8d0957 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryScreenshotOptionsTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryScreenshotOptionsTest.kt @@ -47,10 +47,10 @@ class SentryScreenshotOptionsTest { assertTrue(options.maskViewClasses.contains(SentryMaskingOptions.WEB_VIEW_CLASS_NAME)) assertTrue(options.maskViewClasses.contains(SentryMaskingOptions.VIDEO_VIEW_CLASS_NAME)) assertTrue( - options.maskViewClasses.contains(SentryMaskingOptions.CAMERAX_PREVIEW_VIEW_CLASS_NAME) + options.maskViewClasses.contains(SentryMaskingOptions.CAMERAX_PREVIEW_VIEW_CLASS_NAME), ) assertTrue( - options.maskViewClasses.contains(SentryMaskingOptions.ANDROIDX_MEDIA_VIEW_CLASS_NAME) + options.maskViewClasses.contains(SentryMaskingOptions.ANDROIDX_MEDIA_VIEW_CLASS_NAME), ) assertTrue(options.maskViewClasses.contains(SentryMaskingOptions.EXOPLAYER_CLASS_NAME)) assertTrue(options.maskViewClasses.contains(SentryMaskingOptions.EXOPLAYER_STYLED_CLASS_NAME)) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryUserFeedbackFormTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryUserFeedbackFormTest.kt index 22a35016e77..f6dd2d6b017 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SentryUserFeedbackFormTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryUserFeedbackFormTest.kt @@ -365,7 +365,7 @@ class SentryUserFeedbackFormTest { eq(SentryLevel.WARNING), eq( "Feedback screenshot button won't be shown. It requires the androidx.activity " + - "dependency and the feedback form being shown from a ComponentActivity." + "dependency and the feedback form being shown from a ComponentActivity.", ), ) } @@ -507,7 +507,7 @@ class SentryUserFeedbackFormTest { eq(SentryLevel.WARNING), eq( "Unable to determine the size of the selected screenshot, the attachment size limit " + - "is applied when the feedback is captured." + "is applied when the feedback is captured.", ), any(), ) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SentryWebViewTracingTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SentryWebViewTracingTest.kt new file mode 100644 index 00000000000..96f8e060f00 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SentryWebViewTracingTest.kt @@ -0,0 +1,450 @@ +package io.sentry.android.core + +import android.os.Looper +import android.webkit.WebView +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.webkit.ScriptHandler +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature +import com.google.common.truth.Truth.assertThat +import io.sentry.IScopes +import io.sentry.OptionsContainer +import io.sentry.Sentry +import io.sentry.SentryIntegrationPackageStorage +import io.sentry.TransactionOptions +import io.sentry.util.LoadClass +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertFailsWith +import org.junit.runner.RunWith +import org.mockito.Mockito.mockStatic +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import org.robolectric.Shadows.shadowOf + +@RunWith(AndroidJUnit4::class) +class SentryWebViewTracingTest { + + private class FakeInstaller( + var supported: Boolean = true, + var installFailure: IllegalArgumentException? = null, + var linkageError: LinkageError? = null, + var removeFailure: Throwable? = null, + var onInstall: (() -> Unit)? = null, + ) : WebViewScriptInstaller { + var removeCount = 0 + val installed = mutableListOf>>() + + override fun isDocumentStartScriptSupported(): Boolean = supported + + override fun removeInstalledScript(webView: WebView) { + linkageError?.let { throw it } + removeFailure?.let { throw it } + removeCount++ + } + + override fun installScript( + webView: WebView, + script: String, + allowedOriginRules: Set, + ): Boolean { + installFailure?.let { throw it } + onInstall?.invoke() + installed.add(script to allowedOriginRules) + return true + } + } + + private lateinit var webView: WebView + private val installer = FakeInstaller() + + @BeforeTest + fun setUp() { + SentryIntegrationPackageStorage.getInstance().clearStorage() + webView = WebView(ApplicationProvider.getApplicationContext()) + } + + @AfterTest + fun tearDown() { + Sentry.close() + } + + private fun initSentry(): IScopes { + Sentry.init { + it.dsn = "https://key@sentry.io/123" + it.release = "app@1.0" + it.environment = "prod" + it.tracesSampleRate = 1.0 + } + return Sentry.getCurrentScopes() + } + + private fun add( + allowedHosts: List = listOf("example.com"), + scopes: IScopes = Sentry.getCurrentScopes(), + ): Boolean = SentryWebViewTracing.install(webView, allowedHosts, scopes, installer) + + @Test + fun `installs the current trace for the allowed hosts`() { + val scopes = initSentry() + + assertThat(add()).isTrue() + + val (script, rules) = installer.installed.single() + assertThat(script).contains(scopes.traceparent!!.value) + assertThat(script).contains("sentry-release=app%401.0") + assertThat(rules).containsExactly("https://example.com", "https://*.example.com") + } + + @Test + fun `does not propagate the root span name`() { + initSentry() + val transaction = + Sentry.startTransaction( + "Checkout user@example.com", + "ui.load", + TransactionOptions().apply { isBindToScope = true }, + ) + + assertThat(add()).isTrue() + + val (script, _) = installer.installed.single() + assertThat(script).contains(transaction.toSentryTrace().value) + assertThat(script).contains("sentry-sampled=true") + assertThat(script).doesNotContain("sentry-transaction") + transaction.finish() + } + + @Test + fun `removes the previous script before installing again`() { + initSentry() + + assertThat(add()).isTrue() + assertThat(add()).isTrue() + + assertThat(installer.removeCount).isEqualTo(2) + assertThat(installer.installed).hasSize(2) + } + + @Test + fun `returns false and leaves no script when allowedHosts has no valid entry`() { + initSentry() + + assertThat(add(listOf(" ", ""))).isFalse() + + assertThat(installer.removeCount).isEqualTo(1) + assertThat(installer.installed).isEmpty() + } + + @Test + fun `returns false and leaves no script when document-start scripts are unsupported`() { + initSentry() + installer.supported = false + + assertThat(add()).isFalse() + + assertThat(installer.removeCount).isEqualTo(1) + assertThat(installer.installed).isEmpty() + } + + @Test + fun `returns false and leaves no script when the SDK is not initialized`() { + assertThat(add()).isFalse() + + assertThat(installer.removeCount).isEqualTo(1) + assertThat(installer.installed).isEmpty() + } + + @Test + fun `a re-add after Sentry close removes the previous script`() { + initSentry() + assertThat(add()).isTrue() + Sentry.close() + + assertThat(add()).isFalse() + + assertThat(installer.removeCount).isEqualTo(2) + assertThat(installer.installed).hasSize(1) + } + + @Test + fun `treats a subdomain wildcard entry like the bare host`() { + initSentry() + + assertThat(add(listOf("*.example.com"))).isTrue() + + val (_, rules) = installer.installed.single() + assertThat(rules).containsExactly("https://example.com", "https://*.example.com") + } + + @Test + fun `off the WebView's thread returns false and removes the previous script on that thread`() { + initSentry() + assertThat(add()).isTrue() + var result: Boolean? = null + + val thread = Thread { result = add() } + thread.start() + thread.join() + + assertThat(result).isFalse() + assertThat(installer.removeCount).isEqualTo(1) + shadowOf(Looper.getMainLooper()).idle() + assertThat(installer.removeCount).isEqualTo(2) + assertThat(installer.installed).hasSize(1) + } + + @Test + fun `the removal posted by an off-thread call does not crash when it fails`() { + initSentry() + assertThat(add()).isTrue() + val thread = Thread { add() } + thread.start() + thread.join() + + // For example, the WebView was destroyed before the removal ran. + installer.removeFailure = IllegalStateException("WebView destroyed") + shadowOf(Looper.getMainLooper()).idle() + + assertThat(installer.removeCount).isEqualTo(1) + } + + @Test + fun `the removal posted by an off-thread call rethrows fatal errors`() { + initSentry() + assertThat(add()).isTrue() + val thread = Thread { add() } + thread.start() + thread.join() + + installer.removeFailure = OutOfMemoryError() + + assertFailsWith { shadowOf(Looper.getMainLooper()).idle() } + } + + @Test + fun `the removal posted by an off-thread call does not remove a newer script`() { + initSentry() + val thread = Thread { add() } + thread.start() + thread.join() + + assertThat(add()).isTrue() + shadowOf(Looper.getMainLooper()).idle() + + assertThat(installer.removeCount).isEqualTo(1) + assertThat(installer.installed).hasSize(1) + } + + @Test + fun `an off-thread call made while a script is installed does not remove it later`() { + initSentry() + installer.onInstall = { + // Runs on the WebView's thread while it installs the script. + val thread = Thread { add() } + thread.start() + thread.join() + } + + assertThat(add()).isTrue() + shadowOf(Looper.getMainLooper()).idle() + + assertThat(installer.removeCount).isEqualTo(1) + assertThat(installer.installed).hasSize(1) + } + + @Test + fun `a call on another WebView does not cancel the removal posted for this one`() { + initSentry() + assertThat(add()).isTrue() + val otherWebView = WebView(ApplicationProvider.getApplicationContext()) + val thread = Thread { add() } + thread.start() + thread.join() + + assertThat( + SentryWebViewTracing.install( + otherWebView, + listOf("example.com"), + Sentry.getCurrentScopes(), + installer, + ), + ) + .isTrue() + shadowOf(Looper.getMainLooper()).idle() + + // One removal per on-thread call, plus the one posted for the first WebView. + assertThat(installer.removeCount).isEqualTo(3) + } + + @Test + fun `returns false when androidx webkit is too old`() { + initSentry() + installer.linkageError = NoSuchMethodError("addDocumentStartJavaScript") + + assertThat(add()).isFalse() + + assertThat(installer.installed).isEmpty() + } + + @Test + fun `passes a non-default port through to the origin rules`() { + initSentry() + + assertThat(add(listOf("example.com:8443"))).isTrue() + + val (_, rules) = installer.installed.single() + assertThat(rules).containsExactly("https://example.com:8443", "https://*.example.com:8443") + } + + @Test + fun `returns false when the origin rules are rejected`() { + initSentry() + installer.installFailure = IllegalArgumentException("bad rule") + + assertThat(add(listOf("*"))).isFalse() + } + + @Test + fun `returns false when androidx webkit is not available and still records adoption`() { + val scopes = initSentry() + val loadClass = mock() + whenever( + loadClass.isClassAvailable( + eq(SentryWebViewTracing.SCRIPT_HANDLER_CLASS_NAME), + any(), + ), + ) + .thenReturn(false) + + assertThat( + SentryWebViewTracing.addTracePropagation( + webView, + listOf("example.com"), + scopes, + loadClass, + ), + ) + .isFalse() + // The adoption marker is registered on use, even when nothing can be installed. + assertThat(SentryIntegrationPackageStorage.getInstance().integrations) + .contains("WebViewTracePropagation") + } + + @Test + fun `androidx installer stores the script handler and removes it on the next call`() { + val handler = mock() + mockStatic(WebViewCompat::class.java).use { webViewCompat -> + mockStatic(WebViewFeature::class.java).use { webViewFeature -> + webViewFeature + .`when` { + WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT) + } + .thenReturn(true) + webViewCompat + .`when` { + WebViewCompat.addDocumentStartJavaScript(eq(webView), any(), any()) + } + .thenReturn(handler) + val androidxInstaller = AndroidxWebViewScriptInstaller() + + assertThat(androidxInstaller.isDocumentStartScriptSupported).isTrue() + androidxInstaller.removeInstalledScript(webView) + assertThat(androidxInstaller.installScript(webView, "script", setOf("https://example.com"))) + .isTrue() + assertThat(webView.getTag(R.id.sentry_webview_trace_propagation)).isSameInstanceAs(handler) + + androidxInstaller.removeInstalledScript(webView) + + verify(handler, times(1)).remove() + assertThat(webView.getTag(R.id.sentry_webview_trace_propagation)).isNull() + } + } + } + + @Test + fun `without hosts uses the allowed hosts from the options`() { + Sentry.init(OptionsContainer.create(SentryAndroidOptions::class.java)) { + it.dsn = "https://key@sentry.io/123" + it.webViewTracing.allowedHosts = listOf("example.com") + } + val origins = argumentCaptor>() + mockStatic(WebViewCompat::class.java).use { webViewCompat -> + mockStatic(WebViewFeature::class.java).use { webViewFeature -> + webViewFeature + .`when` { + WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT) + } + .thenReturn(true) + webViewCompat + .`when` { + WebViewCompat.addDocumentStartJavaScript(eq(webView), any(), origins.capture()) + } + .thenReturn(mock()) + + assertThat(SentryWebViewTracing.addTracePropagation(webView)).isTrue() + } + } + + assertThat(origins.firstValue).containsExactly("https://example.com", "https://*.example.com") + } + + @Test + fun `without hosts connects no page when the options have none`() { + Sentry.init(OptionsContainer.create(SentryAndroidOptions::class.java)) { + it.dsn = "https://key@sentry.io/123" + it.setTracePropagationTargets(listOf("example.com")) + } + + assertThat(SentryWebViewTracing.addTracePropagation(webView)).isFalse() + assertThat(webView.getTag(R.id.sentry_webview_trace_propagation)).isNull() + } + + @Test + fun `androidx installer clears the handler even when its removal throws`() { + val handler = mock() + whenever(handler.remove()).thenThrow(IllegalStateException("WebView destroyed")) + webView.setTag(R.id.sentry_webview_trace_propagation, handler) + mockStatic(WebViewFeature::class.java).use { webViewFeature -> + webViewFeature + .`when` { WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT) } + .thenReturn(true) + val androidxInstaller = AndroidxWebViewScriptInstaller() + + assertFailsWith { androidxInstaller.removeInstalledScript(webView) } + assertThat(webView.getTag(R.id.sentry_webview_trace_propagation)).isNull() + + // The next call has nothing left to remove. + androidxInstaller.removeInstalledScript(webView) + verify(handler, times(1)).remove() + } + } + + @Test + fun `androidx installer installs nothing when document-start scripts are unsupported`() { + mockStatic(WebViewCompat::class.java).use { webViewCompat -> + mockStatic(WebViewFeature::class.java).use { webViewFeature -> + webViewFeature + .`when` { + WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT) + } + .thenReturn(false) + + val installed = + AndroidxWebViewScriptInstaller() + .installScript(webView, "script", setOf("https://example.com")) + + assertThat(installed).isFalse() + webViewCompat.verifyNoInteractions() + assertThat(webView.getTag(R.id.sentry_webview_trace_propagation)).isNull() + } + } + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SessionTrackingIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SessionTrackingIntegrationTest.kt index bbb8783d5fd..d3052937b67 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SessionTrackingIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SessionTrackingIntegrationTest.kt @@ -35,7 +35,7 @@ import org.junit.runner.RunWith import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) -@Config(sdk = [31]) +@Config(sdk = [33]) class SessionTrackingIntegrationTest { private lateinit var context: Context @@ -118,7 +118,7 @@ class SessionTrackingIntegrationTest { private fun setupLifecycle(): LifecycleRegistry { val lifecycle = LifecycleRegistry(ProcessLifecycleOwner.get()) - lifecycle.addObserver(AppState.getInstance().lifecycleObserver) + lifecycle.addObserver(AppState.getInstance().lifecycleObserver!!) return lifecycle } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SpanFrameMetricsCollectorTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SpanFrameMetricsCollectorTest.kt index e8b9afa1896..ecc5d58b765 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SpanFrameMetricsCollectorTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SpanFrameMetricsCollectorTest.kt @@ -60,7 +60,7 @@ class SpanFrameMetricsCollectorTest { SentryNanotimeDate(System.currentTimeMillis(), endTimeStampNanos) } else { null - } + }, ) return span } @@ -80,7 +80,7 @@ class SpanFrameMetricsCollectorTest { SentryNanotimeDate(System.currentTimeMillis(), endTimeStampNanos) } else { null - } + }, ) return span } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegrationTest.kt index 2505b6f7f7d..88ddba69a09 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/SystemEventsBreadcrumbsIntegrationTest.kt @@ -387,9 +387,9 @@ class SystemEventsBreadcrumbsIntegrationTest { sut.register(fixture.scopes, fixture.options) assertTrue( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) } @@ -401,9 +401,9 @@ class SystemEventsBreadcrumbsIntegrationTest { sut.register(fixture.scopes, fixture.options) assertFalse( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) } @@ -414,17 +414,17 @@ class SystemEventsBreadcrumbsIntegrationTest { sut.register(fixture.scopes, fixture.options) assertTrue( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) sut.close() assertFalse( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) } @@ -436,9 +436,9 @@ class SystemEventsBreadcrumbsIntegrationTest { sut.register(fixture.scopes, fixture.options) Thread { - sut.close() - latch.countDown() - } + sut.close() + latch.countDown() + } .start() latch.await() @@ -447,9 +447,9 @@ class SystemEventsBreadcrumbsIntegrationTest { shadowOf(Looper.getMainLooper()).idle() assertFalse( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) } @@ -520,9 +520,9 @@ class SystemEventsBreadcrumbsIntegrationTest { assertNotNull(sut.receiver) Thread { - sut.close() - latch.countDown() - } + sut.close() + latch.countDown() + } .start() latch.await() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/TombstoneIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/TombstoneIntegrationTest.kt index 39a63148a17..83514adc260 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/TombstoneIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/TombstoneIntegrationTest.kt @@ -26,7 +26,7 @@ import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowActivityManager.ApplicationExitInfoBuilder @RunWith(AndroidJUnit4::class) -@Config(sdk = [31]) +@Config(sdk = [33]) class TombstoneIntegrationTest : ApplicationExitIntegrationTestBase() { override val config = @@ -58,8 +58,8 @@ class TombstoneIntegrationTest : ApplicationExitIntegrationTestBase(), - ) + ), ) .thenReturn(isLifecycleAvailable) whenever(scopes.options).thenReturn(options) @@ -110,7 +110,7 @@ class UserInteractionIntegrationTest { sut.onActivityResumed(fixture.activity) assertIs(fixture.activity.window.callback) assertIs( - (fixture.activity.window.callback as SentryWindowCallback).delegate + (fixture.activity.window.callback as SentryWindowCallback).delegate, ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/WebViewTracePropagationScriptTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/WebViewTracePropagationScriptTest.kt new file mode 100644 index 00000000000..ce7d3f02bc4 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/WebViewTracePropagationScriptTest.kt @@ -0,0 +1,368 @@ +package io.sentry.android.core + +import com.google.common.truth.Truth.assertThat +import kotlin.test.Test +import org.mozilla.javascript.Context +import org.mozilla.javascript.ScriptableObject + +class WebViewTracePropagationScriptTest { + + private data class Meta(val name: String, val content: String) + + private data class Result(val metas: List, val pwned: Boolean) + + /** + * Runs the injection script against a minimal fake DOM, like the React Native SDK tests do, and + * returns the meta tags present afterwards. A breakout payload would set `window.__pwned`. + */ + private fun runInjection( + script: String, + hostname: String, + existing: List = emptyList(), + mainFrame: Boolean = true, + ): Result { + val cx = Context.enter() + try { + cx.languageVersion = Context.VERSION_ES6 + val scope = cx.initStandardObjects() + ScriptableObject.putProperty(scope, "HOST", hostname) + ScriptableObject.putProperty(scope, "MAIN_FRAME", mainFrame) + cx.evaluateString( + scope, + """ + var metas = []; + var head = { appendChild: function(el) { metas.push({ name: el.name, content: el.content }); } }; + var document = { + head: head, + documentElement: head, + createElement: function() { + return { name: '', content: '', setAttribute: function(k, v) { this[k] = v; } }; + }, + querySelector: function(selector) { + var match = /meta\[name="([^"]+)"\]/.exec(selector); + if (!match) return null; + for (var i = 0; i < metas.length; i++) { + if (metas[i].name === match[1]) return metas[i]; + } + return null; + } + }; + var window = { location: { hostname: HOST } }; + window.top = MAIN_FRAME ? window : {}; + """ + .trimIndent(), + "harness", + 1, + null, + ) + for (meta in existing) { + cx.evaluateString( + scope, + "metas.push({ name: ${WebViewTracePropagationScript.toJsStringLiteral(meta.name)}, " + + "content: ${WebViewTracePropagationScript.toJsStringLiteral(meta.content)} });", + "existing", + 1, + null, + ) + } + + cx.evaluateString(scope, script, "injection", 1, null) + + val count = Context.toNumber(cx.evaluateString(scope, "metas.length", "count", 1, null)) + val metas = + (0 until count.toInt()).map { i -> + Meta( + Context.toString(cx.evaluateString(scope, "metas[$i].name", "name", 1, null)), + Context.toString(cx.evaluateString(scope, "metas[$i].content", "content", 1, null)), + ) + } + val pwned = + Context.toBoolean( + cx.evaluateString( + scope, + "window.__pwned === 1 || typeof __pwned !== 'undefined'", + "pwned", + 1, + null, + ), + ) + return Result(metas, pwned) + } finally { + Context.exit() + } + } + + private fun script( + allowedHosts: List = listOf("example.com"), + sentryTrace: String = SENTRY_TRACE, + baggage: String? = BAGGAGE, + ): String = + WebViewTracePropagationScript.build( + WebViewTracePropagationScript.normalizeHosts(allowedHosts), + sentryTrace, + baggage, + ) + + @Test + fun `injects sentry-trace and baggage meta tags on an allowed host`() { + val result = runInjection(script(), "example.com") + + assertThat(result.metas) + .containsExactly(Meta("sentry-trace", SENTRY_TRACE), Meta("baggage", BAGGAGE)) + .inOrder() + } + + @Test + fun `injects on a subdomain of an allowed host`() { + assertThat(runInjection(script(), "app.example.com").metas).hasSize(2) + } + + @Test + fun `matches allowed hosts case-insensitively`() { + assertThat(runInjection(script(listOf("Example.COM")), "app.example.com").metas).hasSize(2) + } + + @Test + fun `does not inject on a host that is not allowed`() { + assertThat(runInjection(script(), "evil.com").metas).isEmpty() + } + + @Test + fun `does not inject on a host that merely ends with an allowed host`() { + assertThat(runInjection(script(), "notexample.com").metas).isEmpty() + } + + @Test + fun `does not inject into iframes`() { + assertThat(runInjection(script(), "example.com", mainFrame = false).metas).isEmpty() + } + + @Test + fun `does not inject again when the page already has a sentry-trace meta tag`() { + val existing = listOf(Meta("sentry-trace", "already-there")) + + val result = runInjection(script(), "example.com", existing) + + assertThat(result.metas).containsExactly(Meta("sentry-trace", "already-there")) + } + + @Test + fun `injects only sentry-trace when there is no baggage`() { + val result = runInjection(script(baggage = null), "example.com") + + assertThat(result.metas).containsExactly(Meta("sentry-trace", SENTRY_TRACE)) + } + + @Test + fun `normalizes allowedHosts entries`() { + for (entry in + listOf( + " example.com ", + "https://example.com", + "example.com:8080", + "example.com/some/path", + "example.com.", + "https://Example.com:443/x?y#z", + )) { + assertThat(WebViewTracePropagationScript.normalizeHost(entry)).isEqualTo("example.com") + assertThat(runInjection(script(listOf(entry)), "example.com").metas).hasSize(2) + } + } + + @Test + fun `normalizes a subdomain wildcard entry to the bare host`() { + for (entry in listOf("*.example.com", "https://*.Example.com/x", "*.*.example.com")) { + assertThat(WebViewTracePropagationScript.normalizeHost(entry)).isEqualTo("example.com") + } + assertThat(runInjection(script(listOf("*.example.com")), "app.example.com").metas).hasSize(2) + assertThat(runInjection(script(listOf("*.example.com")), "example.com").metas).hasSize(2) + } + + @Test + fun `converts internationalized allowedHosts entries to punycode`() { + assertThat(WebViewTracePropagationScript.normalizeHost("münchen.de")) + .isEqualTo("xn--mnchen-3ya.de") + assertThat(WebViewTracePropagationScript.normalizeHost("https://App.MÜNCHEN.de:8443/x")) + .isEqualTo("app.xn--mnchen-3ya.de") + // location.hostname is the punycode form, so the page matches the entry and its subdomains. + assertThat(runInjection(script(listOf("münchen.de")), "xn--mnchen-3ya.de").metas).hasSize(2) + assertThat(runInjection(script(listOf("münchen.de")), "app.xn--mnchen-3ya.de").metas).hasSize(2) + assertThat(WebViewTracePropagationScript.originRules(listOf("münchen.de:8443"))) + .containsExactly("https://xn--mnchen-3ya.de:8443", "https://*.xn--mnchen-3ya.de:8443") + } + + @Test + fun `drops internationalized allowedHosts entries that cannot be converted`() { + // A label longer than 63 characters is not a valid hostname. + val tooLong = "ü".repeat(64) + ".de" + + assertThat(WebViewTracePropagationScript.normalizeHosts(listOf(tooLong, "example.com"))) + .containsExactly("example.com") + assertThat(WebViewTracePropagationScript.originRules(listOf(tooLong))).isEmpty() + } + + @Test + fun `normalizes IPv6 allowedHosts entries to the bracketed hostname`() { + for ((entry, hostname) in + listOf( + "::1" to "[::1]", + "[::1]" to "[::1]", + "[::1]:8080" to "[::1]", + "2001:db8::1" to "[2001:db8::1]", + "[2001:DB8::1]" to "[2001:db8::1]", + )) { + assertThat(WebViewTracePropagationScript.normalizeHost(entry)).isEqualTo(hostname) + assertThat(runInjection(script(listOf(entry)), hostname).metas).hasSize(2) + } + } + + @Test + fun `normalizeHosts drops blank entries and duplicates`() { + val hosts = + WebViewTracePropagationScript.normalizeHosts( + listOf(" ", "", "example.com", "https://EXAMPLE.com/", "other.com"), + ) + + assertThat(hosts).containsExactly("example.com", "other.com").inOrder() + } + + @Test + fun `originRules allow each host and its subdomains over https`() { + val rules = WebViewTracePropagationScript.originRules(listOf("example.com", "other.com")) + + assertThat(rules) + .containsExactly( + "https://example.com", + "https://*.example.com", + "https://other.com", + "https://*.other.com", + ) + } + + @Test + fun `originRules do not add a subdomain wildcard to IP literals`() { + val rules = WebViewTracePropagationScript.originRules(listOf("[::1]", "10.0.2.2")) + + assertThat(rules).containsExactly("https://[::1]", "https://10.0.2.2") + } + + @Test + fun `originRules keep a non-default port`() { + val rules = + WebViewTracePropagationScript.originRules( + listOf("example.com:8443", "https://other.com:443/x", "[::1]:8080", "10.0.2.2:3000"), + ) + + assertThat(rules) + .containsExactly( + "https://example.com:8443", + "https://*.example.com:8443", + "https://other.com", + "https://*.other.com", + "https://[::1]:8080", + "https://10.0.2.2:3000", + ) + } + + @Test + fun `originRules skip blank entries and treat unbracketed IPv6 as having no port`() { + val rules = WebViewTracePropagationScript.originRules(listOf(" ", "2001:db8::1")) + + assertThat(rules).containsExactly("https://[2001:db8::1]") + } + + @Test + fun `stripTransactionFromBaggage removes sentry-transaction and keeps every other entry`() { + val baggage = + "sentry-trace_id=d4cda95b652f4a1592b449d5929fda1b,sentry-environment=prod," + + "sentry-transaction=GET%20%2Fusers%2F123,sentry-sample_rate=1.0,othervendor=keepme" + + assertThat(WebViewTracePropagationScript.stripTransactionFromBaggage(baggage)) + .isEqualTo( + "sentry-trace_id=d4cda95b652f4a1592b449d5929fda1b,sentry-environment=prod," + + "sentry-sample_rate=1.0,othervendor=keepme", + ) + } + + @Test + fun `stripTransactionFromBaggage returns null when only sentry-transaction is left`() { + assertThat( + WebViewTracePropagationScript.stripTransactionFromBaggage( + "sentry-transaction=GET%20%2Fusers%2F123", + ), + ) + .isNull() + assertThat(WebViewTracePropagationScript.stripTransactionFromBaggage(null)).isNull() + } + + @Test + fun `neutralizes breakout payloads in the sentry-trace value`() { + for (payload in BREAKOUT_PAYLOADS) { + val result = runInjection(script(sentryTrace = payload), "example.com") + + assertThat(result.pwned).isFalse() + assertThat(result.metas).contains(Meta("sentry-trace", payload)) + } + } + + @Test + fun `neutralizes breakout payloads in the baggage value`() { + for (payload in BREAKOUT_PAYLOADS) { + val result = runInjection(script(baggage = payload), "example.com") + + assertThat(result.pwned).isFalse() + assertThat(result.metas).contains(Meta("baggage", payload)) + } + } + + @Test + fun `neutralizes breakout payloads in allowedHosts entries`() { + for (payload in BREAKOUT_PAYLOADS) { + val script = + WebViewTracePropagationScript.build(listOf(payload, "example.com"), SENTRY_TRACE, BAGGAGE) + + val result = runInjection(script, "example.com") + + assertThat(result.pwned).isFalse() + assertThat(result.metas).hasSize(2) + } + } + + @Test + fun `preserves random sentry-trace values as inert content`() { + val chars = "\"'`\\\${}();/<>\n\r\t

abc0= ," + val random = java.util.Random(123456789) + repeat(200) { + val payload = buildString { + repeat(1 + random.nextInt(40)) { append(chars[random.nextInt(chars.length)]) } + } + + val result = runInjection(script(sentryTrace = payload), "example.com") + + assertThat(result.pwned).isFalse() + assertThat(result.metas).contains(Meta("sentry-trace", payload)) + } + } + + companion object { + private const val SENTRY_TRACE = "d4cda95b652f4a1592b449d5929fda1b-6e0c63257de34c92-1" + private const val BAGGAGE = + "sentry-trace_id=d4cda95b652f4a1592b449d5929fda1b,sentry-environment=prod" + + private val BREAKOUT_PAYLOADS = + listOf( + "\");window.__pwned=1;(\"", + "');window.__pwned=1;('", + "`;window.__pwned=1;`", + "\${window.__pwned=1}", + "", + "\\\";window.__pwned=1;//", + "\"}]);window.__pwned=1;//", + "\nwindow.__pwned=1;\n", + "\rwindow.__pwned=1;\r", + "
window.__pwned=1;", + "
window.__pwned=1;", + "abc\u0000;window.__pwned=1;", + ) + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt index 76cdac4d1e6..6c3d08c76bc 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrProfilingIntegrationTest.kt @@ -107,7 +107,7 @@ class AnrProfilingIntegrationTest { val thread = integration.getProperty("thread") assertNotNull(thread) - assertTrue(AppState.getInstance().lifecycleObserver.listeners.isNotEmpty()) + assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isNotEmpty()) integration.close() thread.join(2000) @@ -115,7 +115,7 @@ class AnrProfilingIntegrationTest { assertTrue(!thread.isAlive) val enabled = integration.getProperty("enabled") assertTrue(!enabled.get()) - assertTrue(AppState.getInstance().lifecycleObserver.listeners.isEmpty()) + assertTrue(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) } @Test @@ -354,7 +354,7 @@ class AnrProfilingIntegrationTest { val integration = AnrProfilingIntegration() integration.register(mockScopes, androidOptions) - assertFalse(AppState.getInstance().lifecycleObserver.listeners.isEmpty()) + assertFalse(AppState.getInstance().lifecycleObserver!!.listeners.isEmpty()) assertTrue(SentryIntegrationPackageStorage.getInstance().integrations.contains("AnrProfiling")) integration.close() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrStackTraceTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrStackTraceTest.kt index e53ad507bc1..f26cab58f78 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrStackTraceTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/anr/AnrStackTraceTest.kt @@ -1,5 +1,6 @@ package io.sentry.android.core.anr +import com.google.common.truth.Truth.assertThat import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.DataInputStream @@ -124,4 +125,91 @@ class AnrStackTraceTest { assertNull(deserialized) } + + @Test + fun `v2 round trip keeps the thread state`() { + val stack = arrayOf(StackTraceElement("com.example.MyClass", "method1", "MyClass.java", 42)) + val original = AnrStackTrace(1234567890L, stack, Thread.State.BLOCKED) + + val deserialized = roundTrip(original) + + assertThat(deserialized).isNotNull() + assertThat(deserialized!!.state).isEqualTo(Thread.State.BLOCKED) + assertThat(deserialized.timestampMs).isEqualTo(1234567890L) + assertThat(deserialized.stack).isEqualTo(stack) + } + + @Test + fun `v2 round trip keeps a null thread state`() { + val original = AnrStackTrace(1234567890L, emptyArray(), null) + + val deserialized = roundTrip(original) + + assertThat(deserialized).isNotNull() + assertThat(deserialized!!.state).isNull() + } + + @Test + fun `v1 bytes are still read with a null state`() { + val bytes = ByteArrayOutputStream() + val dos = DataOutputStream(bytes) + dos.writeShort(1) + dos.writeLong(1234567890L) + dos.writeInt(1) + dos.writeUTF("com.example.MyClass") + dos.writeUTF("method1") + dos.writeBoolean(false) + dos.writeUTF("MyClass.java") + dos.writeInt(42) + dos.flush() + + val deserialized = + AnrStackTrace.deserialize(DataInputStream(ByteArrayInputStream(bytes.toByteArray()))) + + assertThat(deserialized).isNotNull() + assertThat(deserialized!!.state).isNull() + assertThat(deserialized.timestampMs).isEqualTo(1234567890L) + assertThat(deserialized.stack) + .isEqualTo(arrayOf(StackTraceElement("com.example.MyClass", "method1", "MyClass.java", 42))) + } + + @Test + fun `unknown thread state name reads as null`() { + val bytes = ByteArrayOutputStream() + val dos = DataOutputStream(bytes) + dos.writeShort(2) + dos.writeLong(1234567890L) + dos.writeBoolean(false) + dos.writeUTF("NOT_A_STATE") + dos.writeInt(0) + dos.flush() + + val deserialized = + AnrStackTrace.deserialize(DataInputStream(ByteArrayInputStream(bytes.toByteArray()))) + + assertThat(deserialized).isNotNull() + assertThat(deserialized!!.state).isNull() + } + + @Test + fun `version 3 returns null`() { + val bytes = ByteArrayOutputStream() + val dos = DataOutputStream(bytes) + dos.writeShort(3) + dos.writeLong(1234567890L) + dos.flush() + + val deserialized = + AnrStackTrace.deserialize(DataInputStream(ByteArrayInputStream(bytes.toByteArray()))) + + assertThat(deserialized).isNull() + } + + private fun roundTrip(original: AnrStackTrace): AnrStackTrace? { + val bytes = ByteArrayOutputStream() + val dos = DataOutputStream(bytes) + original.serialize(dos) + dos.flush() + return AnrStackTrace.deserialize(DataInputStream(ByteArrayInputStream(bytes.toByteArray()))) + } } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/cache/AndroidEnvelopeCacheTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/cache/AndroidEnvelopeCacheTest.kt index 4c11d549f88..4ca73593b33 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/cache/AndroidEnvelopeCacheTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/cache/AndroidEnvelopeCacheTest.kt @@ -165,7 +165,7 @@ class AndroidEnvelopeCacheTest { val hints = HintUtils.createWithTypeCheckHint( - AnrV2Hint(0, NoOpLogger.getInstance(), 12345678L, false, false) + AnrV2Hint(0, NoOpLogger.getInstance(), 12345678L, false, false), ) cache.storeEnvelope(fixture.envelope, hints) @@ -178,7 +178,7 @@ class AndroidEnvelopeCacheTest { val hints = HintUtils.createWithTypeCheckHint( - AnrV2Hint(0, NoOpLogger.getInstance(), 12345678L, false, false) + AnrV2Hint(0, NoOpLogger.getInstance(), 12345678L, false, false), ) cache.storeEnvelope(fixture.envelope, hints) @@ -224,7 +224,7 @@ class AndroidEnvelopeCacheTest { val hints = HintUtils.createWithTypeCheckHint( - MemoryLimiterHint(0, NoOpLogger.getInstance(), 23456789L, false) + MemoryLimiterHint(0, NoOpLogger.getInstance(), 23456789L, false), ) cache.storeEnvelope(fixture.envelope, hints) @@ -244,7 +244,7 @@ class AndroidEnvelopeCacheTest { cache.storeEnvelope( envelope, HintUtils.createWithTypeCheckHint( - MemoryLimiterHint(0, NoOpLogger.getInstance(), exitTimestamp, true) + MemoryLimiterHint(0, NoOpLogger.getInstance(), exitTimestamp, true), ), ) @@ -267,7 +267,7 @@ class AndroidEnvelopeCacheTest { cache.storeEnvelope( envelope, HintUtils.createWithTypeCheckHint( - MemoryLimiterHint(0, NoOpLogger.getInstance(), sessionStart.time - 1_000, true) + MemoryLimiterHint(0, NoOpLogger.getInstance(), sessionStart.time - 1_000, true), ), ) @@ -284,13 +284,13 @@ class AndroidEnvelopeCacheTest { cache.storeEnvelope( fixture.envelope, HintUtils.createWithTypeCheckHint( - AnrV2Hint(0, NoOpLogger.getInstance(), 12345678L, false, false) + AnrV2Hint(0, NoOpLogger.getInstance(), 12345678L, false, false), ), ) cache.storeEnvelope( fixture.envelope, HintUtils.createWithTypeCheckHint( - MemoryLimiterHint(0, NoOpLogger.getInstance(), 23456789L, false) + MemoryLimiterHint(0, NoOpLogger.getInstance(), 23456789L, false), ), ) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/debugmeta/AssetsDebugMetaLoaderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/debugmeta/AssetsDebugMetaLoaderTest.kt index 76f13b63822..0424121f500 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/debugmeta/AssetsDebugMetaLoaderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/debugmeta/AssetsDebugMetaLoaderTest.kt @@ -51,7 +51,7 @@ class AssetsDebugMetaLoaderTest { io.sentry.bundle-ids=88ba82db-cd26-4c09-8b31-21461d286b68 io.sentry.build-tool=maven """ - .trimIndent() + .trimIndent(), ) val options = SentryOptions() @@ -74,7 +74,7 @@ class AssetsDebugMetaLoaderTest { io.sentry.bundle-ids=88ba82db-cd26-4c09-8b31-21461d286b68,8d11a44a-facd-46c1-a49b-87d256227101 io.sentry.build-tool=maven """ - .trimIndent() + .trimIndent(), ) val options = SentryOptions() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/gestures/SentryGestureListenerTracingTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/gestures/SentryGestureListenerTracingTest.kt index e73bf891c8e..b856a4cc622 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/gestures/SentryGestureListenerTracingTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/gestures/SentryGestureListenerTracingTest.kt @@ -411,7 +411,7 @@ class SentryGestureListenerTracingTest { // Verify that a new propagation context was set and it's different from the initial one assertNotNull(scope.propagationContext) assertNotEquals(initialPropagationContext, scope.propagationContext) - } + }, ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/modules/AssetsModulesLoaderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/modules/AssetsModulesLoaderTest.kt index 34d03b175d7..6c6d260e9d9 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/modules/AssetsModulesLoaderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/modules/AssetsModulesLoaderTest.kt @@ -47,7 +47,7 @@ class AssetsModulesLoaderTest { com.squareup.okhttp3:okhttp:3.14.9 com.squareup.okio:okio:1.17.2 """ - .trimIndent() + .trimIndent(), ) assertEquals( @@ -65,7 +65,7 @@ class AssetsModulesLoaderTest { com.squareup.okhttp3:okhttp:3.14.9 com.squareup.okio:okio:1.17.2 """ - .trimIndent() + .trimIndent(), ) // first, call method to get modules cached @@ -95,7 +95,7 @@ class AssetsModulesLoaderTest { """ com.squareup.okhttp3;3.14.9 """ - .trimIndent() + .trimIndent(), ) assertTrue(sut.orLoadModules!!.isEmpty()) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/threaddump/ThreadDumpParserTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/threaddump/ThreadDumpParserTest.kt index e514ecbb88b..4c943550c94 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/threaddump/ThreadDumpParserTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/threaddump/ThreadDumpParserTest.kt @@ -233,9 +233,9 @@ class ThreadDumpParserTest { | sysTid=123 nice=-10 cgrp=top-app sched=0/0 handle=0x7deceb74f8 at MainActivity.run(MainActivity.java:177) """ - .trimIndent() - ) - ) + .trimIndent(), + ), + ), ) val parser = ThreadDumpParser(SentryOptions(), false) @@ -257,9 +257,9 @@ class ThreadDumpParserTest { | sysTid=123 nice=-10 cgrp=top-app sched=0/0 handle=0x7deceb74f8 at MainActivity.nativeRun(Native method) """ - .trimIndent() - ) - ) + .trimIndent(), + ), + ), ) val parser = ThreadDumpParser(SentryOptions(), false) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/tombstone/TombstoneParserTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/tombstone/TombstoneParserTest.kt index 03e73b1ec93..723f64c0563 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/tombstone/TombstoneParserTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/tombstone/TombstoneParserTest.kt @@ -121,7 +121,7 @@ class TombstoneParserTest { if (frame.isInApp!!) { assert( frame.function!!.startsWith(inAppIncludes[0]) || - frame.`package`!!.startsWith(nativeLibraryDir) + frame.`package`!!.startsWith(nativeLibraryDir), ) } } @@ -166,7 +166,7 @@ class TombstoneParserTest { "/system/lib64/libc.so", buildId, 0, - ) + ), ) // Second mapping: r-xp at offset 0x1000 (executable segment) .addMemoryMapping( @@ -180,7 +180,7 @@ class TombstoneParserTest { "/system/lib64/libc.so", buildId, 0, - ) + ), ) // Third mapping: r--p at offset 0x10000 (read-only data) .addMemoryMapping( @@ -194,7 +194,7 @@ class TombstoneParserTest { "/system/lib64/libc.so", buildId, 0, - ) + ), ) // Fourth mapping: rw-p at offset 0x11000 (writable data) .addMemoryMapping( @@ -208,7 +208,7 @@ class TombstoneParserTest { "/system/lib64/libc.so", buildId, 0, - ) + ), ) .addThread( TombstoneThread( @@ -221,7 +221,7 @@ class TombstoneParserTest { emptyList(), 0, 0, - ) + ), ) .build() @@ -262,7 +262,7 @@ class TombstoneParserTest { "/system/lib64/libdl.so", buildId, 0, - ) + ), ) // Second mapping: r-xp at offset 0 (duplicate!) .addMemoryMapping( @@ -276,7 +276,7 @@ class TombstoneParserTest { "/system/lib64/libdl.so", buildId, 0, - ) + ), ) // Third mapping: r--p at offset 0 (another duplicate!) .addMemoryMapping( @@ -290,7 +290,7 @@ class TombstoneParserTest { "/system/lib64/libdl.so", buildId, 0, - ) + ), ) .addThread( TombstoneThread( @@ -303,7 +303,7 @@ class TombstoneParserTest { emptyList(), 0, 0, - ) + ), ) .build() @@ -341,7 +341,7 @@ class TombstoneParserTest { apkPath, firstBuildId, 0, - ) + ), ) .addMemoryMapping( MemoryMapping( @@ -354,7 +354,7 @@ class TombstoneParserTest { apkPath, firstBuildId, 0, - ) + ), ) .addMemoryMapping( MemoryMapping( @@ -367,7 +367,7 @@ class TombstoneParserTest { apkPath, secondBuildId, 0, - ) + ), ) .addMemoryMapping( MemoryMapping( @@ -380,7 +380,7 @@ class TombstoneParserTest { apkPath, secondBuildId, 0, - ) + ), ) .build() @@ -417,7 +417,7 @@ class TombstoneParserTest { apkPath, buildId, 0, - ) + ), ) // The virtual-address progression can differ from the file-offset progression by one page. .addMemoryMapping( @@ -431,7 +431,7 @@ class TombstoneParserTest { apkPath, "", 0, - ) + ), ) // Each PT_LOAD adds one page of alignment drift. Validation must compare adjacent // mappings so this drift does not accumulate from the start of the module. @@ -446,7 +446,7 @@ class TombstoneParserTest { apkPath, "", 0, - ) + ), ) .build() @@ -478,7 +478,7 @@ class TombstoneParserTest { apkPath, buildId, 0, - ) + ), ) // A different ELF in the APK that does not have a GNU build ID. .addMemoryMapping( @@ -492,7 +492,7 @@ class TombstoneParserTest { apkPath, "", 0x4000, - ) + ), ) .build() @@ -526,7 +526,7 @@ class TombstoneParserTest { apkPath, buildId, 0, - ) + ), ) .addThread( TombstoneThread( @@ -545,12 +545,12 @@ class TombstoneParserTest { "$apkPath!libnative-sample.so", 0x156c000, buildId, - ) + ), ), emptyList(), 0, 0, - ) + ), ) .build() @@ -583,7 +583,7 @@ class TombstoneParserTest { "/system/lib64/libc.so", invalidBuildId, 0, - ) + ), ) .addMemoryMapping( MemoryMapping( @@ -596,7 +596,7 @@ class TombstoneParserTest { "/system/lib64/libm.so", validBuildId, 0, - ) + ), ) .addThread( TombstoneThread( @@ -609,7 +609,7 @@ class TombstoneParserTest { emptyList(), 0, 0, - ) + ), ) .build() @@ -633,7 +633,7 @@ class TombstoneParserTest { fun `parses APK embedded ELF from full tombstone fixture`() { val tombstoneStream = GZIPInputStream( - TombstoneParserTest::class.java.getResourceAsStream("/tombstone_apk_embedded.pb.gz") + TombstoneParserTest::class.java.getResourceAsStream("/tombstone_apk_embedded.pb.gz"), ) val event = TombstoneParser(tombstoneStream, inAppIncludes, inAppExcludes, nativeLibraryDir).parse() @@ -699,7 +699,7 @@ class TombstoneParserTest { emptyList(), 0, 0, - ) + ), ) .addThread( TombstoneThread( @@ -712,7 +712,7 @@ class TombstoneParserTest { emptyList(), 0, 0, - ) + ), ) .addThread( TombstoneThread( @@ -725,7 +725,7 @@ class TombstoneParserTest { emptyList(), 0, 0, - ) + ), ) .build() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderConcurrencyTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderConcurrencyTest.kt new file mode 100644 index 00000000000..bce34be5e27 --- /dev/null +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderConcurrencyTest.kt @@ -0,0 +1,916 @@ +package io.sentry.android.core.internal.util + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager.PERMISSION_GRANTED +import android.net.ConnectivityManager +import android.net.ConnectivityManager.NetworkCallback +import android.net.Network +import android.net.NetworkCapabilities +import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET +import android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED +import android.net.NetworkCapabilities.TRANSPORT_CELLULAR +import android.net.NetworkCapabilities.TRANSPORT_WIFI +import android.os.Build +import android.telephony.TelephonyCallback +import android.telephony.TelephonyManager +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import io.sentry.IConnectionStatusProvider.ConnectionStatus +import io.sentry.IConnectionStatusProvider.IConnectionStatusObserver +import io.sentry.ILogger +import io.sentry.ISentryExecutorService +import io.sentry.SentryOptions +import io.sentry.android.core.AppState +import io.sentry.android.core.BuildInfoProvider +import io.sentry.android.core.ContextUtils +import io.sentry.test.DeferredExecutorService +import io.sentry.time.TestMonotonicTicker +import java.util.concurrent.Callable +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.Future +import java.util.concurrent.FutureTask +import java.util.concurrent.TimeUnit.MINUTES +import java.util.concurrent.TimeUnit.SECONDS +import java.util.concurrent.TimeoutException +import kotlin.test.AfterTest +import kotlin.test.Test +import org.junit.runner.RunWith +import org.mockito.MockedStatic +import org.mockito.Mockito.CALLS_REAL_METHODS +import org.mockito.Mockito.mockStatic +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doAnswer +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 +import org.mockito.kotlin.verifyNoInteractions +import org.mockito.kotlin.whenever +import org.robolectric.annotation.Config + +/** + * Scenarios in which the SDK executor, network callbacks and callers such as the main thread use + * the provider at the same time. Slow system service calls are stalled with a [Stall], and calls + * that must not wait for them run on a separate caller thread with a bounded wait. + */ +@RunWith(AndroidJUnit4::class) +@Config(sdk = [Build.VERSION_CODES.TIRAMISU]) +class AndroidConnectionStatusProviderConcurrencyTest { + + @AfterTest + fun `tear down`() { + Fixture.closeAll() + } + + // Caller-side calls while the network callback registration is stalled + + @Test + fun `addConnectionStatusObserver does not wait for a stalled network callback registration`() { + val fixture = Fixture.create() + val stall = fixture.stallNetworkCallbackRegistration() + val connectionStatusProvider = fixture.createProvider() + stall.awaitEntered() + val observer = mock() + + val added = fixture.onCallerThread { + connectionStatusProvider.addConnectionStatusObserver(observer) + } + + assertThat(added).isTrue() + assertThat(connectionStatusProvider.statusObservers).containsExactly(observer) + } + + @Test + fun `getConnectionStatus refreshes an empty cache without waiting for a stalled network callback registration`() { + val fixture = Fixture.create() + val stall = fixture.stallNetworkCallbackRegistration() + val connectionStatusProvider = fixture.createProvider() + stall.awaitEntered() + + val status = fixture.onCallerThread { connectionStatusProvider.connectionStatus } + + assertThat(status).isEqualTo(ConnectionStatus.CONNECTED) + } + + @Test + fun `getConnectionType refreshes an empty cache without waiting for a stalled network callback registration`() { + val fixture = Fixture.create() + val stall = fixture.stallNetworkCallbackRegistration() + val connectionStatusProvider = fixture.createProvider() + stall.awaitEntered() + + val type = fixture.onCallerThread { connectionStatusProvider.connectionType } + + assertThat(type).isEqualTo("wifi") + } + + @Test + fun `getConnection refreshes an empty cache without waiting for a stalled network callback registration`() { + val fixture = Fixture.create() + val stall = fixture.stallNetworkCallbackRegistration() + val connectionStatusProvider = fixture.createProvider() + stall.awaitEntered() + + val connection = fixture.onCallerThread { connectionStatusProvider.connection } + + assertThat(connection.type).isEqualTo("wifi") + } + + // Caller-side calls while the telephony callback registration is stalled + + @Test + fun `addConnectionStatusObserver does not wait for a stalled telephony callback registration`() { + val fixture = Fixture.create(sdkVersion = Build.VERSION_CODES.S) + val stall = fixture.stallTelephonyCallbackRegistration() + val connectionStatusProvider = fixture.createProvider() + stall.awaitEntered() + val observer = mock() + + val added = fixture.onCallerThread { + connectionStatusProvider.addConnectionStatusObserver(observer) + } + + assertThat(added).isTrue() + assertThat(connectionStatusProvider.statusObservers).containsExactly(observer) + } + + @Test + fun `removeConnectionStatusObserver does not wait for a stalled telephony callback registration`() { + val fixture = Fixture.create(sdkVersion = Build.VERSION_CODES.S) + val connectionStatusProvider = fixture.createRegisteredProvider() + val observer = mock() + connectionStatusProvider.addConnectionStatusObserver(observer) + connectionStatusProvider.onBackground() + fixture.awaitExecutorIdle() + val stall = fixture.stallTelephonyCallbackRegistration() + connectionStatusProvider.onForeground() + stall.awaitEntered() + + fixture.onCallerThread { connectionStatusProvider.removeConnectionStatusObserver(observer) } + + assertThat(connectionStatusProvider.statusObservers).isEmpty() + } + + @Test + fun `getConnectionStatus refreshes an empty cache without waiting for a stalled telephony callback registration`() { + val fixture = Fixture.create(sdkVersion = Build.VERSION_CODES.S) + val stall = fixture.stallTelephonyCallbackRegistration() + val connectionStatusProvider = fixture.createProvider() + stall.awaitEntered() + + val status = fixture.onCallerThread { connectionStatusProvider.connectionStatus } + + assertThat(status).isEqualTo(ConnectionStatus.CONNECTED) + } + + // Caller-side calls while unregistering in the background is stalled + + @Test + fun `addConnectionStatusObserver does not wait for a stalled network callback unregistration`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val stall = fixture.stallNetworkCallbackUnregistration() + connectionStatusProvider.onBackground() + stall.awaitEntered() + val observer = mock() + + val added = fixture.onCallerThread { + connectionStatusProvider.addConnectionStatusObserver(observer) + } + + assertThat(added).isTrue() + assertThat(connectionStatusProvider.statusObservers).containsExactly(observer) + } + + @Test + fun `getConnectionStatus refreshes an empty cache without waiting for a stalled network callback unregistration`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val stall = fixture.stallNetworkCallbackUnregistration() + connectionStatusProvider.onBackground() + stall.awaitEntered() + + val status = fixture.onCallerThread { connectionStatusProvider.connectionStatus } + + assertThat(status).isEqualTo(ConnectionStatus.CONNECTED) + } + + @Test + fun `addConnectionStatusObserver does not wait for a stalled telephony callback unregistration`() { + val fixture = Fixture.create(sdkVersion = Build.VERSION_CODES.S) + val connectionStatusProvider = fixture.createRegisteredProvider() + val stall = fixture.stallTelephonyCallbackUnregistration() + connectionStatusProvider.onBackground() + stall.awaitEntered() + val observer = mock() + + val added = fixture.onCallerThread { + connectionStatusProvider.addConnectionStatusObserver(observer) + } + + assertThat(added).isTrue() + assertThat(connectionStatusProvider.statusObservers).containsExactly(observer) + } + + @Test + fun `getConnectionStatus refreshes an empty cache without waiting for a stalled telephony callback unregistration`() { + val fixture = Fixture.create(sdkVersion = Build.VERSION_CODES.S) + val connectionStatusProvider = fixture.createRegisteredProvider() + val stall = fixture.stallTelephonyCallbackUnregistration() + connectionStatusProvider.onBackground() + stall.awaitEntered() + + val status = fixture.onCallerThread { connectionStatusProvider.connectionStatus } + + assertThat(status).isEqualTo(ConnectionStatus.CONNECTED) + } + + // An in-flight cache refresh racing a network callback + + @Test + fun `a network capabilities change survives an in-flight cache refresh`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + networkCallback.onAvailable(fixture.network) + val stall = fixture.stallNetworkCapabilitiesQuery() + val refresh = fixture.startOnCallerThread { connectionStatusProvider.connectionType } + stall.awaitEntered() + + fixture.onCallerThread { + networkCallback.onCapabilitiesChanged(fixture.network, fixture.cellularCapabilities) + } + stall.release() + val type = refresh.get(TIMEOUT_SECONDS, SECONDS) + + assertThat(type).isEqualTo("cellular") + } + + @Test + fun `a network loss survives an in-flight cache refresh`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + networkCallback.onAvailable(fixture.network) + val stall = fixture.stallNetworkCapabilitiesQuery() + val refresh = fixture.startOnCallerThread { connectionStatusProvider.connectionStatus } + stall.awaitEntered() + + fixture.onCallerThread { networkCallback.onLost(fixture.network) } + stall.release() + refresh.get(TIMEOUT_SECONDS, SECONDS) + + assertThat(connectionStatusProvider.cachedNetworkCapabilities).isNull() + } + + @Test + fun `a network that becomes available during an in-flight cache refresh stays the current network`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + val observer = mock() + connectionStatusProvider.addConnectionStatusObserver(observer) + val stall = fixture.stallNetworkCapabilitiesQuery() + val refresh = fixture.startOnCallerThread { connectionStatusProvider.connectionStatus } + stall.awaitEntered() + + fixture.onCallerThread { networkCallback.onAvailable(fixture.network) } + stall.release() + refresh.get(TIMEOUT_SECONDS, SECONDS) + networkCallback.onLost(fixture.network) + + verify(observer).onConnectionStatusChanged(ConnectionStatus.DISCONNECTED) + } + + @Test + fun `an in-flight refresh of a stale cache keeps its query result when another network becomes available`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + networkCallback.onAvailable(fixture.network) + networkCallback.onCapabilitiesChanged(fixture.network, fixture.wifiCapabilities) + fixture.ticker.advance(CACHE_EXPIRY_MINUTES, MINUTES) + val stall = fixture.stallNetworkCapabilitiesQuery(result = fixture.cellularCapabilities) + val refresh = fixture.startOnCallerThread { connectionStatusProvider.connectionType } + stall.awaitEntered() + + fixture.onCallerThread { networkCallback.onAvailable(fixture.otherNetwork) } + stall.release() + val type = refresh.get(TIMEOUT_SECONDS, SECONDS) + + assertThat(type).isEqualTo("cellular") + } + + @Test + fun `getConnectionType reads a fresh cache without waiting for another caller's in-flight cache refresh`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + networkCallback.onAvailable(fixture.network) + val stall = fixture.stallNetworkCapabilitiesQuery() + val refresh = fixture.startOnCallerThread { connectionStatusProvider.connectionType } + stall.awaitEntered() + fixture.onCallerThread { + networkCallback.onCapabilitiesChanged(fixture.network, fixture.cellularCapabilities) + } + + val type = fixture.onCallerThread { connectionStatusProvider.connectionType } + stall.release() + refresh.get(TIMEOUT_SECONDS, SECONDS) + + assertThat(type).isEqualTo("cellular") + } + + // Observers being notified + + @Test + fun `addConnectionStatusObserver does not wait for an observer that is being notified`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + networkCallback.onAvailable(fixture.network) + val stall = fixture.newStall() + connectionStatusProvider.addConnectionStatusObserver { stall.block(Unit) } + val notification = fixture.startOnCallerThread { networkCallback.onLost(fixture.network) } + stall.awaitEntered() + val observer = mock() + + val added = fixture.onCallerThread { + connectionStatusProvider.addConnectionStatusObserver(observer) + } + stall.release() + notification.get(TIMEOUT_SECONDS, SECONDS) + + assertThat(added).isTrue() + assertThat(connectionStatusProvider.statusObservers).contains(observer) + } + + @Test + fun `removeConnectionStatusObserver does not wait for an observer that is being notified`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + networkCallback.onAvailable(fixture.network) + val stall = fixture.newStall() + connectionStatusProvider.addConnectionStatusObserver { stall.block(Unit) } + val observer = mock() + connectionStatusProvider.addConnectionStatusObserver(observer) + val notification = fixture.startOnCallerThread { networkCallback.onLost(fixture.network) } + stall.awaitEntered() + + fixture.onCallerThread { connectionStatusProvider.removeConnectionStatusObserver(observer) } + stall.release() + notification.get(TIMEOUT_SECONDS, SECONDS) + + assertThat(connectionStatusProvider.statusObservers).doesNotContain(observer) + } + + @Test + fun `an observer removing itself during a notification does not stop delivery to the other observers`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + networkCallback.onAvailable(fixture.network) + val selfRemovingObserver = + object : IConnectionStatusObserver { + override fun onConnectionStatusChanged(status: ConnectionStatus) { + connectionStatusProvider.removeConnectionStatusObserver(this) + } + } + val otherObserver = mock() + connectionStatusProvider.addConnectionStatusObserver(selfRemovingObserver) + connectionStatusProvider.addConnectionStatusObserver(otherObserver) + + networkCallback.onLost(fixture.network) + + verify(otherObserver).onConnectionStatusChanged(ConnectionStatus.DISCONNECTED) + assertThat(connectionStatusProvider.statusObservers).containsExactly(otherObserver) + } + + @Test + fun `an observer added during a notification only receives later notifications`() { + val fixture = Fixture.create() + val connectionStatusProvider = fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + networkCallback.onAvailable(fixture.network) + val addedObserver = mock() + val addingObserver = + object : IConnectionStatusObserver { + override fun onConnectionStatusChanged(status: ConnectionStatus) { + connectionStatusProvider.addConnectionStatusObserver(addedObserver) + } + } + connectionStatusProvider.addConnectionStatusObserver(addingObserver) + + networkCallback.onLost(fixture.network) + + verifyNoInteractions(addedObserver) + assertThat(connectionStatusProvider.statusObservers).contains(addedObserver) + + networkCallback.onUnavailable() + + verify(addedObserver).onConnectionStatusChanged(ConnectionStatus.DISCONNECTED) + } + + // Child network callbacks + + @Test + fun `addNetworkCallback does not wait for a child network callback that is being notified`() { + val fixture = Fixture.create() + fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + val stall = fixture.newStall() + fixture.addChildNetworkCallback( + object : NetworkCallback() { + override fun onAvailable(network: Network) { + stall.block(Unit) + } + }, + ) + val notification = fixture.startOnCallerThread { networkCallback.onAvailable(fixture.network) } + stall.awaitEntered() + val childNetworkCallback = mock() + + val added = fixture.onCallerThread { + AndroidConnectionStatusProvider.addNetworkCallback( + fixture.context, + fixture.logger, + fixture.buildInfo, + childNetworkCallback, + ) + } + stall.release() + notification.get(TIMEOUT_SECONDS, SECONDS) + + assertThat(added).isTrue() + assertThat(AndroidConnectionStatusProvider.getChildCallbacks()).contains(childNetworkCallback) + } + + @Test + fun `removeNetworkCallback does not wait for a child network callback that is being notified`() { + val fixture = Fixture.create() + fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + val stall = fixture.newStall() + fixture.addChildNetworkCallback( + object : NetworkCallback() { + override fun onAvailable(network: Network) { + stall.block(Unit) + } + }, + ) + val childNetworkCallback = mock() + fixture.addChildNetworkCallback(childNetworkCallback) + val notification = fixture.startOnCallerThread { networkCallback.onAvailable(fixture.network) } + stall.awaitEntered() + + fixture.onCallerThread { + AndroidConnectionStatusProvider.removeNetworkCallback(childNetworkCallback) + } + stall.release() + notification.get(TIMEOUT_SECONDS, SECONDS) + + assertThat(AndroidConnectionStatusProvider.getChildCallbacks()) + .doesNotContain(childNetworkCallback) + } + + @Test + fun `a child network callback removing itself during a notification does not stop delivery to the other child network callbacks`() { + val fixture = Fixture.create() + fixture.createRegisteredProvider() + val networkCallback = fixture.captureNetworkCallback() + fixture.addChildNetworkCallback( + object : NetworkCallback() { + override fun onAvailable(network: Network) { + AndroidConnectionStatusProvider.removeNetworkCallback(this) + } + }, + ) + val otherChildNetworkCallback = mock() + fixture.addChildNetworkCallback(otherChildNetworkCallback) + + networkCallback.onAvailable(fixture.network) + + verify(otherChildNetworkCallback).onAvailable(fixture.network) + assertThat(AndroidConnectionStatusProvider.getChildCallbacks()) + .containsExactly(otherChildNetworkCallback) + } + + // Foreground and background transitions queued behind other executor tasks + + @Test + fun `backgrounding while the initial network callback registration is queued unregisters the network callback`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(executorService = executor) + val connectionStatusProvider = fixture.createProvider() + + connectionStatusProvider.onBackground() + executor.runAll() + + assertThat(connectionStatusProvider.networkCallback).isNull() + verify(fixture.connectivityManager).unregisterNetworkCallback(any()) + } + + @Test + fun `backgrounding while the initial network callback registration is queued unregisters the telephony callback`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(sdkVersion = Build.VERSION_CODES.S, executorService = executor) + val connectionStatusProvider = fixture.createProvider() + + connectionStatusProvider.onBackground() + executor.runAll() + + verify(fixture.telephonyManager).unregisterTelephonyCallback(any()) + } + + @Test + fun `foregrounding while a background unregistration is queued registers the network callback again`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(executorService = executor) + val connectionStatusProvider = fixture.createProvider() + executor.runAll() + + connectionStatusProvider.onBackground() + connectionStatusProvider.onForeground() + executor.runAll() + + assertThat(connectionStatusProvider.networkCallback).isNotNull() + verify(fixture.connectivityManager, times(2)).registerDefaultNetworkCallback(any()) + } + + @Test + fun `adding an observer while a background unregistration is queued registers the network callback again`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(executorService = executor) + val connectionStatusProvider = fixture.createProvider() + executor.runAll() + + connectionStatusProvider.onBackground() + connectionStatusProvider.addConnectionStatusObserver(mock()) + executor.runAll() + + assertThat(connectionStatusProvider.networkCallback).isNotNull() + verify(fixture.connectivityManager, times(2)).registerDefaultNetworkCallback(any()) + } + + // Registrations queued around close + + @Test + fun `closing after the network callback registration ran unregisters the network callback`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(executorService = executor) + val connectionStatusProvider = fixture.createProvider() + executor.runAll() + + connectionStatusProvider.close() + executor.runAll() + + assertThat(connectionStatusProvider.networkCallback).isNull() + verify(fixture.connectivityManager).unregisterNetworkCallback(any()) + } + + @Test + fun `closing while the network callback registration is running unregisters the network callback`() { + val fixture = Fixture.create() + val stall = fixture.stallNetworkCallbackRegistration() + val connectionStatusProvider = fixture.createProvider() + stall.awaitEntered() + + connectionStatusProvider.close() + stall.release() + fixture.awaitExecutorIdle() + + assertThat(connectionStatusProvider.networkCallback).isNull() + verify(fixture.connectivityManager).unregisterNetworkCallback(any()) + } + + @Test + fun `closing while the initial network callback registration is queued does not register the network callback`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(executorService = executor) + val connectionStatusProvider = fixture.createProvider() + + connectionStatusProvider.close() + executor.runAll() + + assertThat(connectionStatusProvider.networkCallback).isNull() + verify(fixture.connectivityManager, never()).registerDefaultNetworkCallback(any()) + } + + @Test + fun `adding an observer after close does not register the network callback again`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(executorService = executor) + val connectionStatusProvider = fixture.createProvider() + executor.runAll() + connectionStatusProvider.close() + executor.runAll() + + connectionStatusProvider.addConnectionStatusObserver(mock()) + executor.runAll() + + assertThat(connectionStatusProvider.networkCallback).isNull() + verify(fixture.connectivityManager, times(1)).registerDefaultNetworkCallback(any()) + } + + @Test + fun `adding an observer after close does not register the telephony callback again`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(sdkVersion = Build.VERSION_CODES.S, executorService = executor) + val connectionStatusProvider = fixture.createProvider() + executor.runAll() + connectionStatusProvider.close() + executor.runAll() + + connectionStatusProvider.addConnectionStatusObserver(mock()) + executor.runAll() + + verify(fixture.telephonyManager, times(1)).registerTelephonyCallback(any(), any()) + } + + @Test + fun `foregrounding after close does not register the network callback again`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(executorService = executor) + val connectionStatusProvider = fixture.createProvider() + executor.runAll() + connectionStatusProvider.close() + executor.runAll() + + connectionStatusProvider.onForeground() + executor.runAll() + + assertThat(connectionStatusProvider.networkCallback).isNull() + verify(fixture.connectivityManager, times(1)).registerDefaultNetworkCallback(any()) + } + + @Test + fun `foregrounding after close does not notify child network callbacks of a lost network`() { + val executor = DeferredExecutorService() + val fixture = Fixture.create(executorService = executor) + val connectionStatusProvider = fixture.createProvider() + executor.runAll() + connectionStatusProvider.close() + executor.runAll() + val childNetworkCallback = mock() + fixture.addChildNetworkCallback(childNetworkCallback) + whenever(fixture.connectivityManager.activeNetwork).thenReturn(null) + + connectionStatusProvider.onForeground() + executor.runAll() + + verify(childNetworkCallback, never()).onLost(anyOrNull()) + } + + /** Blocks a mocked system service call until released, or until a timeout elapses. */ + private class Stall { + private val entered = CountDownLatch(1) + private val released = CountDownLatch(1) + + fun block(result: T): T { + entered.countDown() + released.await(STALL_TIMEOUT_SECONDS, SECONDS) + return result + } + + fun awaitEntered() { + assertThat(entered.await(TIMEOUT_SECONDS, SECONDS)).isTrue() + } + + fun release() { + released.countDown() + } + } + + /** + * Runs tasks in order on a single thread, like the SDK executor. Mockito's static mocks only + * apply to the thread that creates them, so the thread mocks + * [ContextUtils.isForegroundImportance] itself. + */ + private class SingleThreadExecutorService : ISentryExecutorService { + private val executor: ExecutorService = Executors.newSingleThreadExecutor { + Thread(it, "test-sentry-executor").apply { isDaemon = true } + } + private lateinit var contextUtils: MockedStatic + + init { + executor.submit { contextUtils = mockForegroundImportance() }.get(TIMEOUT_SECONDS, SECONDS) + } + + fun awaitIdle() { + executor.submit {}.get(TIMEOUT_SECONDS, SECONDS) + } + + fun shutdown() { + executor.submit { contextUtils.close() }.get(TIMEOUT_SECONDS, SECONDS) + executor.shutdown() + executor.awaitTermination(TIMEOUT_SECONDS, SECONDS) + } + + override fun submit(runnable: Runnable): Future<*> = executor.submit(runnable) + + override fun submit(callable: Callable): Future = executor.submit(callable) + + override fun schedule(runnable: Runnable, delayMillis: Long): Future<*> = + throw UnsupportedOperationException() + + override fun close(timeoutMillis: Long) {} + + override fun isClosed(): Boolean = executor.isShutdown + } + + private class Fixture + private constructor( + sdkVersion: Int, + private val executorService: ISentryExecutorService, + ) { + val context = mock() + val connectivityManager = mock() + val telephonyManager = mock() + val buildInfo = mock() + val logger = mock() + val network = mock() + val otherNetwork = mock() + val wifiCapabilities = capabilities(TRANSPORT_WIFI) + val cellularCapabilities = capabilities(TRANSPORT_CELLULAR) + val ticker = TestMonotonicTicker() + private val stalls = mutableListOf() + private val callerThreads = mutableListOf() + + private val options = SentryOptions() + private val contextUtils = mockForegroundImportance() + private var connectionStatusProvider: AndroidConnectionStatusProvider? = null + + init { + whenever(context.getSystemService(Context.CONNECTIVITY_SERVICE)) + .thenReturn(connectivityManager) + whenever(context.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(telephonyManager) + whenever(context.checkPermission(eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any())) + .thenReturn(PERMISSION_GRANTED) + whenever(buildInfo.sdkInfoVersion).thenReturn(sdkVersion) + whenever(connectivityManager.activeNetwork).thenReturn(network) + whenever(connectivityManager.getNetworkCapabilities(any())).thenReturn(wifiCapabilities) + + // Another suite can leave its connectivity manager and child callbacks in the static fields. + AndroidConnectionStatusProvider::class + .java + .getDeclaredField("connectivityManager") + .apply { isAccessible = true } + .set(null, null) + AndroidConnectionStatusProvider.getChildCallbacks().clear() + + options.setLogger(logger) + options.executorService = executorService + + AppState.getInstance().resetInstance() + AppState.getInstance().registerLifecycleObserver(options) + } + + fun createProvider(): AndroidConnectionStatusProvider = + AndroidConnectionStatusProvider(context, options, buildInfo, ticker).also { + connectionStatusProvider = it + } + + /** Creates a provider and waits until its network callback registration has run. */ + fun createRegisteredProvider(): AndroidConnectionStatusProvider = + createProvider().also { awaitExecutorIdle() } + + fun awaitExecutorIdle() { + (executorService as SingleThreadExecutorService).awaitIdle() + } + + fun captureNetworkCallback(): NetworkCallback { + val captor = argumentCaptor() + verify(connectivityManager).registerDefaultNetworkCallback(captor.capture()) + return captor.lastValue + } + + fun addChildNetworkCallback(networkCallback: NetworkCallback) { + AndroidConnectionStatusProvider.addNetworkCallback( + context, + logger, + buildInfo, + networkCallback, + ) + } + + fun stallNetworkCallbackRegistration(): Stall = + newStall().also { stall -> + doAnswer { stall.block(null) } + .whenever(connectivityManager) + .registerDefaultNetworkCallback(any()) + } + + fun stallNetworkCallbackUnregistration(): Stall = + newStall().also { stall -> + doAnswer { stall.block(null) } + .whenever(connectivityManager) + .unregisterNetworkCallback(any()) + } + + fun stallTelephonyCallbackRegistration(): Stall = + newStall().also { stall -> + doAnswer { stall.block(null) } + .whenever(telephonyManager) + .registerTelephonyCallback(any(), any()) + } + + fun stallTelephonyCallbackUnregistration(): Stall = + newStall().also { stall -> + doAnswer { stall.block(null) } + .whenever(telephonyManager) + .unregisterTelephonyCallback(any()) + } + + fun stallNetworkCapabilitiesQuery(result: NetworkCapabilities = wifiCapabilities): Stall = + newStall().also { stall -> + whenever(connectivityManager.getNetworkCapabilities(any())).thenAnswer { + stall.block(result) + } + } + + fun newStall(): Stall = Stall().also { stalls += it } + + /** Starts [action] on a new thread, standing in for a caller such as the main thread. */ + fun startOnCallerThread(action: () -> T): FutureTask = + FutureTask(action).also { task -> + callerThreads += Thread(task, "test-caller").apply { isDaemon = true }.also { it.start() } + } + + /** Runs [action] on a new caller thread and fails if it does not complete in time. */ + fun onCallerThread(action: () -> T): T { + val task = startOnCallerThread(action) + try { + return task.get(TIMEOUT_SECONDS, SECONDS) + } catch (e: TimeoutException) { + throw AssertionError("The call did not complete within $TIMEOUT_SECONDS seconds", e) + } + } + + fun close() { + stalls.forEach { it.release() } + // A caller that is still running after close() would cache this test's connectivity + // manager in the static field that close() resets, and leak it into the next test. + callerThreads.forEach { it.join(SECONDS.toMillis(TIMEOUT_SECONDS)) } + val hungCallerThreads = callerThreads.count { it.isAlive } + connectionStatusProvider?.close() + when (executorService) { + is SingleThreadExecutorService -> executorService.shutdown() + is DeferredExecutorService -> executorService.runAll() + } + contextUtils.close() + AppState.getInstance().unregisterLifecycleObserver() + assertWithMessage("Caller threads still running after their stalls were released") + .that(hungCallerThreads) + .isEqualTo(0) + } + + companion object { + private val created = mutableListOf() + + fun create( + sdkVersion: Int = Build.VERSION_CODES.N, + executorService: ISentryExecutorService = SingleThreadExecutorService(), + ): Fixture = Fixture(sdkVersion, executorService).also { created += it } + + fun closeAll() { + created.forEach { it.close() } + created.clear() + } + + private fun capabilities(transport: Int): NetworkCapabilities { + val capabilities = mock() + whenever(capabilities.hasCapability(NET_CAPABILITY_INTERNET)).thenReturn(true) + whenever(capabilities.hasCapability(NET_CAPABILITY_VALIDATED)).thenReturn(true) + whenever(capabilities.hasTransport(transport)).thenReturn(true) + return capabilities + } + } + } + + private companion object { + /** Bounds every wait, so a regression fails the test instead of hanging the build. */ + const val TIMEOUT_SECONDS = 5L + + /** Longer than the provider's 2-minute cache TTL, so advancing by it makes the cache stale. */ + const val CACHE_EXPIRY_MINUTES = 3L + + /** + * Bounds a stalled call, which the test releases itself. Much longer than [TIMEOUT_SECONDS], so + * that a caller waiting for the stalled call times out before the stall gives up. + */ + const val STALL_TIMEOUT_SECONDS = 30L + + fun mockForegroundImportance(): MockedStatic = + mockStatic(ContextUtils::class.java, CALLS_REAL_METHODS).also { + it.`when` { ContextUtils.isForegroundImportance() }.thenReturn(true) + } + } +} diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderTest.kt index d534ba436d3..20afcff46c2 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/AndroidConnectionStatusProviderTest.kt @@ -19,8 +19,10 @@ import android.os.Handler import android.os.Looper import android.telephony.TelephonyManager import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat import io.sentry.IConnectionStatusProvider import io.sentry.ILogger +import io.sentry.SentryLevel import io.sentry.SentryOptions import io.sentry.android.core.AppState import io.sentry.android.core.BuildInfoProvider @@ -78,7 +80,7 @@ class AndroidConnectionStatusProviderTest { whenever(contextMock.getSystemService(Context.CONNECTIVITY_SERVICE)) .thenReturn(connectivityManager) whenever( - contextMock.checkPermission(eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any()) + contextMock.checkPermission(eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any()), ) .thenReturn(PERMISSION_GRANTED) @@ -185,7 +187,7 @@ class AndroidConnectionStatusProviderTest { eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any(), - ) + ), ) .thenReturn(PERMISSION_GRANTED) @@ -256,7 +258,7 @@ class AndroidConnectionStatusProviderTest { /// Lets a test reject work only after the setup that needs a working executor is done. @Test - @Config(sdk = [Build.VERSION_CODES.S]) + @Config(sdk = [Build.VERSION_CODES.TIRAMISU]) fun `When the network callback cannot be registered, the telephony listener is not started`() { // Without ACCESS_NETWORK_STATE the network callback registration fails, and onBackground skips // unregistering while there is no network callback, so the listener must not be started here. @@ -264,7 +266,7 @@ class AndroidConnectionStatusProviderTest { whenever(contextMock.getSystemService(eq(Context.TELEPHONY_SERVICE))) .thenReturn(telephonyManager) whenever( - contextMock.checkPermission(eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any()) + contextMock.checkPermission(eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any()), ) .thenReturn(PERMISSION_DENIED) whenever(buildInfo.sdkInfoVersion).thenReturn(Build.VERSION_CODES.S) @@ -303,7 +305,7 @@ class AndroidConnectionStatusProviderTest { whenever(contextMock.checkPermission(eq(Manifest.permission.READ_PHONE_STATE), any(), any())) .thenReturn(PERMISSION_DENIED) whenever( - contextMock.checkPermission(eq(Manifest.permission.READ_BASIC_PHONE_STATE), any(), any()) + contextMock.checkPermission(eq(Manifest.permission.READ_BASIC_PHONE_STATE), any(), any()), ) .thenReturn(PERMISSION_DENIED) @@ -352,7 +354,7 @@ class AndroidConnectionStatusProviderTest { buildInfo, null, mock(), - ) + ), ) } @@ -379,6 +381,23 @@ class AndroidConnectionStatusProviderTest { assertTrue(connectionStatusProvider.statusObservers.isEmpty()) } + @Test + fun `addConnectionStatusObserver adds the observer and returns true when the network callback cannot be registered`() { + whenever( + contextMock.checkPermission(eq(Manifest.permission.ACCESS_NETWORK_STATE), any(), any()), + ) + .thenReturn(PERMISSION_DENIED) + val provider = AndroidConnectionStatusProvider(contextMock, options, buildInfo, ticker) + val observer = IConnectionStatusProvider.IConnectionStatusObserver {} + + val added = provider.addConnectionStatusObserver(observer) + + assertThat(added).isTrue() + assertThat(provider.statusObservers).containsExactly(observer) + assertThat(provider.networkCallback).isNull() + provider.close() + } + @Test fun `an unpopulated cache is not treated as fresh shortly after boot`() { whenever(networkInfo.isConnected).thenReturn(true) @@ -400,6 +419,31 @@ class AndroidConnectionStatusProviderTest { provider.close() } + @Test + fun `a stale-cache refresh without network capabilities does not query the connectivity manager for its debug log when debug logging is off`() { + options.isDebug = false + whenever(networkInfo.isConnected).thenReturn(true) + whenever(connectivityManager.activeNetwork).thenReturn(null) + clearInvocations(connectivityManager) + + val status = connectionStatusProvider.connectionStatus + + assertThat(status).isEqualTo(IConnectionStatusProvider.ConnectionStatus.CONNECTED) + // Only the refresh and the returned status query; the debug log message is not built. + verify(connectivityManager, times(1)).activeNetwork + verify(connectivityManager, times(1)).activeNetworkInfo + } + + @Test + fun `a stale-cache refresh logs the refreshed connection status and type when debug logging is on`() { + options.isDebug = true + whenever(networkInfo.isConnected).thenReturn(true) + + connectionStatusProvider.connectionStatus + + verify(logger).log(eq(SentryLevel.DEBUG), eq("Cache updated - Status: CONNECTED, Type: wifi")) + } + @Test fun `cache TTL works correctly`() { // Setup: Mock network info to return connected @@ -781,9 +825,9 @@ class AndroidConnectionStatusProviderTest { connectionStatusProvider.onBackground() assertFalse( - AppState.getInstance().lifecycleObserver.listeners.any { + AppState.getInstance().lifecycleObserver!!.listeners.any { it is SystemEventsBreadcrumbsIntegration - } + }, ) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/CellularNetworkTechnologyProviderTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/CellularNetworkTechnologyProviderTest.kt index 29047ee304e..6c9250836a3 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/CellularNetworkTechnologyProviderTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/CellularNetworkTechnologyProviderTest.kt @@ -27,7 +27,7 @@ import org.mockito.kotlin.whenever import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) -@Config(sdk = [Build.VERSION_CODES.S]) +@Config(sdk = [Build.VERSION_CODES.TIRAMISU]) class CellularNetworkTechnologyProviderTest { private class Fixture { val context = mock() @@ -57,7 +57,7 @@ class CellularNetworkTechnologyProviderTest { /** Registers the provider and returns the callback the telephony manager received. */ fun registerAndCaptureCallback( - provider: CellularNetworkTechnologyProvider + provider: CellularNetworkTechnologyProvider, ): TelephonyCallback.DisplayInfoListener { provider.register() val captor = argumentCaptor() @@ -118,17 +118,19 @@ class CellularNetworkTechnologyProviderTest { @Test fun `networkTypeToGeneration maps fourth and fifth generation network types`() { assertThat( - CellularNetworkTechnologyProvider.networkTypeToGeneration(TelephonyManager.NETWORK_TYPE_LTE) + CellularNetworkTechnologyProvider.networkTypeToGeneration( + TelephonyManager.NETWORK_TYPE_LTE, + ), ) .isEqualTo("4g") assertThat( CellularNetworkTechnologyProvider.networkTypeToGeneration( - TelephonyManager.NETWORK_TYPE_IWLAN - ) + TelephonyManager.NETWORK_TYPE_IWLAN, + ), ) .isEqualTo("4g") assertThat( - CellularNetworkTechnologyProvider.networkTypeToGeneration(TelephonyManager.NETWORK_TYPE_NR) + CellularNetworkTechnologyProvider.networkTypeToGeneration(TelephonyManager.NETWORK_TYPE_NR), ) .isEqualTo("5g") } @@ -137,8 +139,8 @@ class CellularNetworkTechnologyProviderTest { fun `networkTypeToGeneration returns null for unknown network types`() { assertThat( CellularNetworkTechnologyProvider.networkTypeToGeneration( - TelephonyManager.NETWORK_TYPE_UNKNOWN - ) + TelephonyManager.NETWORK_TYPE_UNKNOWN, + ), ) .isNull() } @@ -215,7 +217,7 @@ class CellularNetworkTechnologyProviderTest { fixture.displayInfo( networkType = TelephonyManager.NETWORK_TYPE_NR, overrideNetworkType = TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE, - ) + ), ) assertThat(provider.cellularNetworkTechnology).isEqualTo("5g") @@ -230,7 +232,7 @@ class CellularNetworkTechnologyProviderTest { fixture.displayInfo( networkType = TelephonyManager.NETWORK_TYPE_LTE, overrideNetworkType = TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE, - ) + ), ) assertThat(provider.cellularNetworkTechnology).isEqualTo("4g") @@ -255,10 +257,10 @@ class CellularNetworkTechnologyProviderTest { val done = CountDownLatch(threadCount) repeat(threadCount) { Thread { - start.await() - provider.register() - done.countDown() - } + start.await() + provider.register() + done.countDown() + } .start() } @@ -276,7 +278,7 @@ class CellularNetworkTechnologyProviderTest { fixture.displayInfo( networkType = TelephonyManager.NETWORK_TYPE_LTE, overrideNetworkType = TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE, - ) + ), ) provider.unregister() @@ -294,7 +296,7 @@ class CellularNetworkTechnologyProviderTest { fixture.displayInfo( networkType = TelephonyManager.NETWORK_TYPE_NR, overrideNetworkType = TelephonyDisplayInfo.OVERRIDE_NETWORK_TYPE_NONE, - ) + ), ) provider.unregister() diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/DebouncerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/DebouncerTest.kt index 3a3e7778070..7177b5ecb96 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/DebouncerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/DebouncerTest.kt @@ -1,28 +1,23 @@ package io.sentry.android.core.internal.util -import io.sentry.transport.ICurrentDateProvider -import kotlin.test.BeforeTest +import io.sentry.time.TestMonotonicTicker +import java.util.concurrent.TimeUnit import kotlin.test.Test import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue class DebouncerTest { - private class Fixture : ICurrentDateProvider { - var currentTimeMs: Long = 0 + private class Fixture { + val ticker = TestMonotonicTicker() - override fun getCurrentTimeMillis(): Long = currentTimeMs + fun advance(millis: Long) = ticker.advance(millis, TimeUnit.MILLISECONDS) fun getDebouncer(waitTimeMs: Long = 3000, maxExecutions: Int = 1): Debouncer = - Debouncer(this, waitTimeMs, maxExecutions) + Debouncer(ticker, waitTimeMs, maxExecutions) } private val fixture = Fixture() - @BeforeTest - fun `set up`() { - fixture.currentTimeMs = 0 - } - @Test fun `Debouncer should not debounce on the first check`() { val debouncer = fixture.getDebouncer() @@ -39,27 +34,34 @@ class DebouncerTest { @Test fun `Debouncer should signal debounce if the second invocation is too early`() { - fixture.currentTimeMs = 1000 val debouncer = fixture.getDebouncer(3000) assertFalse(debouncer.checkForDebounce()) - fixture.currentTimeMs = 3999 + fixture.advance(2999) assertTrue(debouncer.checkForDebounce()) } @Test fun `Debouncer should not signal debounce if the second invocation is late enough`() { - fixture.currentTimeMs = 1000 val debouncer = fixture.getDebouncer(3000) assertFalse(debouncer.checkForDebounce()) - fixture.currentTimeMs = 4000 + fixture.advance(3000) + assertFalse(debouncer.checkForDebounce()) + } + + @Test + fun `Debouncer does not debounce after a window that expired during deep sleep`() { + val debouncer = fixture.getDebouncer(60_000) + assertFalse(debouncer.checkForDebounce()) + + // The ticker keeps counting while the device sleeps, so an hour asleep expires the window. + fixture.advance(TimeUnit.HOURS.toMillis(1)) assertFalse(debouncer.checkForDebounce()) } @Test fun `Debouncer maxExecutions is always greater than 0`() { - fixture.currentTimeMs = 1000 val debouncer = fixture.getDebouncer(3000, -1) assertFalse(debouncer.checkForDebounce()) assertTrue(debouncer.checkForDebounce()) @@ -67,7 +69,6 @@ class DebouncerTest { @Test fun `Debouncer should signal debounce after maxExecutions calls`() { - fixture.currentTimeMs = 1000 val debouncer = fixture.getDebouncer(3000, 3) assertFalse(debouncer.checkForDebounce()) assertFalse(debouncer.checkForDebounce()) @@ -77,13 +78,12 @@ class DebouncerTest { @Test fun `Debouncer maxExecutions counter resets if the other invocation is late enough`() { - fixture.currentTimeMs = 1000 val debouncer = fixture.getDebouncer(3000, 3) assertFalse(debouncer.checkForDebounce()) assertFalse(debouncer.checkForDebounce()) // After waitTimeMs passes, the maxExecutions counter is reset - fixture.currentTimeMs = 4000 + fixture.advance(3000) assertFalse(debouncer.checkForDebounce()) assertFalse(debouncer.checkForDebounce()) assertFalse(debouncer.checkForDebounce()) @@ -92,7 +92,6 @@ class DebouncerTest { @Test fun `Debouncer maxExecutions counter resets after maxExecutions`() { - fixture.currentTimeMs = 1000 val debouncer = fixture.getDebouncer(3000, 3) assertFalse(debouncer.checkForDebounce()) assertFalse(debouncer.checkForDebounce()) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/RootCheckerTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/RootCheckerTest.kt index 71368b80ae9..3dc060bb635 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/RootCheckerTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/RootCheckerTest.kt @@ -89,7 +89,7 @@ class RootCheckerTest { fixture.packageManager.getPackageInfo( eq("com.devadvance.rootcloak"), any(), - ) + ), ) .thenReturn(packageInfo) @@ -106,7 +106,7 @@ class RootCheckerTest { fixture.packageManager.getPackageInfo( eq("com.devadvance.rootcloak"), any(), - ) + ), ) .thenThrow(PackageManager.NameNotFoundException()) diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilTest.kt index 5e74042d3d1..c63addd55cc 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilTest.kt @@ -22,7 +22,7 @@ import org.robolectric.Robolectric.buildActivity import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowPixelCopy -@Config(shadows = [ShadowPixelCopy::class], sdk = [26, 33]) +@Config(shadows = [ShadowPixelCopy::class], sdk = [30, 33]) @RunWith(AndroidJUnit4::class) class ScreenshotUtilTest { @Test diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilsMaskedScreenshotTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilsMaskedScreenshotTest.kt index 9f6e220c2d2..2585990fcdf 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilsMaskedScreenshotTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilsMaskedScreenshotTest.kt @@ -138,7 +138,7 @@ private class TextActivity : Activity() { setTextColor(Color.BLACK) textSize = 32f layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) - } + }, ) setContentView(linearLayout) } diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTest.kt b/sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTest.kt index 1cae2cdeba8..a989e62ecd0 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTest.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTest.kt @@ -138,7 +138,7 @@ class AppStartMetricsTest { description = "ExampleContentProvider" setStartedAt(1) setStoppedAt(2) - } + }, ) metrics.applicationOnCreateTimeSpan.apply { diff --git a/sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTestApi35.kt b/sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTestApi35.kt index a7eace97371..c89054e9ca3 100644 --- a/sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTestApi35.kt +++ b/sentry-android-core/src/test/java/io/sentry/android/core/performance/AppStartMetricsTestApi35.kt @@ -169,8 +169,8 @@ class AppStartMetricsTestApi35 { .thenReturn( mapOf( ApplicationStartInfo.START_TIMESTAMP_APPLICATION_ONCREATE to - TimeUnit.MILLISECONDS.toNanos(onCreateStartUptimeMs) - ) + TimeUnit.MILLISECONDS.toNanos(onCreateStartUptimeMs), + ), ) SentryShadowActivityManager.setHistoricalProcessStartReasons(listOf(mockStartInfo)) SentryShadowActivityManager.setImportance(RunningAppProcessInfo.IMPORTANCE_CACHED) @@ -255,7 +255,7 @@ class AppStartMetricsTestApi35 { @Test fun `does not crash when getHistoricalProcessStartReasons throws RuntimeException`() { SentryShadowActivityManager.setHistoricalProcessStartReasonsException( - RuntimeException("isolated process") + RuntimeException("isolated process"), ) val metrics = AppStartMetrics.getInstance() diff --git a/sentry-android-distribution/build.gradle.kts b/sentry-android-distribution/build.gradle.kts index 1198867a9cb..cd4078eded8 100644 --- a/sentry-android-distribution/build.gradle.kts +++ b/sentry-android-distribution/build.gradle.kts @@ -9,6 +9,7 @@ plugins { id("io.sentry.jdk-target") id("io.sentry.publish") id("io.sentry.api-validation") + id("io.sentry.robolectric") } android { @@ -44,7 +45,7 @@ androidComponents.beforeVariants { dependencies { implementation(projects.sentry) implementation( - libs.jetbrains.annotations + libs.jetbrains.annotations, ) // Use implementation instead of compileOnly to override kotlin stdlib's version implementation(kotlin(Config.kotlinStdLib, Config.kotlinStdLibVersionAndroid)) testImplementation(libs.androidx.test.ext.junit) diff --git a/sentry-android-distribution/detekt-baseline.xml b/sentry-android-distribution/detekt-baseline.xml index 78b4ed376de..61fbab0629e 100644 --- a/sentry-android-distribution/detekt-baseline.xml +++ b/sentry-android-distribution/detekt-baseline.xml @@ -15,10 +15,6 @@ SwallowedException:DistributionIntegration.kt$DistributionIntegration$e: android.content.ActivityNotFoundException TooGenericExceptionCaught:DistributionIntegration.kt$DistributionIntegration$e: Exception TooGenericExceptionCaught:UpdateResponseParser.kt$UpdateResponseParser$e: Exception - UseCheckOrError:DistributionHttpClient.kt$DistributionHttpClient$throw IllegalStateException( "Missing required distribution configuration: orgSlug, projectSlug, or orgAuthToken" ) - UseCheckOrError:DistributionHttpClient.kt$DistributionHttpClient$throw IllegalStateException("sentryClientName must be set") - UseCheckOrError:DistributionIntegration.kt$DistributionIntegration$throw IllegalStateException("buildConfiguration must be set in distribution options") - UseRequire:UpdateResponseParser.kt$UpdateResponseParser$throw IllegalArgumentException( "Missing required fields in API response: ${missingFields.joinToString(", ")}" ) WildcardImport:DistributionHttpClientTest.kt$import org.junit.Assert.* diff --git a/sentry-android-distribution/src/main/java/io/sentry/android/distribution/DistributionHttpClient.kt b/sentry-android-distribution/src/main/java/io/sentry/android/distribution/DistributionHttpClient.kt index 9ffaf19949b..9d5e8c1107c 100644 --- a/sentry-android-distribution/src/main/java/io/sentry/android/distribution/DistributionHttpClient.kt +++ b/sentry-android-distribution/src/main/java/io/sentry/android/distribution/DistributionHttpClient.kt @@ -44,16 +44,14 @@ internal class DistributionHttpClient(private val options: SentryOptions) { val authToken = distributionOptions.orgAuthToken val baseUrl = distributionOptions.sentryBaseUrl - if (orgSlug.isNullOrEmpty() || projectSlug.isNullOrEmpty() || authToken.isNullOrEmpty()) { - throw IllegalStateException( - "Missing required distribution configuration: orgSlug, projectSlug, or orgAuthToken" - ) + check(!orgSlug.isNullOrEmpty() && !projectSlug.isNullOrEmpty() && !authToken.isNullOrEmpty()) { + "Missing required distribution configuration: orgSlug, projectSlug, or orgAuthToken" } val urlString = buildString { append(baseUrl.trimEnd('/')) append( - "/api/0/projects/${URLEncoder.encode(orgSlug, "UTF-8")}/${URLEncoder.encode(projectSlug, "UTF-8")}/preprodartifacts/check-for-updates/" + "/api/0/projects/${URLEncoder.encode(orgSlug, "UTF-8")}/${URLEncoder.encode(projectSlug, "UTF-8")}/preprodartifacts/check-for-updates/", ) append("?app_id=${URLEncoder.encode(params.appId, "UTF-8")}") append("&platform=${URLEncoder.encode(params.platform, "UTF-8")}") @@ -85,7 +83,7 @@ internal class DistributionHttpClient(private val options: SentryOptions) { connection.setRequestProperty("Accept", "application/json") connection.setRequestProperty( "User-Agent", - options.sentryClientName ?: throw IllegalStateException("sentryClientName must be set"), + checkNotNull(options.sentryClientName) { "sentryClientName must be set" }, ) connection.connectTimeout = options.connectionTimeoutMillis connection.readTimeout = options.readTimeoutMillis diff --git a/sentry-android-distribution/src/main/java/io/sentry/android/distribution/DistributionIntegration.kt b/sentry-android-distribution/src/main/java/io/sentry/android/distribution/DistributionIntegration.kt index 4a53b557a03..57590bc278d 100644 --- a/sentry-android-distribution/src/main/java/io/sentry/android/distribution/DistributionIntegration.kt +++ b/sentry-android-distribution/src/main/java/io/sentry/android/distribution/DistributionIntegration.kt @@ -142,7 +142,7 @@ public class DistributionIntegration(context: Context) : Integration, IDistribut val buildConfiguration = sentryOptions.distribution.buildConfiguration - ?: throw IllegalStateException("buildConfiguration must be set in distribution options") + ?: error("buildConfiguration must be set in distribution options") DistributionHttpClient.UpdateCheckParams( appId = appId, diff --git a/sentry-android-distribution/src/main/java/io/sentry/android/distribution/UpdateResponseParser.kt b/sentry-android-distribution/src/main/java/io/sentry/android/distribution/UpdateResponseParser.kt index 0734b80f485..8ac1e684d3e 100644 --- a/sentry-android-distribution/src/main/java/io/sentry/android/distribution/UpdateResponseParser.kt +++ b/sentry-android-distribution/src/main/java/io/sentry/android/distribution/UpdateResponseParser.kt @@ -72,10 +72,8 @@ internal class UpdateResponseParser(private val options: SentryOptions) { missingFields.add("downloadUrl") } - if (missingFields.isNotEmpty()) { - throw IllegalArgumentException( - "Missing required fields in API response: ${missingFields.joinToString(", ")}" - ) + require(missingFields.isEmpty()) { + "Missing required fields in API response: ${missingFields.joinToString(", ")}" } return UpdateInfo( diff --git a/sentry-android-distribution/src/test/java/io/sentry/android/distribution/UpdateResponseParserTest.kt b/sentry-android-distribution/src/test/java/io/sentry/android/distribution/UpdateResponseParserTest.kt index f1817a39f34..d3c491ba665 100644 --- a/sentry-android-distribution/src/test/java/io/sentry/android/distribution/UpdateResponseParserTest.kt +++ b/sentry-android-distribution/src/test/java/io/sentry/android/distribution/UpdateResponseParserTest.kt @@ -328,7 +328,7 @@ class UpdateResponseParserTest { assertTrue( "Error message should mention all missing required fields", error.message.contains( - "Missing required fields in API response: id, buildVersion, downloadUrl" + "Missing required fields in API response: id, buildVersion, downloadUrl", ), ) } diff --git a/sentry-android-fragment/build.gradle.kts b/sentry-android-fragment/build.gradle.kts index 713323383af..f83470a4fdc 100644 --- a/sentry-android-fragment/build.gradle.kts +++ b/sentry-android-fragment/build.gradle.kts @@ -54,6 +54,10 @@ android { // We run a full lint analysis as build part in CI, so skip vital checks for assemble tasks. checkReleaseBuilds = false + + // Lint 9.5 can't load the custom checks bundled with older androidx.lifecycle releases and + // reports that it skips them. They only cover lifecycle APIs this module doesn't call. + disable += "ObsoleteLintCustomCheck" } buildFeatures { buildConfig = true } diff --git a/sentry-android-fragment/src/main/java/io/sentry/android/fragment/FragmentLifecycleIntegration.kt b/sentry-android-fragment/src/main/java/io/sentry/android/fragment/FragmentLifecycleIntegration.kt index 8511b514b2e..122644f505f 100644 --- a/sentry-android-fragment/src/main/java/io/sentry/android/fragment/FragmentLifecycleIntegration.kt +++ b/sentry-android-fragment/src/main/java/io/sentry/android/fragment/FragmentLifecycleIntegration.kt @@ -26,7 +26,7 @@ public class FragmentLifecycleIntegration( } public constructor( - application: Application + application: Application, ) : this( application = application, filterFragmentLifecycleBreadcrumbs = FragmentLifecycleState.states, diff --git a/sentry-android-fragment/src/test/java/io/sentry/android/fragment/SentryFragmentLifecycleCallbacksTest.kt b/sentry-android-fragment/src/test/java/io/sentry/android/fragment/SentryFragmentLifecycleCallbacksTest.kt index 997c1206398..ea9ef550af5 100644 --- a/sentry-android-fragment/src/test/java/io/sentry/android/fragment/SentryFragmentLifecycleCallbacksTest.kt +++ b/sentry-android-fragment/src/test/java/io/sentry/android/fragment/SentryFragmentLifecycleCallbacksTest.kt @@ -50,7 +50,7 @@ class SentryFragmentLifecycleCallbacksTest { SentryOptions().apply { setTracesSampleRate(tracesSampleRate) isEnableScreenTracking = enableScreenTracking - } + }, ) whenever(span.spanContext) .thenReturn(SpanContext(SentryId.EMPTY_ID, SpanId.EMPTY_ID, "op", null, null)) diff --git a/sentry-android-integration-tests/sentry-uitest-android-critical/src/main/java/io/sentry/uitest/android/critical/EmptyBroadcastReceiver.kt b/sentry-android-integration-tests/sentry-uitest-android-critical/src/main/java/io/sentry/uitest/android/critical/EmptyBroadcastReceiver.kt index 3aef794189b..cc01e478840 100644 --- a/sentry-android-integration-tests/sentry-uitest-android-critical/src/main/java/io/sentry/uitest/android/critical/EmptyBroadcastReceiver.kt +++ b/sentry-android-integration-tests/sentry-uitest-android-critical/src/main/java/io/sentry/uitest/android/critical/EmptyBroadcastReceiver.kt @@ -14,9 +14,9 @@ class EmptyBroadcastReceiver : BroadcastReceiver() { val pendingResult = goAsync() Log.d(TAG, "onReceive: broadcast received") Thread { - Thread.sleep(1000) - pendingResult.finish() - } + Thread.sleep(1000) + pendingResult.finish() + } .start() } } diff --git a/sentry-android-integration-tests/sentry-uitest-android-critical/src/main/java/io/sentry/uitest/android/critical/MainActivity.kt b/sentry-android-integration-tests/sentry-uitest-android-critical/src/main/java/io/sentry/uitest/android/critical/MainActivity.kt index eab3ace0dd1..c26874c1970 100644 --- a/sentry-android-integration-tests/sentry-uitest-android-critical/src/main/java/io/sentry/uitest/android/critical/MainActivity.kt +++ b/sentry-android-integration-tests/sentry-uitest-android-critical/src/main/java/io/sentry/uitest/android/critical/MainActivity.kt @@ -79,7 +79,7 @@ class MainActivity : ComponentActivity() { .trimIndent() file.writeText(corruptedEnvelopeContent) println("Wrote corrupted envelope to: ${file.absolutePath}") - } + }, ) { Text("Write Corrupted Envelope") } @@ -91,7 +91,7 @@ class MainActivity : ComponentActivity() { } else { postNotification() } - } + }, ) { Text("Trigger Notification") } @@ -102,11 +102,11 @@ class MainActivity : ComponentActivity() { addFlags( Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or - Intent.FLAG_ACTIVITY_SINGLE_TOP + Intent.FLAG_ACTIVITY_SINGLE_TOP, ) - } + }, ) - } + }, ) { Text("Launch Main Activity (singleTask)") } 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 5539cac6944..557a5fab63a 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts +++ b/sentry-android-integration-tests/sentry-uitest-android/build.gradle.kts @@ -77,6 +77,10 @@ android { // This module is the one lint picks to check the build root's Gradle wrapper, and this check // compares it with the latest Gradle release online, so every new release would fail the build. disable += "AndroidGradlePluginVersion" + + // Lint 9.5 can't load the custom checks bundled with older androidx.lifecycle releases and + // reports that it skips them. They only cover lifecycle APIs this module doesn't call. + disable += "ObsoleteLintCustomCheck" } androidComponents.beforeVariants { @@ -108,6 +112,7 @@ dependencies { implementation(libs.androidx.constraintlayout) implementation(libs.androidx.core) implementation(libs.androidx.recyclerview) + implementation(libs.androidx.webkit) implementation(libs.androidx.test.espresso.idling.resource) implementation(libs.leakcanary) @@ -130,11 +135,22 @@ dependencies { androidTestImplementation(libs.okhttp.mockwebserver4) } -tasks.withType().configureEach { - options.errorprone { - check("NullAway", net.ltgt.gradle.errorprone.CheckSeverity.ERROR) - option("NullAway:AnnotatedPackages", "io.sentry") - option("NullAway:UnannotatedSubPackages", "io.sentry.uitest.android.databinding") +// net.ltgt.errorprone only configures Gradle's JVM source sets, not Android variants, so put Error +// Prone on each variant's processor path and enable it ourselves. +androidComponents.onVariants { variant -> + variant.annotationProcessorConfiguration.extendsFrom(configurations.errorprone.get()) + variant.configureJavaCompileTask { task -> + // Tells Error Prone this is Android code, so it skips checks that don't apply there, such as + // DefaultCharset (Android's default charset is always UTF-8), and runs its Android checks. + task.options.compilerArgs.add("-XDandroidCompatible=true") + task.options.errorprone { + enabled = true + check("NullAway", net.ltgt.gradle.errorprone.CheckSeverity.ERROR) + option("NullAway:AnnotatedPackages", "io.sentry") + option("NullAway:UnannotatedSubPackages", "io.sentry.uitest.android.databinding") + // AGP generates the view binding classes, so their findings can't be fixed here. + excludedPaths.set(".*/build/generated/.*") + } } } diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/AutomaticSpansTest.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/AutomaticSpansTest.kt index db9a138d797..635ebf5a6c9 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/AutomaticSpansTest.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/AutomaticSpansTest.kt @@ -70,9 +70,9 @@ class AutomaticSpansTest : BaseUiTest() { relay.assert { findEnvelope { - assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == - "ProfilingSampleActivity" - } + assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == + "ProfilingSampleActivity" + } .assert { val transactionItem: SentryTransaction = it.assertTransaction() it.assertNoOtherItems() diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/EnvelopeTests.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/EnvelopeTests.kt index 1d77c95663a..f036bbbbe0f 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/EnvelopeTests.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/EnvelopeTests.kt @@ -62,9 +62,9 @@ class EnvelopeTests : BaseUiTest() { transaction.finish() relay.assert { findEnvelope { - assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == - "ProfilingSampleActivity" - } + assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == + "ProfilingSampleActivity" + } .assert { val transactionItem: SentryTransaction = it.assertTransaction() it.assertNoOtherItems() @@ -72,8 +72,8 @@ class EnvelopeTests : BaseUiTest() { } findEnvelope { - assertEnvelopeProfile(it.items.toList()).transactionName == "profiledTransaction" - } + assertEnvelopeProfile(it.items.toList()).transactionName == "profiledTransaction" + } .assert { val transactionItem: SentryTransaction = it.assertTransaction() val profilingTraceData: ProfilingTraceData = it.assertProfile() @@ -234,7 +234,7 @@ class EnvelopeTests : BaseUiTest() { {"type":"transaction","length":1335} {"event_id":"729ff878-5539-458d-f657-a1acf423a127","platform":"native","transaction":"little.teapot","start_timestamp":"2025-04-02T10:02:04.731697Z","spans":[{"op":"littlest.teapot","span_id":"00028ba394454124","status":"ok","trace_id":"7160e289fe4c4496f02c72bbc7edb392","parent_span_id":"b0dc1649a8ec4101","description":null,"start_timestamp":"2025-04-02T10:02:04.732127Z","timestamp":"2025-04-02T10:02:04.732133Z"},{"op":"littler.teapot","span_id":"b0dc1649a8ec4101","status":"ok","trace_id":"7160e289fe4c4496f02c72bbc7edb392","parent_span_id":"7ad2e40529af4650","description":null,"start_timestamp":"2025-04-02T10:02:04.732118Z","data":{"span_data_says":"hi!"},"timestamp":"2025-04-02T10:02:04.732137Z"}],"type":"transaction","timestamp":"2025-04-02T10:02:04.732142Z","level":"info","contexts":{"trace":{"trace_id":"7160e289fe4c4496f02c72bbc7edb392","span_id":"7ad2e40529af4650","op":"Short and stout here is my handle and here is my spout","status":"ok","data":{"url":"https://example.com"}},"os":{"build":"android14-4-00257-g7e35917775b8-ab9964412","name":"Linux","version":"6.1.23"}},"release":"1.0.0","dist":"dist","environment":"production","sdk":{"name":"io.sentry.ndk","version":"0.8.3","packages":[{"name":"github:getsentry/sentry-native","version":"0.8.3"}],"integrations":["inproc"]},"tags":{},"extra":{},"breadcrumbs":[]} """ - .trimIndent() + .trimIndent(), ) relayIdlingResource.increment() 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 86f30dc1a1a..f7203549c4c 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 @@ -37,7 +37,7 @@ class ReplayTest : BaseUiTest() { ReferencePattern.InstanceFieldPattern( "com.saucelabs.rdcinjector.testfairy.TestFairyEventQueue", "context", - ) + ), ), // Seems like a false-positive returned by LeakCanary when curtains is used in // the host application (LeakCanary uses it itself internally). We use kind of @@ -49,7 +49,7 @@ class ReplayTest : BaseUiTest() { ReferencePattern.InstanceFieldPattern( "curtains.internal.RootViewsSpy", "delegatingViewList", - ) + ), ), ) + ('a'..'z').map { char -> @@ -57,9 +57,9 @@ class ReplayTest : BaseUiTest() { ReferencePattern.StaticFieldPattern( "com.testfairy.modules.capture.TouchListener", "$char", - ) + ), ) - } + }, ) val activityScenario = launchActivity() diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/SdkInitTests.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/SdkInitTests.kt index d3a60d2c198..6f71f15aeda 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/SdkInitTests.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/SdkInitTests.kt @@ -75,8 +75,8 @@ class SdkInitTests : BaseUiTest() { relay.assert { findEnvelope { - assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == "e2etests" - } + assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == "e2etests" + } .assert { val transactionItem: SentryTransaction = it.assertTransaction() it.assertNoOtherItems() @@ -84,9 +84,8 @@ class SdkInitTests : BaseUiTest() { } findEnvelope { - assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == - "EmptyActivity" - } + assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == "EmptyActivity" + } .assert { val transactionItem: SentryTransaction = it.assertTransaction() // Transaction-based Profiling is already in e2etests transaction, so it won't run again @@ -96,8 +95,8 @@ class SdkInitTests : BaseUiTest() { } findEnvelope { - assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == "e2etests2" - } + assertEnvelopeTransaction(it.items.toList(), AndroidLogger()).transaction == "e2etests2" + } .assert { val transactionItem: SentryTransaction = it.assertTransaction() // Profiling uses executorService, so if the executorService is shutdown it would fail @@ -186,17 +185,17 @@ class SdkInitTests : BaseUiTest() { ReferencePattern.InstanceFieldPattern( "com.saucelabs.rdcinjector.testfairy.TestFairyEventQueue", "context", - ) - ) + ), + ), ) + ('a'..'z').map { char -> IgnoredReferenceMatcher( ReferencePattern.StaticFieldPattern( "com.testfairy.modules.capture.TouchListener", "$char", - ) + ), ) - } + }, ) val activityScenario = launchActivity() @@ -237,12 +236,12 @@ class SdkInitTests : BaseUiTest() { // so we need to set the current activity manually CurrentActivityHolder.getInstance().setActivity(activity) Thread { - initSentry(false) { options: SentryAndroidOptions -> - options.tracesSampleRate = 1.0 - options.profilesSampleRate = 1.0 - } - initLatch.countDown() + initSentry(false) { options: SentryAndroidOptions -> + options.tracesSampleRate = 1.0 + options.profilesSampleRate = 1.0 } + initLatch.countDown() + } .start() } initLatch.await() diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/UserFeedbackUiTest.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/UserFeedbackUiTest.kt index 1569d97e41f..0b27499cf82 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/UserFeedbackUiTest.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/UserFeedbackUiTest.kt @@ -422,7 +422,7 @@ class UserFeedbackUiTest : BaseUiTest() { name = "Test User" username = "Test UserName" email = "Test User Email" - } + }, ) showDialogAndCheck { // Name and email are filled with Sentry user properties @@ -446,7 +446,7 @@ class UserFeedbackUiTest : BaseUiTest() { name = "Test User" username = "Test UserName" email = "Test User Email" - } + }, ) showDialogAndCheck { // Name and email are not filled @@ -484,9 +484,9 @@ class UserFeedbackUiTest : BaseUiTest() { relay.assert { findEnvelope { - assertEnvelopeFeedback(it.items.toList(), AndroidLogger()).contexts.feedback!!.message == - "Description filled" - } + assertEnvelopeFeedback(it.items.toList(), AndroidLogger()).contexts.feedback!!.message == + "Description filled" + } .assert { val event: SentryEvent = it.assertItem() val feedback = event.contexts.feedback!! diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/UserInteractionTests.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/UserInteractionTests.kt index 2ea1905b761..2327fb16a5d 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/UserInteractionTests.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/UserInteractionTests.kt @@ -53,13 +53,13 @@ class UserInteractionTests : BaseUiTest() { Press.FINGER, InputDevice.SOURCE_UNKNOWN, MotionEvent.BUTTON_PRIMARY, - ) + ), ) activity.moveToState(Lifecycle.State.DESTROYED) assertTrue( breadcrumbs .filter { it.category == "ui.click" && it.data["view.tag"] == "button_login" } - .size == 1 + .size == 1, ) } @@ -77,7 +77,7 @@ class UserInteractionTests : BaseUiTest() { .filter { it.category == "ui.swipe" && it.data["view.tag"] == "list" && it.data["direction"] == "up" } - .size == 1 + .size == 1, ) } diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/WebViewTracePropagationTest.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/WebViewTracePropagationTest.kt new file mode 100644 index 00000000000..1d95819ddf4 --- /dev/null +++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/WebViewTracePropagationTest.kt @@ -0,0 +1,45 @@ +package io.sentry.uitest.android + +import androidx.lifecycle.Lifecycle +import androidx.test.core.app.launchActivity +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.webkit.WebViewFeature +import java.util.concurrent.TimeUnit +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import org.awaitility.kotlin.await +import org.junit.Assume.assumeTrue +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class WebViewTracePropagationTest : BaseUiTest() { + + @Test + fun injectsTheTraceBeforePageScriptsAndOnlyIntoTheMainFrame() { + assumeTrue( + "The System WebView does not support document-start scripts", + WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT), + ) + initSentry { it.tracesSampleRate = 1.0 } + + val scenario = launchActivity() + scenario.moveToState(Lifecycle.State.RESUMED) + + var activity: WebViewTraceActivity? = null + scenario.onActivity { activity = it } + val webViewActivity = assertNotNull(activity) + await.atMost(30, TimeUnit.SECONDS).until { + webViewActivity.pageTrace != null && webViewActivity.iframeInjected != null + } + + assertTrue(webViewActivity.installed) + assertNotNull(webViewActivity.nativeTrace) + // Read by the page's first synchronous script: present, so there is no race. + assertEquals(webViewActivity.nativeTrace, webViewActivity.pageTrace) + assertFalse(webViewActivity.iframeInjected!!) + scenario.close() + } +} diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/mockservers/RelayAsserter.kt b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/mockservers/RelayAsserter.kt index a449be66ae4..4d0ad2ab55b 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/mockservers/RelayAsserter.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/androidTest/java/io/sentry/uitest/android/mockservers/RelayAsserter.kt @@ -37,7 +37,7 @@ class RelayAsserter(private val unassertedEnvelopes: MutableList) throw AssertionError( "No envelope request found with specified filter.\n" + "There was a total of ${originalUnassertedEnvelopes.size} envelopes: " + - originalUnassertedEnvelopes.joinToString { it.envelope!!.describeForTest() } + originalUnassertedEnvelopes.joinToString { it.envelope!!.describeForTest() }, ) } return unassertedEnvelopes.removeAt(relayResponseIndex) @@ -48,7 +48,7 @@ class RelayAsserter(private val unassertedEnvelopes: MutableList) if (unassertedEnvelopes.isNotEmpty()) { throw AssertionError( "There was a total of ${originalUnassertedEnvelopes.size} envelopes: " + - originalUnassertedEnvelopes.joinToString { it.envelope!!.describeForTest() } + originalUnassertedEnvelopes.joinToString { it.envelope!!.describeForTest() }, ) } } diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml b/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml index 0b676446a85..1b7f8f0108f 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml +++ b/sentry-android-integration-tests/sentry-uitest-android/src/main/AndroidManifest.xml @@ -14,6 +14,7 @@ + diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/main/assets/webview/iframe.html b/sentry-android-integration-tests/sentry-uitest-android/src/main/assets/webview/iframe.html new file mode 100644 index 00000000000..05f42a95bbb --- /dev/null +++ b/sentry-android-integration-tests/sentry-uitest-android/src/main/assets/webview/iframe.html @@ -0,0 +1,15 @@ + + + + + + + + + + diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/main/assets/webview/index.html b/sentry-android-integration-tests/sentry-uitest-android/src/main/assets/webview/index.html new file mode 100644 index 00000000000..ddccd20a972 --- /dev/null +++ b/sentry-android-integration-tests/sentry-uitest-android/src/main/assets/webview/index.html @@ -0,0 +1,16 @@ + + + + + + + + + + + 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 c54af11f6d2..fd0ff09f4bc 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 @@ -39,7 +39,7 @@ class ComposeActivity : AppCompatActivity() { .clickable { // no-op } - .testTag("button_login") + .testTag("button_login"), ) { Text("Login") } diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/ProfilingSampleActivity.kt b/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/ProfilingSampleActivity.kt index 1ac1590e78a..f1de54efd9c 100644 --- a/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/ProfilingSampleActivity.kt +++ b/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/ProfilingSampleActivity.kt @@ -50,7 +50,7 @@ class ProfilingSampleActivity : AppCompatActivity() { scrollingIdlingResource.decrement() } } - } + }, ) } } diff --git a/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/WebViewTraceActivity.kt b/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/WebViewTraceActivity.kt new file mode 100644 index 00000000000..d0a9abee52c --- /dev/null +++ b/sentry-android-integration-tests/sentry-uitest-android/src/main/java/io/sentry/uitest/android/WebViewTraceActivity.kt @@ -0,0 +1,66 @@ +package io.sentry.uitest.android + +import android.annotation.SuppressLint +import android.os.Bundle +import android.webkit.JavascriptInterface +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.appcompat.app.AppCompatActivity +import androidx.webkit.WebViewAssetLoader +import io.sentry.Sentry +import io.sentry.android.core.SentryWebViewTracing + +/** Loads a bundled page with WebView trace propagation and records what the page received. */ +class WebViewTraceActivity : AppCompatActivity() { + + /** The trace the app injected. */ + @Volatile var nativeTrace: String? = null + + /** Whether addTracePropagation installed its script. */ + @Volatile var installed: Boolean = false + + /** The sentry-trace meta tag seen by the page's first synchronous script, empty if missing. */ + @Volatile var pageTrace: String? = null + + /** Whether the iframe on the page saw a sentry-trace meta tag. */ + @Volatile var iframeInjected: Boolean? = null + + @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val webView = WebView(this) + setContentView(webView) + + val assetLoader = + WebViewAssetLoader.Builder() + .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this)) + .build() + webView.webViewClient = + object : WebViewClient() { + override fun shouldInterceptRequest( + view: WebView, + request: WebResourceRequest, + ): WebResourceResponse? = assetLoader.shouldInterceptRequest(request.url) + } + webView.settings.javaScriptEnabled = true + webView.addJavascriptInterface(PageBridge(), "SentryTest") + + nativeTrace = Sentry.getTraceparent()?.value + installed = SentryWebViewTracing.addTracePropagation(webView, WebViewAssetLoader.DEFAULT_DOMAIN) + webView.loadUrl("https://${WebViewAssetLoader.DEFAULT_DOMAIN}/assets/webview/index.html") + } + + private inner class PageBridge { + @JavascriptInterface + fun onPageTrace(trace: String) { + pageTrace = trace + } + + @JavascriptInterface + fun onIframeTrace(injected: Boolean) { + iframeInjected = injected + } + } +} diff --git a/sentry-android-navigation/build.gradle.kts b/sentry-android-navigation/build.gradle.kts index ca02d462a70..a9e75743b05 100644 --- a/sentry-android-navigation/build.gradle.kts +++ b/sentry-android-navigation/build.gradle.kts @@ -11,6 +11,7 @@ plugins { id("io.sentry.jdk-target") id("io.sentry.publish") id("io.sentry.api-validation") + id("io.sentry.robolectric") } android { @@ -54,6 +55,10 @@ android { // We run a full lint analysis as build part in CI, so skip vital checks for assemble tasks. checkReleaseBuilds = false + + // Lint 9.5 can't load the custom checks bundled with older androidx.lifecycle releases and + // reports that it skips them. They only cover lifecycle APIs this module doesn't call. + disable += "ObsoleteLintCustomCheck" } buildFeatures { buildConfig = true } diff --git a/sentry-android-navigation3/build.gradle.kts b/sentry-android-navigation3/build.gradle.kts index 0e348e15eda..9478825b347 100644 --- a/sentry-android-navigation3/build.gradle.kts +++ b/sentry-android-navigation3/build.gradle.kts @@ -12,6 +12,7 @@ plugins { id("io.sentry.jdk-target") id("io.sentry.publish") id("io.sentry.api-validation") + id("io.sentry.robolectric") } android { @@ -39,13 +40,22 @@ android { } testOptions { - unitTests.isReturnDefaultValues = true + unitTests.apply { + isReturnDefaultValues = true + // AGP 9.5 can't create the Compose Preview task without it, which breaks any + // build that creates every task, such as an LSP's Gradle import. + isIncludeAndroidResources = true + } } lint { warningsAsErrors = true checkDependencies = true + // Lifecycle 2.8.3's lint checks are incompatible with AGP 9.5. Lifecycle 2.10.0 fixes them, + // but raises minSdk to 23 while this SDK still supports 21. + disable += "ObsoleteLintCustomCheck" + // We run a full lint analysis as build part in CI, so skip vital checks for assemble tasks. checkReleaseBuilds = false } @@ -67,7 +77,10 @@ dependencies { implementation(libs.androidx.lifecycle.runtime.compose) compileOnly(libs.androidx.compose.runtime) + compileOnly(libs.androidx.compose.ui) + testImplementation(projects.sentryAndroidCore) + testImplementation(projects.sentryTestSupport) testImplementation(libs.androidx.compose.ui.test.junit4) testImplementation(libs.androidx.fragment.ktx) testImplementation(libs.androidx.test.core) 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 d26336d1066..924f8c49728 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 @@ -165,7 +165,7 @@ public fun interface BackStackEntryMapper { * logic or recreating its own state whenever the mapper changed. */ internal class ForwardingBackStackEntryMapper( - private val currentMapper: () -> BackStackEntryMapper + private val currentMapper: () -> BackStackEntryMapper, ) { fun map(backStackEntry: T): SentryBackStackEntry? = Snapshot.withoutReadObservation { currentMapper().map(backStackEntry) diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt index 2c4fd1fb14d..d3e92777ce3 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/BackStackObserver.kt @@ -5,23 +5,18 @@ import io.sentry.Hint import io.sentry.SentryIntegrationPackageStorage import io.sentry.SentryLevel.INFO import io.sentry.SentryOptions -import io.sentry.TransactionContext -import io.sentry.TransactionOptions import io.sentry.compose.navigation3.BackStackConverter.RetentionPolicy import io.sentry.compose.navigation3.PreparedChange.BackStackHasNewTop import io.sentry.compose.navigation3.PreparedChange.BackStackHasSameTop import io.sentry.compose.navigation3.PreparedChange.BackStackIsEmpty import io.sentry.compose.navigation3.lifecycle.INavScope import io.sentry.compose.navigation3.lifecycle.INavScopes -import io.sentry.compose.navigation3.lifecycle.INavTransaction import io.sentry.compose.navigation3.lifecycle.NAVIGATION_CONTEXT_KEY -import io.sentry.protocol.App -import io.sentry.protocol.TransactionNameSource +import io.sentry.compose.navigation3.lifecycle.NAVIGATION_OP +import io.sentry.compose.navigation3.lifecycle.NavTransactionRequest import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion import java.lang.ref.WeakReference -private const val NAVIGATION_OP: String = "navigation" - /** * Observes the back stack managed by a single [SentryNavEffect] and records Sentry state as the * back stack is updated. @@ -33,8 +28,8 @@ private const val NAVIGATION_OP: String = "navigation" * * **Entry identity determines whether the top has changed** * - * Referential equality (===), not structural equality, is used to determine whether the top of the - * incoming back stack has changed. That approach: + * Referential equality (===) is used to determine whether the top of the incoming back stack has + * changed. That approach: * * - matches the typical Nav3 SnapshotStateList, where an entry instance has a stable identity for * its lifetime in the stack; @@ -57,10 +52,9 @@ internal class BackStackObserver( private val backStackConverter = BackStackConverter(entryMapper, scopes.options.logger) - private val navTransactions = NavTransactions(scopes) private val navBreadcrumbs = NavBreadcrumbs(scopes) private val navScreen = NavScreen() - private val navContext = NavContext(scopes, options) + private val navContext = NavContext(options) // Safe because the host back stack retains the current top entry strongly between updates. private var previousTop: WeakReference? = null @@ -192,35 +186,36 @@ internal class BackStackObserver( navBreadcrumbs.emit(fromEntry = previousTop, toEntry = currentBackStack.topEntryNormalized) } - navTransactions.stop(scope) + scope.finishNavTransaction() if (areNavigationTransactionsEnabled) { - navTransactions - .start( - scope, - currentTop.name, - currentTop.argumentsWithMetadata(), - ) - ?.let { transaction -> navContext.updateTransaction(transaction, scope, currentBackStack) } + scope.startNavTransaction(navTransactionRequestFor(currentBackStack)) } else { scope.rotatePropagationContext() } - storeAsPreviousTop(currentBackStack.topEntry, currentBackStack.topEntryNormalized) + storePreviousTop(currentBackStack) } private fun handleSameTop(scope: INavScope, backStack: BackStackData) { navContext.update(scope, backStack.capturedEntriesNormalized) - storeAsPreviousTop(backStack.topEntry, backStack.topEntryNormalized) + + // Keeps the nav context of transactions started later for the same destination (e.g., when the + // user returns to the nav root) in step with the back stack. + if (areNavigationTransactionsEnabled) { + scope.updateNavTransactionRequest(navTransactionRequestFor(backStack)) + } + + storePreviousTop(backStack) } private fun handleEmptyBackStack(scope: INavScope) { tearDown(scope) } - private fun storeAsPreviousTop(topEntry: T, topEntryNormalized: NormalizedSentryBackStackEntry) { - previousTop = WeakReference(topEntry) - previousTopNormalized = topEntryNormalized + private fun storePreviousTop(backStack: BackStackData) { + previousTop = WeakReference(backStack.topEntry) + previousTopNormalized = backStack.topEntryNormalized } private fun clearPreviousTop() { @@ -228,8 +223,20 @@ internal class BackStackObserver( previousTopNormalized = null } + private fun navTransactionRequestFor(backStack: BackStackData): NavTransactionRequest { + val top = backStack.topEntryNormalized + + return NavTransactionRequest.forDestination( + name = top.name, + arguments = top.argumentsWithMetadata(), + contexts = navContext.forTransaction(backStack.capturedEntriesNormalized), + viewNames = if (scopes.options.isEnableScreenTracking) listOf(top.name) else null, + options = scopes.options, + ) + } + private fun tearDown(scope: INavScope) { - navTransactions.stop(scope) + scope.finishNavTransaction() navContext.clear(scope) navScreen.clear(scope) clearPreviousTop() @@ -274,58 +281,8 @@ private data class BackStackData( val capturedEntriesNormalized: List, ) -/** A helper class for managing nav transactions. */ -private class NavTransactions(private val scopes: INavScopes) { - - private companion object { - private const val TRANSACTION_ORIGIN = "auto.navigation.nav3" - } - - /** - * Starts an idle navigation transaction, or no-ops if another transaction is already active. - * - * [Stop][stop] the current navigation transaction first. See [INavScope.startNavTransaction]. - */ - fun start( - scope: INavScope, - name: String, - arguments: Map, - ): INavTransaction? { - val transactionOptions = - TransactionOptions().also { - it.isWaitForChildren = true - it.idleTimeout = scopes.options.idleTimeout - val deadlineTimeoutMillis = scopes.options.deadlineTimeout - it.deadlineTimeout = if (deadlineTimeoutMillis <= 0) null else deadlineTimeoutMillis - it.isTrimEnd = true - it.origin = TRANSACTION_ORIGIN - } - - val transaction = - scope.startNavTransaction( - TransactionContext(name, TransactionNameSource.ROUTE, NAVIGATION_OP), - transactionOptions, - ) ?: return null - - if (arguments.isNotEmpty()) { - transaction.setData("arguments", arguments) - } - - return transaction - } - - /** - * Finishes and unsets the active navigation transaction, if one exists. - * - * See [INavScope.finishNavTransaction]. - */ - fun stop(scope: INavScope) { - scope.finishNavTransaction() - } -} - /** A helper class for updating [nav context][NAVIGATION_CONTEXT_KEY]. */ -private class NavContext(private val scopes: INavScopes, private val options: SentryNavOptions) { +private class NavContext(private val options: SentryNavOptions) { private companion object { private const val BACKSTACK_KEY = "Back Stack" @@ -345,33 +302,21 @@ private class NavContext(private val scopes: INavScopes, private val options: Se } /** - * Updates the transaction with the provided navigation info. + * The nav context to set on the nav transaction for a destination whose back stack is + * [capturedEntries], if any. * * Needed because transactions inherit base scope context on a per-key basis unless transactions - * have their own values for those keys. In our case, we need to keep fresh back stack and route - * values in the base context for purposes of crash reporting. But those values will often advance - * past what's relevant to a given transaction. This method prevents misassociation by binding - * proper values to the transaction context instead. + * have their own values for those keys. In our case, we need to keep fresh back stack values in + * the base context for purposes of crash reporting. But those values will often advance past + * what's relevant to a given transaction. Setting the destination's own back stack on its + * transaction prevents misassociation. */ - fun updateTransaction( - transaction: INavTransaction, - scope: INavScope, - backStack: BackStackData, - ) { - if (scopes.options.isEnableScreenTracking) { - val appContext = scope.app ?: App() - - appContext.viewNames = listOf(backStack.topEntryNormalized.name) - transaction.setApp(appContext) - } - - if (options.captureBackStack && backStack.capturedEntriesNormalized.isNotEmpty()) { - transaction.setContext( - NAVIGATION_CONTEXT_KEY, - backStack.capturedEntriesNormalized.toBackStackMap(), - ) + fun forTransaction(capturedEntries: List): Map = + if (options.captureBackStack && capturedEntries.isNotEmpty()) { + mapOf(NAVIGATION_CONTEXT_KEY to capturedEntries.toBackStackMap()) + } else { + emptyMap() } - } /** Builds the `{"backstack": [...]}` map bound under [NAVIGATION_CONTEXT_KEY]. */ private fun List.toBackStackMap(): Map = diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserver.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserver.kt index a34a214decc..a01e658e938 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserver.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserver.kt @@ -1,15 +1,15 @@ package io.sentry.compose.navigation3 -import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import io.sentry.IScope import io.sentry.IScopes import io.sentry.compose.navigation3.lifecycle.NavLeaseCoordinator +import io.sentry.compose.navigation3.lifecycle.NavRootInfo import io.sentry.compose.navigation3.lifecycle.NavScopes /** - * A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with other - * `BackStackObserver`s. + * A [BackStackObserver] whose updates to a shared mutable [IScope] are coordinated with those of + * other `BackStackObserver`s. * * Coordination is achieved via [NavScopes]. * @@ -35,8 +35,8 @@ internal class CoordinatedBackStackObserver( private val navScopes = NavScopes(scopes, coordinator) private val observer = BackStackObserver(navScopes, options, entryMapper) - fun attach(lifecycle: Lifecycle) { - navScopes.attach(lifecycle) + fun attach(rootInfo: NavRootInfo) { + navScopes.attach(rootInfo) } fun onBackStackChanged(backStack: List) { @@ -52,5 +52,24 @@ internal class CoordinatedBackStackObserver( } } -/** The [NavLeaseCoordinator] shared by default by all [SentryNavEffect]s. */ +/** + * 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/SentryNavEffect.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt index c666122efc7..41e2bda95cb 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/SentryNavEffect.kt @@ -4,17 +4,19 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.compose.LocalLifecycleOwner import io.sentry.IScopes import io.sentry.ScopesAdapter import io.sentry.SentryOptions import io.sentry.compose.navigation3.lifecycle.NavLeaseCoordinator +import io.sentry.compose.navigation3.lifecycle.NavRootInfo +import io.sentry.compose.navigation3.lifecycle.findActivity import org.jetbrains.annotations.ApiStatus /** - * An effect for generating Sentry data from your Nav3 backstack. Configure it via [options] and - * call it before you invoke your `NavDisplay`. - * + * A composable effect for generating Sentry data from your Nav3 backstack. Configure it via + * [options] and call it before you invoke your `NavDisplay`: * ```kotlin * @Composable * fun AppNavigation() { @@ -24,7 +26,7 @@ import org.jetbrains.annotations.ApiStatus * // Place SentryNavEffect in the same composable as your NavDisplay and call * // the effect first. Doing so ensures the effect's lifecycle matches your * // NavDisplay, and that any Sentry data produced by your initial nav - * // destination get attributed to the appropriate nav transaction. + * // destination are attributed to the appropriate nav transaction. * SentryNavEffect( * backStack = navBackStack, * backStackEntryMapper = { entry -> @@ -105,6 +107,7 @@ internal fun SentryNavEffect( ) { val currentBackStackEntryMapper = rememberUpdatedState(backStackEntryMapper) val lifecycle = LocalLifecycleOwner.current.lifecycle + val context = LocalContext.current val observer = remember(scopes, options, lifecycle, coordinator) { @@ -116,9 +119,13 @@ internal fun SentryNavEffect( ) } - // Register first so the initial prepared back stack update can acquire navigation ownership. + // Intentionally don't key on context. It's only used to find the Activity that displays the nav + // root, which can't change without the lifecycle changing too, and that replaces the observer. + // The context's identity can change more often (e.g., if the host app provides a new + // ContextThemeWrapper on every recomposition), and re-attaching for those changes would + // needlessly finish the nav transaction. DisposableEffect(observer) { - observer.attach(lifecycle) + observer.attach(NavRootInfo(lifecycle, context.findActivity())) onDispose { observer.dispose() } } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavActivityWatcher.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavActivityWatcher.kt new file mode 100644 index 00000000000..3c949384f57 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavActivityWatcher.kt @@ -0,0 +1,111 @@ +package io.sentry.compose.navigation3.lifecycle + +import android.app.Activity +import android.app.Application +import android.app.Application.ActivityLifecycleCallbacks +import android.os.Build +import android.os.Bundle + +/** + * Watches every Activity of the host application and reports the Activity lifecycle events that + * [NavLeaseCoordinator] acts on, so that the coordinator needn't know how they differ across API + * levels. + * + * Each event is reported relative to `ActivityLifecycleIntegration`, which binds an Activity's + * `ui.load` transaction to the scope when the Activity is created and removes it when the Activity + * is destroyed: + * + * - [onActivityCreatedOrResumed] is called when an Activity is created and again when it resumes, + * with [ActivityEvent.CREATED] or [ActivityEvent.RESUMED] as its event. On API 29+, creation is + * reported before `ActivityLifecycleIntegration` tries to bind the Activity's `ui.load` + * transaction; below API 29, after. So below API 29, a withdrawal on creation comes too late for + * that `ui.load` transaction, which stays unbound (see "Non-candidate roots and lease withdrawal" + * in the package README). + * + * - [onActivityDestroyed] is called when an Activity is destroyed, after + * `ActivityLifecycleIntegration` has removed the Activity's `ui.load` transaction from the scope. + * + * **Android ordering assumptions** + * + * The watcher relies on the following callback orders, which Android doesn't document but AOSP has + * historically upheld: + * + * - `Application` calls `ActivityLifecycleCallbacks` in registration order. Below API 29, + * `ActivityLifecycleIntegration`'s callbacks run before this class's, provided the SDK is + * initialized before this class starts [watching][watch]. + * + * - On API 29+, every `onActivityPreCreated` callback runs before any `onActivityCreated` callback, + * and every `onActivityDestroyed` callback before any `onActivityPostDestroyed` callback. + * + * **Lifetime** + * + * The callbacks are registered at most once per watcher and never unregistered. Like + * `defaultNavLeaseCoordinator`, which owns the watcher used in practice, they're meant to live as + * long as the process. + */ +internal class NavActivityWatcher( + private val onActivityCreatedOrResumed: (activity: Activity, event: ActivityEvent) -> Unit, + private val onActivityDestroyed: (activity: Activity) -> Unit, +) { + + /** + * The Activity lifecycle event passed to [onActivityCreatedOrResumed], described by [description] + * in past tense (e.g., "created") for log messages. + */ + enum class ActivityEvent(val description: String) { + CREATED("created"), + RESUMED("resumed"), + } + + private var isWatching = false + + /** Starts watching the Activities of [application]. Does nothing if already watching. */ + fun watch(application: Application) { + if (isWatching) { + return + } + isWatching = true + application.registerActivityLifecycleCallbacks(Callbacks()) + } + + private inner class Callbacks : ActivityLifecycleCallbacks { + + // Only called on API 29+, before any callback's onActivityCreated. + override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) { + onActivityCreatedOrResumed(activity, ActivityEvent.CREATED) + } + + // Covers API levels below 29, as they don't call onActivityPreCreated. Runs after + // ActivityLifecycleIntegration's onActivityCreated, which finds the slot taken and never binds + // the Activity's ui.load transaction. This is a known limitation (see the package README). + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + onActivityCreatedOrResumed(activity, ActivityEvent.CREATED) + } + } + + override fun onActivityResumed(activity: Activity) { + onActivityCreatedOrResumed(activity, ActivityEvent.RESUMED) + } + + override fun onActivityStarted(activity: Activity) = Unit + + override fun onActivityPaused(activity: Activity) = Unit + + override fun onActivityStopped(activity: Activity) = Unit + + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit + + // Covers API levels below 29, which don't call onActivityPostDestroyed. + override fun onActivityDestroyed(activity: Activity) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + this@NavActivityWatcher.onActivityDestroyed(activity) + } + } + + // Only called on API 29+, after every callback's onActivityDestroyed. + override fun onActivityPostDestroyed(activity: Activity) { + this@NavActivityWatcher.onActivityDestroyed(activity) + } + } +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavLeaseCoordinator.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavLeaseCoordinator.kt index 15e3706ad4c..2049b07ecce 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavLeaseCoordinator.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavLeaseCoordinator.kt @@ -1,5 +1,6 @@ package io.sentry.compose.navigation3.lifecycle +import android.app.Activity import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle.Event.ON_DESTROY import androidx.lifecycle.Lifecycle.Event.ON_PAUSE @@ -10,347 +11,279 @@ import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import io.sentry.IScope import io.sentry.IScopes +import io.sentry.SentryLevel +import java.lang.ref.WeakReference /** * Manages a lease in order to determine which [NavScopes] instance can bind nav transactions and * publish nav data to a shared [IScope]. * - * `NavScopes` instances register as [candidates][Candidate] for lease ownership via [register]. - * Each candidate observes its owner's lifecycle until it's disposed. + * `NavScopes` instances register as [candidates][Candidate] for lease ownership via [register], + * each on behalf of its [nav root][NavRootInfo]. Each candidate observes its nav root's lifecycle + * until it's disposed. * - * Note: "Owner" below refers to the `LifecycleOwner` whose lifecycle the candidate observes. - * - * **A fundamental tradeoff** - * - * During `LifecycleOwner` overlap, the nav transaction and scoped nav data can reflect - * **_either_**: - * - * 1. the outgoing owner that's still visible, or - * 2. the incoming owner that may crash before it becomes visible, - * - * but not both. This class opts for (2) so that the incoming destination populates crash context - * and any work performed is associated with it† – the idea being that start-up logic is more likely - * to cause a crash or produce interesting spans than an outgoing destination's steady state. - * - * † Associating work with the incoming transaction means spans produced by the outgoing owner may - * appear as if they were produced by the incoming owner (or vice versa, were our policy reversed). - * - * **Lease handoff policy** - * - * The lease is acquired preemptively by an incoming owner's `NavScopes` instance when it applies - * its first [back stack update][onBackStackUpdate].† - * - * A displaced owner remains eligible for lease restoration until it - * [stops][Lifecycle.Event.ON_STOP]. It gets the lease back when it - * [resumes][Lifecycle.Event.ON_RESUME], or sooner if the new owner leaves or pauses while the - * displaced owner is still visible. If restored, the displaced owner's nav data and unfinished - * transaction are reinstated. - * - * † There are some exceptions, e.g., the leaseholder is resumed and the incoming owner isn't (e.g., - * a preloaded ViewPager2 Fragment page next to the current one). Such an owner acquires the lease - * when it resumes instead. - * - * The following diagram illustrates how handoff works: - * ``` - * Time - * │ - * ▼ - * - * NavScopes A + Lifecycle A Shared state NavScopes B + Lifecycle B - * ───────────────────────── ──────────── ───────────────────────── - * - * attach() Navigation lease: none - * │ - * Initial back stack update - * │ - * ├── acquire lease ────────► Navigation lease: A - * ├── create & bind txA ────► Scope transaction: txA - * ├── publish nav data ─────► Published data: A - * │ - * ON_RESUME A is eligible for restoration - * │ - * ON_PAUSE - * │ - * ├────────────────────────► Navigation lease: A (no other resumed owner) - * │ A remains eligible for restoration - * │ - * │ attach() - * │ │ - * │ Navigation lease: A ◄────────────────────┤ - * │ Scope transaction: txA │ - * │ Published data: A │ - * │ B registered, awaiting initial back │ - * │ stack update │ - * │ │ - * │ Initial back stack update - * │ │ - * │ Suspend & unbind txA ◄───────────────────┤ - * │ Navigation lease: B │ - * │ Published data: B │ - * │ Scope transaction: txB │ - * │ (rollback point) │ - * │ │ - * │ ON_RESUME - * │ │ - * │ B eligible for restoration ◄─────────────┤ - * │ │ - * ON_STOP │ - * │ │ - * ├── retain txA; timers continue │ - * ├────────────────────────► A no longer eligible for restoration │ - * │ │ - * ON_DESTROY │ - * │ │ - * ├── finish retained txA if unfinished │ - * └────────────────────────► A no longer tracked │ - * ON_PAUSE - * │ - * Navigation lease: B (no other resumed ◄─┤ - * owner) │ - * │ - * ON_STOP - * │ - * Navigation lease: B (no other resumed ◄─┤ - * owner); B keeps recording navigation │ - * B no longer eligible for restoration │ - * │ - * ON_DESTROY - * │ - * Finish txB if unfinished; ◄──────────────┤ - * unbind if still bound │ - * Clear B's remaining screen/back stack │ - * Retain recorded nav events │ - * Navigation lease: none │ - * ▼ - * - * Alternative at rollback point: B disposes before A stops - * Unbind txB ◄─────────────── dispose B ───┤ - * Navigation lease: A │ - * Republish A's staged data │ - * Restore txA if unfinished and scope free │ - * Finish txB if unfinished │ - * ``` - * - * **Nav transactions follow navigation, not the lease** - * - * A candidate gets a nav transaction for a destination it navigates to, never merely for acquiring - * the lease. A destination reached without the lease gets its transaction when the lease is next - * acquired, if it can start then; otherwise it gets none. On reacquiring the lease without having - * navigated in the meantime, a candidate only gets its unfinished transaction back, if any. - * - * Hence the asymmetry for, e.g., ViewPager2 pages: the first time the user swipes to a preloaded - * page, it gets the transaction for the destination it reached while offscreen, but swiping back to - * a page whose transaction has finished starts none. + * See the package README for the lease policy this class enforces. * * **Exception policy** * - * Methods in this class with an `IScope` parameter can throw arbitrary exceptions†, which propagate - * to the caller. Each method updates its own bookkeeping before calling into the scope or a - * candidate's [LeasedNavState], so the coordinator remains usable if the exception is caught. - * Candidates call these methods from [configureScope][IScopes.configureScope] callbacks, whose - * error handling catches the exceptions. + * Methods in this class with an `IScope` parameter can throw arbitrary exceptions, which propagate + * to the caller. For instance, `IScope` can throw arbitrary exceptions when scope mutators notify + * registered observers – including the host app – in an unguarded loop, or when starting a nav + * transaction triggers the host app's callbacks. * - * † E.g., `IScope` can throw arbitrary exceptions when scope mutators notify registered observers – - * including the host app – in an unguarded loop, or when starting a nav transaction triggers the - * host app's callbacks. + * Each method updates its own bookkeeping so that the coordinator remains usable if the exception + * is caught by the caller. * * **Thread safety** * - * This class is ***not*** thread-safe. All `NavScopes` instances using this coordinator must - * confine their access to the same thread. + * This class is ***not*** thread-safe. All callers should confine their access to the same thread. */ @Suppress("TooManyFunctions") internal class NavLeaseCoordinator { + /** A list of all possible leaseholders. */ private val candidates = mutableListOf() - /** Candidate whose nav state was most recently published to the shared scope. */ - private var publisher: Candidate? = null - + /** The actual leaseholder. */ private var leaseHolder: Candidate? = null + /** The last candidate to publish nav state, even if it no longer holds the lease. */ + private var lastPublisher: Candidate? = null + /** - * Counter that orders candidates by when this coordinator most recently observed them in resumed - * state. + * Counter that lets us order candidates by when this coordinator most recently observed them in + * resumed state. */ private var resumeOrder: Long = 0 /** - * Registers a candidate for the nav lease that observes [lifecycle] until it's - * [disposed][NavLeaseRegistration.dispose] or `lifecycle` is destroyed. Returns `null` if - * `lifecycle` is already [destroyed][Lifecycle.State.DESTROYED]. + * Reports the host application's Activities to this coordinator so that it can detect whether a + * leaseholder is covered by a non-candidate root, and retry a nav transaction blocked by a closed + * Activity's `ui.load` transaction. + */ + private val activityWatcher = + NavActivityWatcher( + onActivityCreatedOrResumed = ::onActivityCreatedOrResumed, + onActivityDestroyed = ::onAnyActivityDestroyed, + ) + + /** + * Registers a [nav root][rootInfo] as a lease candidate until disposal or lifecycle destruction. + * + * Returns `null` if the lifecycle is already destroyed. */ fun register( - lifecycle: Lifecycle, scopes: IScopes, - navState: LeasedNavState, + rootInfo: NavRootInfo, + publisher: INavStatePublisher, ): NavLeaseRegistration? { + val lifecycle = rootInfo.lifecycle val lifecycleState = lifecycle.currentState + if (lifecycleState == Lifecycle.State.DESTROYED) { return null } + rootInfo.activity?.application?.let { activityWatcher.watch(it) } + val initialResumeOrder = if (lifecycleState == Lifecycle.State.RESUMED) ++resumeOrder else 0 - val candidate = Candidate(lifecycle, scopes, navState, lifecycleState, initialResumeOrder) - candidates += candidate + val candidate = Candidate(rootInfo, lifecycleState, initialResumeOrder, publisher, scopes) + // Only list the candidate once addObserver() succeeds, so a failure can't leave behind a + // candidate that never observes its nav root's lifecycle. lifecycle.addObserver(candidate) + candidates += candidate return candidate } /** - * Records that [candidate] is about to apply a back-stack update and acquires the nav lease if - * the owner's lifecycle permits it. - * - * Later calls for the same [candidate] do nothing. + * Gives [candidate] one chance to acquire the lease on its first back-stack update, and no-ops + * otherwise. */ private fun onBackStackUpdate(candidate: Candidate, scope: IScope) { - if (candidate.hasAppliedInitialBackStackUpdate) { + if (candidate.hasHandledFirstUpdate) { return } - candidate.hasAppliedInitialBackStackUpdate = true + candidate.hasHandledFirstUpdate = true val holder = leaseHolder - // An owner that isn't resumed doesn't take the lease from a resumed leaseholder, as it isn't - // the one the user is interacting with (e.g., a preloaded ViewPager2 page next to the current - // page). Instead, it acquires the lease when it resumes. - val wouldDisplaceResumedHolder = - holder != null && - holder.state == Lifecycle.State.RESUMED && - candidate.state != Lifecycle.State.RESUMED + // A nav root that isn't resumed while either the leaseholder or its own host Activity is + // resumed isn't the one the user is interacting with (e.g., a preloaded ViewPager2 page next to + // the current page, which may be a page without a SentryNavEffect and so never a leaseholder). + // Instead, it acquires the lease when it resumes. + val isBesideResumedContent = + candidate.state != Lifecycle.State.RESUMED && + (holder?.state == Lifecycle.State.RESUMED || candidate.isHostActivityResumed) - if (candidate.canAcquireLeaseOnFirstUpdate && !wouldDisplaceResumedHolder) { + if (candidate.canAcquireLeaseOnFirstUpdate && !isBesideResumedContent) { transferLeaseTo(candidate, scope) } } - /** - * Records that [candidate] resumed. - * - * Restores the lease to `candidate` if it already applied a back stack update and [scope] is - * non-null. - */ - private fun resumeCandidate(candidate: Candidate, scope: IScope?) { - // A null scope (e.g., the SDK is disabled) still records the lifecycle transition so that the - // candidate remains eligible for fallback once the scope becomes available. - candidate.resume(++resumeOrder) - - if (scope != null && candidate.hasAppliedInitialBackStackUpdate) { - transferLeaseTo(candidate, scope) + /** Hands the lease to [next], or releases it if [scope] is unavailable. */ + private fun handOffLease(next: Candidate?, scope: IScope?) { + if (scope != null) { + transferLeaseTo(next, scope) + } else { + leaseHolder = null } } - /** - * Records that [candidate] paused. - * - * Hands the lease to another owner only if that owner is resumed (e.g., a Fragment whose dialog - * is being dismissed); otherwise keeps it. - */ - private fun pauseCandidate(candidate: Candidate, scope: IScope?) { - candidate.pause() - - // A paused leaseholder may still be the topmost visible owner (e.g., beneath a translucent - // window or picture-in-picture mode), and any other paused owner is beneath it. A displaced - // owner will acquire the lease again when it resumes. + /** Hands the lease to [candidate], or releases it given `null`. */ + private fun transferLeaseTo(candidate: Candidate?, scope: IScope) { if (leaseHolder === candidate) { - mostRecentlyResumedCandidate(excluding = candidate, resumedOnly = true)?.let { next -> - handOffLease(next, scope) + return + } + + val previous = lastPublisher + leaseHolder = candidate + if (candidate != null) { + // Record the candidate as the last publisher before calling into the scope: it owns the + // scope's nav state from the moment it takes the lease. If unpublishing the previous nav + // root's state then throws, the next handoff still unpublishes the candidate's state rather + // than never unpublishing it. + lastPublisher = candidate + if (previous != null && previous !== candidate) { + previous.publisher.unpublishFrom(scope) } + candidate.publisher.publishTo(scope) } } /** - * Records that [candidate] stopped. + * Releases the lease without handing it off and unpublishes its nav state from [scope]. The + * candidate retains staged state for a later return. Without a scope, state remains published. * - * As with pausing, hands the lease to another owner only if that owner is resumed; otherwise the - * stopped owner keeps it. Keeping it lets a lone owner go on recording navigation that happens - * while it isn't resumed (e.g., while the app is in the background, or after it restarts but - * before it resumes), including starting nav transactions. + * Logs [withdrawalReason]. */ - private fun stopCandidate(candidate: Candidate, scope: IScope?) { - candidate.stop() - - // A paused owner doesn't get the lease. When the leaseholder stops before it, the app is - // typically going to the background (e.g., a translucent leaseholder stops before the owner - // beneath it), and that owner isn't what the user last saw. A paused owner that comes back to - // the foreground will acquire the lease when it resumes. - if (leaseHolder === candidate) { - mostRecentlyResumedCandidate(resumedOnly = true)?.let { next -> handOffLease(next, scope) } + private fun withdrawLease(scope: IScope?, withdrawalReason: String) { + val holder = leaseHolder ?: return + + leaseHolder = null + scope + ?.options + ?.logger + ?.log( + SentryLevel.DEBUG, + "Withdrew the Nav3 lease from a nav root hosted by %s: %s.", + holder.hostActivity?.javaClass?.name, + withdrawalReason, + ) + if (scope != null && lastPublisher === holder) { + // Clear the last publisher before calling into the scope (see the class's exception policy). + lastPublisher = null + holder.publisher.unpublishFrom(scope) } } /** * The eligible candidate most recently observed to be in a resumed state, other than [excluding]. * - * If [resumedOnly] is set to `true`, only candidates that are resumed right now are considered; - * if `false`, started and paused candidates are also considered. + * Only candidates whose current state is at least [minimumState] are considered. Candidates + * hosted by [excludingHostedBy] are skipped. */ private fun mostRecentlyResumedCandidate( excluding: Candidate? = null, - resumedOnly: Boolean = false, + minimumState: Lifecycle.State = Lifecycle.State.STARTED, + excludingHostedBy: Activity? = null, ): Candidate? = candidates .filter { it !== excluding && - it.hasAppliedInitialBackStackUpdate && - it.state.isAtLeast(Lifecycle.State.STARTED) && - it.resumeOrder > 0 && - (!resumedOnly || it.state == Lifecycle.State.RESUMED) + (excludingHostedBy == null || it.hostActivity !== excludingHostedBy) && + it.canReceiveLease && + it.state.isAtLeast(minimumState) && + it.resumeOrder > 0 } .maxByOrNull { it.resumeOrder } /** - * Hands the current lease to [next]. Without a [scope], the lease is released instead, as [next] - * could not publish its staged data. + * Records that [candidate] resumed. + * + * Gives [candidate] the lease if its back stack has had an initial update and [scope] is + * available. */ - private fun handOffLease(next: Candidate?, scope: IScope?) { - if (scope != null) { - transferLeaseTo(next, scope) - } else { - leaseHolder = null + private fun resumeCandidate(candidate: Candidate, scope: IScope?) { + // A null scope (e.g., the SDK is disabled) still records the lifecycle transition so that the + // candidate remains eligible for fallback once the scope becomes available. + candidate.resume(++resumeOrder) + + if (scope != null && candidate.canReceiveLease) { + transferLeaseTo(candidate, scope) } } - /** Hands the lease to [candidate], or releases it given `null`. */ - private fun transferLeaseTo(candidate: Candidate?, scope: IScope) { + /** + * Records that [candidate] paused. + * + * If [candidate] holds the lease when it pauses, hands it to another resumed nav root (e.g., a + * Fragment whose dialog is being dismissed), unless that nav root shares [candidate]'s pausing + * host Activity. If none exists, withdraws it when the host Activity remains resumed; otherwise + * the paused nav root keeps the lease. + */ + private fun pauseCandidate(candidate: Candidate, scope: IScope?) { + candidate.pause() + + // A paused leaseholder may still be the topmost visible nav root (e.g., beneath a translucent + // window or picture-in-picture mode), and any other paused nav root is beneath it. A displaced + // nav root will acquire the lease again when it resumes. if (leaseHolder === candidate) { - return + // An Activity pauses before its Fragments, so when the host Activity is pausing, its other + // nav roots are still resumed but about to pause too. Handing them the lease would publish + // their nav state, and start a nav transaction, just as the app is backgrounded or covered. + val next = + mostRecentlyResumedCandidate( + excluding = candidate, + minimumState = Lifecycle.State.RESUMED, + excludingHostedBy = candidate.hostActivity.takeIf { candidate.isHostActivityPaused }, + ) + when { + next != null -> handOffLease(next, scope) + candidate.isHostActivityResumed -> + withdrawLease( + scope, + withdrawalReason = "the nav root paused while its host Activity stayed resumed", + ) + } } + } - val previousPublisher = publisher - leaseHolder = candidate - if (candidate != null) { - // Record the candidate as the publisher before calling into the scope: it owns the scope's - // nav state from the moment it takes the lease. If unpublishing the previous owner's state - // then throws, the next handoff still unpublishes the candidate's state rather than never - // unpublishing it. - publisher = candidate - if (previousPublisher != null && previousPublisher !== candidate) { - previousPublisher.navState.unpublishFrom(scope) + /** + * Records that [candidate] stopped. + * + * If [candidate] holds the lease when it stops, hands it to another resumed nav root or keeps it + * so a lone nav root can record navigation while the app is backgrounded. + */ + private fun stopCandidate(candidate: Candidate, scope: IScope?) { + candidate.stop() + + // A paused nav root doesn't get the lease. When the leaseholder stops before it, the app is + // typically going to the background (e.g., a translucent leaseholder stops before the nav root + // beneath it), and that nav root isn't what the user last saw. A paused nav root that comes + // back to the foreground will acquire the lease when it resumes. + if (leaseHolder === candidate) { + mostRecentlyResumedCandidate(minimumState = Lifecycle.State.RESUMED)?.let { next -> + handOffLease(next, scope) } - candidate.navState.publishTo(scope) } } /** - * Stops tracking [candidate] (e.g., because it was destroyed). - * - * Unpublishes `candidate`'s nav state from [scope] if it's the most recently published. If - * `candidate` holds the lease, hands it to the eligible candidate most recently observed resumed, - * even if that candidate is now only started or paused, or releases it if there's none. + * Removes [candidate], unpublishes its state if needed, and hands off its lease to the latest + * eligible candidate. Without [scope], releases the lease without unpublishing. */ private fun unregisterCandidate(candidate: Candidate, scope: IScope?) { - val wasPublisher = publisher === candidate + val wasLastPublisher = lastPublisher === candidate val wasLeaseHolder = leaseHolder === candidate // Remove candidate before any scope calls to ensure it's released even if cleanup or handoff // throws. candidates.remove(candidate) - if (wasPublisher) { - publisher = null + if (wasLastPublisher) { + lastPublisher = null } if (wasLeaseHolder) { leaseHolder = null @@ -362,8 +295,8 @@ internal class NavLeaseCoordinator { return } - if (wasPublisher) { - candidate.navState.unpublishFrom(scope) + if (wasLastPublisher) { + candidate.publisher.unpublishFrom(scope) } if (wasLeaseHolder) { transferLeaseTo(mostRecentlyResumedCandidate(), scope) @@ -371,45 +304,132 @@ internal class NavLeaseCoordinator { } /** - * A [LifecycleOwner] registered as a candidate for lease ownership. Relays its owner's lifecycle - * events to the coordinator until it's [disposed][dispose]. + * Whether [activity] owns a candidate's nav root that + * [can receive the lease][Candidate.canReceiveLease]. + * + * A returning Activity root takes the lease on resume and should not trigger withdrawal first. + */ + private fun isActivityNavRoot(activity: Activity): Boolean = candidates.any { + it.canReceiveLease && it.isActivityNavRoot(activity) + } + + /** Withdraws the lease when [activity] appears to cover a non-resumed nav root. */ + private fun onActivityCreatedOrResumed( + activity: Activity, + event: NavActivityWatcher.ActivityEvent, + ) { + // Assume the created or resumed `activity` is covering the current leaseholder if i) the + // leaseholder itself isn't resumed, ii) `activity` isn't the leaseholder's host Activity, and + // iii) `activity` isn't itself a nav root (see [isActivityNavRoot]). (i) checks the + // leaseholder's own state rather than its host Activity's, as they differ for Fragment nav + // roots: a Fragment leaseholder that isn't resumed isn't what the user is interacting with, + // even if its host Activity is resumed. + val holder = leaseHolder ?: return + val hostActivity = holder.hostActivity ?: return + if ( + hostActivity === activity || + holder.state == Lifecycle.State.RESUMED || + isActivityNavRoot(activity) + ) { + return + } + + holder.withScopeOrNull { scope -> + withdrawLease( + scope, + withdrawalReason = + "${activity.javaClass.name} was ${event.description} while the nav root wasn't resumed", + ) + } + } + + /** + * After [activity] is destroyed, asks the leaseholder to retry publication if an Activity's + * `ui.load` blocked it. The publisher decides whether the blocker has left and retry is allowed. + */ + private fun onAnyActivityDestroyed(activity: Activity) { + val holder = leaseHolder ?: return + if (holder.hostActivity === activity) { + return + } + + holder.withScopeOrNull { scope -> + if (scope != null) { + holder.publisher.retryTransactionPublication(scope) + } + } + } + + /** + * A [nav root][rootInfo] eligible to hold the lease managed by [NavLeaseCoordinator]. + * + * [Disposed][dispose] upon the nav root's destruction. */ private inner class Candidate( - private val lifecycle: Lifecycle, - private val scopes: IScopes, - val navState: LeasedNavState, + rootInfo: NavRootInfo, initialState: Lifecycle.State, initialResumeOrder: Long, + val publisher: INavStatePublisher, + private val scopes: IScopes, ) : NavLeaseRegistration, LifecycleEventObserver { - /** The candidate's lifecycle state, as last observed. */ - var state: Lifecycle.State = initialState - private set + // Held weakly because candidates live in a process-wide coordinator: if disposal fails before + // the candidate is removed, it must not keep its destroyed host Activity alive. + private val hostActivityRef: WeakReference? = rootInfo.activity?.let(::WeakReference) - /** - * Whether the candidate has been observed STOPPED since - * [registration][NavLeaseCoordinator.register]. - */ - private var wasStopped: Boolean = false + /** The Activity hosting this nav root, or `null` if it's unknown or has been collected. */ + val hostActivity: Activity? + get() = hostActivityRef?.get() - /** - * See [NavLeaseCoordinator.resumeOrder]. Non-zero once the candidate has been observed RESUMED - * since [registration][NavLeaseCoordinator.register]. - */ + /** Whether the host Activity is resumed; false when its lifecycle is unavailable. */ + val isHostActivityResumed: Boolean + get() = hostActivityState == Lifecycle.State.RESUMED + + /** Whether the host Activity isn't resumed; false when its lifecycle is unavailable. */ + val isHostActivityPaused: Boolean + get() = hostActivityState.let { it != null && it != Lifecycle.State.RESUMED } + + private val hostActivityState: Lifecycle.State? + get() = (hostActivity as? LifecycleOwner)?.lifecycle?.currentState + + /** Most recent resume order; zero until this candidate first resumes. */ var resumeOrder: Long = initialResumeOrder private set - var hasAppliedInitialBackStackUpdate: Boolean = false + /** The candidate's last observed lifecycle state. */ + var state: Lifecycle.State = initialState + private set + + /** Whether this candidate has handled its first back-stack update. */ + var hasHandledFirstUpdate: Boolean = false /** - * Whether the candidate's lifecycle permits its first back stack update since - * [registration][NavLeaseCoordinator.register] to acquire the nav lease: it's resumed, or it - * has neither resumed nor stopped since registration (i.e., it's still coming up for the first - * time). + * Whether the first back-stack update may take the lease: the nav root is resumed or has not + * yet resumed or stopped since registration. */ val canAcquireLeaseOnFirstUpdate: Boolean get() = state == Lifecycle.State.RESUMED || (resumeOrder == 0L && !wasStopped) + /** + * Whether this candidate can acquire the lease on a lifecycle change, i.e., when it resumes or + * as a fallback. + * + * False until its first back stack update is handled, as it has no nav state to publish before + * then. + */ + val canReceiveLease: Boolean + get() = hasHandledFirstUpdate + + override val hasLease: Boolean + get() = leaseHolder === this + + private val lifecycle: Lifecycle = rootInfo.lifecycle + + /** Whether this candidate has stopped since registration. */ + private var wasStopped: Boolean = false + + private var isDisposed = false + fun start() { // Attaching to an already-resumed lifecycle replays ON_START before ON_RESUME, so only move // up from CREATED. @@ -432,11 +452,6 @@ internal class NavLeaseCoordinator { wasStopped = true } - private var isDisposed = false - - override val hasLease: Boolean - get() = leaseHolder === this - override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { when (event) { ON_START -> start() @@ -466,19 +481,16 @@ internal class NavLeaseCoordinator { try { unregisterCandidate(this, scope) } finally { - navState.onUnregistered(scope) + publisher.onUnregistered(scope) } } } /** - * Runs [block] with the real scope, or with `null` if [configureScope][IScopes.configureScope] - * skips its callback (e.g., the SDK is disabled), so coordinator bookkeeping still happens. - * - * A callback that ran but threw is not retried, as retrying could let its exception escape into - * the host app. + * Runs [block] with the scope, or with `null` if [IScopes.configureScope] skips its callback. + * Does not rerun a callback that throws. */ - private fun withScopeOrNull(block: (IScope?) -> Unit) { + fun withScopeOrNull(block: (IScope?) -> Unit) { var callbackInvoked = false scopes.configureScope { scope -> callbackInvoked = true @@ -489,6 +501,10 @@ internal class NavLeaseCoordinator { block(null) } } + + /** Whether [activity] itself owns this nav root, rather than a Fragment it hosts. */ + fun isActivityNavRoot(activity: Activity): Boolean = + hostActivity === activity && (activity as? LifecycleOwner)?.lifecycle === lifecycle } } @@ -502,41 +518,31 @@ internal interface NavLeaseRegistration { /** Whether the candidate holds the nav lease. */ val hasLease: Boolean - /** - * Announces that the candidate is about to apply a back stack update, so it can acquire the nav - * lease if it's eligible to. Does nothing once the candidate is unregistered. - */ + /** Gives the candidate a chance to acquire the lease before its first back-stack update. */ fun onBackStackUpdate() /** - * Stops observing the candidate's lifecycle and unregisters it: releases the lease, unpublishes - * the candidate's nav state, and then calls [LeasedNavState.onUnregistered], even if - * unregistering throws. Does nothing once the candidate is unregistered. + * Unregisters the candidate, releases its lease, and unpublishes its nav state. Calls + * [INavStatePublisher.onUnregistered] even if cleanup throws. Repeated calls do nothing. */ fun dispose() } -/** - * The nav state a [NavLeaseCoordinator] candidate publishes to the shared [IScope] while it holds - * the nav lease. - * - * Nav transactions and nav data each occupy a single, mutually-exclusive slot in the `IScope`, so - * only one candidate's nav state can be published at a time. Unpublishing nav state removes it from - * the scope but keeps it staged, so the candidate can publish it again if it regains the lease. - */ -internal interface LeasedNavState { +/** Publishes a [NavLeaseCoordinator.Candidate]'s nav state to the shared [IScope]. */ +internal interface INavStatePublisher { - /** Publishes staged nav state to [scope]. */ + /** Publishes the candidate's staged nav state to [scope]. */ fun publishTo(scope: IScope) - /** Removes published nav state from [scope], keeping it staged so it can be republished. */ - fun unpublishFrom(scope: IScope) - /** - * Called when the lease candidate is unregistered, after its nav state has been unpublished. - * - * The provided [scope] is the scope the candidate was unregistered against, or `null` if there - * was none (e.g., the SDK is disabled). + * Retries a nav transaction blocked by an Activity's `ui.load`, subject to + * [StagedNavTransaction.retryPublishIfBlocked]. Leaves other published nav state alone. */ + fun retryTransactionPublication(scope: IScope) + + /** Removes published nav state from [scope], retaining it for a later lease acquisition. */ + fun unpublishFrom(scope: IScope) + + /** Called after unregistering, with the affected [scope] or `null` if none was available. */ fun onUnregistered(scope: IScope?) } diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavRootInfo.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavRootInfo.kt new file mode 100644 index 00000000000..01f64bef0d4 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavRootInfo.kt @@ -0,0 +1,39 @@ +package io.sentry.compose.navigation3.lifecycle + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import androidx.lifecycle.Lifecycle + +/** + * Describes the nav root of a `SentryNavEffect`. + * + * A "nav root" is the Activity or Fragment whose content calls a `SentryNavEffect` and owns the + * back stack the effect observes. + */ +internal class NavRootInfo( + /** The nav root's lifecycle. */ + val lifecycle: Lifecycle, + /** + * The Activity that displays the nav root's content, or `null` if it's unknown. + * + * If the nav root is itself an Activity, this is the nav root. If the nav root is a Fragment, + * this is the Activity that hosts the Fragment. + */ + val activity: Activity?, +) + +/** + * The Activity the receiver belongs to, found by unwrapping [ContextWrapper]s (e.g., the + * `ContextThemeWrapper` of a dialog), or `null` if there is none. + */ +internal fun Context.findActivity(): Activity? { + var context: Context? = this + while (context is ContextWrapper) { + if (context is Activity) { + return context + } + context = context.baseContext + } + return null +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopes.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopes.kt index 37a796a58c6..b8115cacafe 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopes.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopes.kt @@ -8,10 +8,6 @@ import io.sentry.IScopes import io.sentry.PropagationContext import io.sentry.SentryLevel import io.sentry.SentryOptions -import io.sentry.TransactionContext -import io.sentry.TransactionOptions -import io.sentry.protocol.App -import io.sentry.protocol.Contexts /** The key under which nav context (i.e., the captured back stack) is stored in a scope. */ internal const val NAVIGATION_CONTEXT_KEY: String = "Navigation" @@ -24,8 +20,8 @@ internal const val NAVIGATION_CONTEXT_KEY: String = "Navigation" * Needed because all `SentryNavEffect`s mutate a single [IScope] instance by default and will * clobber or interleave one another's updates unless properly managed: * ``` - * LifecycleOwner (e.g., Activity or Fragment) - * ↓ owns + * Nav root (Activity or Fragment) + * ↓ owns / calls * SentryNavEffect * ↓ * CoordinatedBackStackObserver (wrapper) @@ -56,7 +52,7 @@ internal const val NAVIGATION_CONTEXT_KEY: String = "Navigation" * 2. Pass the same [NavLeaseCoordinator] instance to all `NavScopes` whose effects must be * coordinated (i.e., that target the same `IScope`). * - * 3. Call [attach] with the lifecycle that manages the effect before the first back stack update. + * 3. Call [attach] with the effect's [nav root][NavRootInfo] before the first back stack update. * * 4. Call [onBackStackUpdate] before applying each back stack update. * @@ -80,22 +76,25 @@ internal class NavScopes( /** This instance's registration with the [coordinator], while it's attached. */ private var registration: NavLeaseRegistration? = null - private val stagedNavTransaction = StagedNavTransaction(delegate) + private val stagedNavTransaction = + StagedNavTransaction(delegate, delegate.options.monotonicTicker) private val stagedNavData = StagedNavData() private val navStatePublisher = NavStatePublisher() /** - * Registers this [NavScopes] instance with [lifecycle]. No-ops if `lifecycle` has already been - * attached or is [destroyed][Lifecycle.Event.ON_DESTROY]. + * Registers this [NavScopes] instance with the lifecycle of the effect's nav root, described by + * [rootInfo]. * - * Attaching to a second, different lifecycle no-ops. + * No-ops if the caller tries to attach more than once or if the nav root has already been + * destroyed. */ - fun attach(lifecycle: Lifecycle) { + fun attach(rootInfo: NavRootInfo) { val currentLifecycle = attachedLifecycle + val incomingLifecycle = rootInfo.lifecycle if (currentLifecycle != null) { - if (currentLifecycle !== lifecycle) { + if (currentLifecycle !== incomingLifecycle) { delegate.options.logger.log( SentryLevel.WARNING, "NavScopes is already attached to a different lifecycle; ignoring the new lifecycle.", @@ -106,12 +105,12 @@ internal class NavScopes( return } - if (lifecycle.currentState == Lifecycle.State.DESTROYED) { + if (incomingLifecycle.currentState == Lifecycle.State.DESTROYED) { return } - attachedLifecycle = lifecycle - registration = coordinator.register(lifecycle, delegate, navStatePublisher) + attachedLifecycle = incomingLifecycle + registration = coordinator.register(delegate, rootInfo, navStatePublisher) } /** @@ -147,7 +146,7 @@ internal class NavScopes( * Publishes this instance's [stagedNavTransaction] and [stagedNavData] to the shared [IScope] * while it holds the nav lease, as directed by the [coordinator]. */ - private inner class NavStatePublisher : LeasedNavState { + private inner class NavStatePublisher : INavStatePublisher { override fun publishTo(scope: IScope) { // Publishing the data first ensures a staged transaction is sampled against the rotated @@ -156,6 +155,10 @@ internal class NavScopes( stagedNavTransaction.publishTo(scope) } + override fun retryTransactionPublication(scope: IScope) { + stagedNavTransaction.retryPublishIfBlocked(scope) + } + override fun unpublishFrom(scope: IScope) { stagedNavTransaction.unpublishFrom(scope) stagedNavData.clearPublishedStateFrom(scope) @@ -192,15 +195,6 @@ internal class NavScopes( } } - /** - * Copies the whole of [IScope.getContexts] in order to return a copy of its [App]. - * - * [App]'s copy constructor isn't public, so an `App` can't be copied on its own. Going through - * [Contexts] deep-copies every context on the scope and discards all of it but the `App`. - */ - override val app: App? - get() = Contexts(delegate.contexts).app - private val hasLease: Boolean get() = registration?.hasLease == true @@ -219,6 +213,10 @@ internal class NavScopes( } } + override fun updateNavTransactionRequest(request: NavTransactionRequest) { + stagedNavTransaction.updateRequest(request) + } + /** * Starts and binds a nav transaction with the nav lease, or defers it until the lease is * acquired (see [StagedNavTransaction]). Callers must [finish][finishNavTransaction] the @@ -232,15 +230,14 @@ internal class NavScopes( * meantime attach to whichever transaction is bound to the scope at that time, usually the * leaseholder's. */ - override fun startNavTransaction( - transactionContext: TransactionContext, - transactionOptions: TransactionOptions, - ): INavTransaction? { - return if (hasLease) { - stagedNavTransaction.start(delegate, transactionContext, transactionOptions) + override fun startNavTransaction(request: NavTransactionRequest) { + stagedNavTransaction.stage(request) + if (hasLease) { + // Don't retry b/c ui.load retry is only for returns to a nav root, not for navigation + // within it. + stagedNavTransaction.publishTo(delegate, canRetry = false) } else { stagedNavData.deferPropagationContextRotation() - stagedNavTransaction.stage(transactionContext, transactionOptions) } } @@ -284,17 +281,6 @@ internal sealed interface INavScope { var screen: String? - /** - * A copy of the scope's app context, if any. - * - * A copy rather than the live instance, because callers mutate the result before binding it to a - * transaction, and mutating the scope's own [App] would corrupt shared scope state. - * - * Implementations may have to copy more than the [App] to produce it, so treat this as expensive: - * read it once where it's needed rather than per frame or in a loop. - */ - val app: App? - /** * Sets or, given `null`, clears the value stored under [NAVIGATION_CONTEXT_KEY]. * @@ -307,21 +293,29 @@ internal sealed interface INavScope { fun rotatePropagationContext() /** - * Starts a nav transaction and binds it to the scope, unless another unfinished transaction is - * already bound to it. Returns `null` if no transaction was started. + * Replaces the request kept from the most recent [startNavTransaction] with [request] (e.g., to + * reflect a back stack whose entries below the top changed), so that transactions started for the + * same destination later are started from it. A transaction that has already started keeps what + * it was started with. + * + * Does nothing if no request is kept, i.e., none was made since the last [finishNavTransaction]. + */ + fun updateNavTransactionRequest(request: NavTransactionRequest) + + /** + * Starts a nav transaction for [request] and binds it to the scope, unless another unfinished + * transaction is already bound to it, in which case none is started. * * (Note: Callers must first [finish][finishNavTransaction] the nav transaction most recently * requested, if any. Otherwise, with the nav lease, it blocks the new one while it's bound; * without the lease, it's replaced without being finished.) * - * The start may be deferred until the nav lease is acquired, in which case writes to the returned - * transaction are staged in the meantime, and whether another transaction blocks it is decided - * then (see [StagedNavTransaction.publishTo]). + * The start may be deferred until the nav lease is acquired, in which case whether another + * transaction blocks it is decided then (see [StagedNavTransaction.publishTo]). Either way, the + * request is kept until the next [finishNavTransaction], so that a new transaction can be started + * from it if the user returns to the nav root after this one finished. */ - fun startNavTransaction( - transactionContext: TransactionContext, - transactionOptions: TransactionOptions, - ): INavTransaction? + fun startNavTransaction(request: NavTransactionRequest) /** * Finishes the nav transaction most recently requested via [startNavTransaction] and unbinds it diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransaction.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransaction.kt deleted file mode 100644 index c8c1464687c..00000000000 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransaction.kt +++ /dev/null @@ -1,149 +0,0 @@ -package io.sentry.compose.navigation3.lifecycle - -import io.sentry.IScopes -import io.sentry.ITransaction -import io.sentry.SpanStatus -import io.sentry.TransactionContext -import io.sentry.TransactionOptions -import io.sentry.protocol.App - -/** - * An [INavTransaction] handle backed by an [ITransaction] that's either started right away or, when - * the nav lease isn't held, [started later][start]. - * - * A deferred handle records what's set on it and replays it onto the transaction once started. - * [Finishing][finish] a deferred handle before it starts discards it, so its transaction never - * starts. - * - * **Thread safety** - * - * This class is ***not*** thread-safe. Apply the thread safety policy from [NavScopes]. - */ -internal class NavTransaction -private constructor( - val name: String, - private var state: State, -) : INavTransaction { - - /** - * The backing transaction, once [started][State.Started]; `null` while [pending][State.Pending] - * or once [discarded][State.Discarded]. - */ - val transaction: ITransaction? - get() = (state as? State.Started)?.transaction - - override fun setData(key: String, value: Any) { - when (val state = state) { - is State.Pending -> state.data[key] = value - is State.Started -> state.transaction.setData(key, value) - State.Discarded -> Unit - } - } - - override fun setContext(key: String, value: Any) { - when (val state = state) { - is State.Pending -> state.contexts[key] = value - is State.Started -> state.transaction.setContext(key, value) - State.Discarded -> Unit - } - } - - override fun setApp(app: App) { - when (val state = state) { - is State.Pending -> state.app = app - is State.Started -> state.transaction.contexts.setApp(app) - State.Discarded -> Unit - } - } - - /** - * Starts a deferred handle's transaction via [scopes] and replays what was set on the handle onto - * it. - * - * Returns the started transaction, or `null` if the handle was started already or discarded, or - * [scopes] declined to start one. - */ - fun start(scopes: IScopes): ITransaction? { - val pending = state as? State.Pending ?: return null - val transaction = - scopes.startTransaction(pending.context, pending.options).takeUnless { it.isNoOp } - ?: return null - - state = State.Started(transaction) - pending.data.forEach { (key, value) -> transaction.setData(key, value) } - pending.contexts.forEach { (key, value) -> transaction.setContext(key, value) } - pending.app?.let { transaction.contexts.setApp(it) } - return transaction - } - - /** - * Finishes the backing transaction with its own status, or [OK][SpanStatus.OK] if it has none, - * and then passes it to [onFinished]. - * - * A deferred handle that hasn't started is discarded instead, so it never starts, and - * [onFinished] isn't called. - */ - fun finish(onFinished: (ITransaction) -> Unit) { - when (val state = state) { - is State.Pending -> this.state = State.Discarded - is State.Started -> { - if (!state.transaction.isFinished) { - state.transaction.finish(state.transaction.status ?: SpanStatus.OK) - } - onFinished(state.transaction) - } - State.Discarded -> Unit - } - } - - /** Lifecycle state for a [NavTransaction] handle. */ - private sealed interface State { - - /** - * Not started yet: the transaction will be started from [context] and [options], and what's set - * on the handle until then is recorded for replay. - */ - class Pending(val context: TransactionContext, val options: TransactionOptions) : State { - val data = linkedMapOf() - val contexts = linkedMapOf() - var app: App? = null - } - - /** The backing [transaction] has been started. A terminal [State]. */ - class Started(val transaction: ITransaction) : State - - /** The handle was finished before its backing transaction was started. A terminal [State]. */ - data object Discarded : State - } - - companion object { - /** A handle backed by the already-started [transaction]. */ - fun started(transaction: ITransaction): NavTransaction = - NavTransaction(transaction.name, State.Started(transaction)) - - /** A handle whose transaction is started later, via [start]. */ - fun deferred(context: TransactionContext, options: TransactionOptions): NavTransaction = - NavTransaction(context.name, State.Pending(context, options)) - } -} - -/** - * The subset of the [ITransaction] interface used to record nav data on a nav transaction. - * - * Protects against accidental misuse of what would otherwise be a partially-implemented - * `ITransaction` interface. New operations against the underlying `ITransaction` instance must be - * added here. Operations not directly delegable to `ITransaction` should ***not*** be added. - * - * Starting and finishing a nav transaction are lease-aware, so they go through [INavScope] instead. - */ -internal sealed interface INavTransaction { - - /** See [ITransaction.setData]. */ - fun setData(key: String, value: Any) - - /** See [ITransaction.setContext]. */ - fun setContext(key: String, value: Any) - - /** Sets the transaction's app context. See [ITransaction.getContexts]. */ - fun setApp(app: App) -} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionRequest.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionRequest.kt new file mode 100644 index 00000000000..343518b6542 --- /dev/null +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionRequest.kt @@ -0,0 +1,103 @@ +package io.sentry.compose.navigation3.lifecycle + +import io.sentry.IScope +import io.sentry.IScopes +import io.sentry.ITransaction +import io.sentry.SentryOptions +import io.sentry.TransactionContext +import io.sentry.TransactionOptions +import io.sentry.protocol.App +import io.sentry.protocol.Contexts +import io.sentry.protocol.TransactionNameSource + +/** The operation of nav transactions, and the type and category of nav breadcrumbs. */ +internal const val NAVIGATION_OP: String = "navigation" + +/** + * Everything needed to start a nav transaction for a destination. + * + * Transactions started from a request are named [name] with [TransactionNameSource.ROUTE] as their + * name source, and have the operation [NAVIGATION_OP]. + * + * A request may be reused to start a new transaction if the user returns to a nav root after its + * transaction finishes. Each [start] creates a new transaction for the same destination. + */ +internal class NavTransactionRequest( + val name: String, + /** Builds the options for each transaction started from this request. */ + private val newOptions: () -> TransactionOptions, + /** Data set on each transaction started from this request. See [ITransaction.setData]. */ + private val data: Map = emptyMap(), + /** Contexts set on each transaction started from this request. See [ITransaction.setContext]. */ + private val contexts: Map = emptyMap(), + /** + * The view names to set on the app context of each transaction started from this request, or + * `null` to leave the transaction's app context alone. The rest of the app context is copied from + * the scope when the transaction starts. + */ + private val viewNames: List? = null, +) { + + companion object { + + private const val TRANSACTION_ORIGIN = "auto.navigation.nav3" + + /** Creates a request whose transaction options are read when each transaction starts. */ + fun forDestination( + name: String, + arguments: Map, + contexts: Map, + viewNames: List?, + options: SentryOptions, + ): NavTransactionRequest = + NavTransactionRequest( + name = name, + newOptions = { + TransactionOptions().also { + it.isWaitForChildren = true + it.idleTimeout = options.idleTimeout + val deadlineTimeoutMillis = options.deadlineTimeout + it.deadlineTimeout = if (deadlineTimeoutMillis <= 0) null else deadlineTimeoutMillis + it.isTrimEnd = true + it.origin = TRANSACTION_ORIGIN + } + }, + data = if (arguments.isNotEmpty()) mapOf("arguments" to arguments) else emptyMap(), + contexts = contexts, + viewNames = viewNames, + ) + } + + /** + * Starts a transaction via [scopes] with this request's data and contexts. Copies the app context + * from [publishingScope] when setting view names, without binding the transaction to that scope. + * + * Returns `null` if [scopes] declined to start one (i.e., returned a no-op transaction, e.g., + * because the SDK is disabled or ignores the transaction's origin). + */ + fun start(scopes: IScopes, publishingScope: IScope): ITransaction? { + val transaction = + scopes + .startTransaction( + TransactionContext(name, TransactionNameSource.ROUTE, NAVIGATION_OP), + newOptions(), + ) + .takeUnless { it.isNoOp } ?: return null + + data.forEach { (key, value) -> transaction.setData(key, value) } + contexts.forEach { (key, value) -> transaction.setContext(key, value) } + viewNames?.let { + transaction.contexts.setApp(publishingScope.appCopy().apply { this.viewNames = it }) + } + return transaction + } + + /** + * A copy of the receiver's app context, or a new one if it has none, so that setting view names + * on it leaves the scope's own app context alone. + * + * [App]'s copy constructor isn't public, so this copies all of [IScope.getContexts] and discards + * all of it but the `App`. + */ + private fun IScope.appCopy(): App = Contexts(contexts).app ?: App() +} diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/README.md b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/README.md index e003af99061..9670faa20f8 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/README.md +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/README.md @@ -3,10 +3,6 @@ Package contains code for coordinating multiple `SentryNavEffect`s and their access to a shared `IScope`, so that overlapping effects (e.g., during Activity or Fragment transitions) don't clobber one another's screen names, nav context, or nav transactions. -See the `NavLeaseCoordinator` KDoc for the lease policy that decides which effect may write to the scope. - -## Encapsulation policy - This package is meant to encapsulate knowledge about the possibility of multiple `SentryNavEffect`s and the shared mutable state issues it 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. @@ -16,10 +12,6 @@ logic should we someday need to. Support for multiple `SentryNavEffect`s is restricted to the scenarios documented in the [Navigation for Android docs](https://docs.sentry.io/platforms/android/integrations/navigation/#supported-setups). -`NavLeaseCoordinator` implements the policy that underlies those scenarios. It assumes that, at any moment, the user is interacting with at -most one registered `LifecycleOwner` in the host app, and that the `LifecycleOwner` being interacted with is the one that was most recently -resumed. - Concretely, a host app can safely use more than one `SentryNavEffect` only if: 1. each `SentryNavEffect` is called in the same composable as the `NavDisplay` it observes; @@ -28,7 +20,216 @@ Concretely, a host app can safely use more than one `SentryNavEffect` only if: not alongside one in the Activity hosting them); and 4. the user can interact with only one of those Activities or Fragments at a time. -† Meant to ensure each effect's `LocalLifecycleOwner` is an Activity or a Fragment and not a `NavDisplay`-provided owner. `NavDisplay` +> † Meant to ensure each effect's `LocalLifecycleOwner` is an Activity or a Fragment and not a `NavDisplay`-provided owner. `NavDisplay` provides its own `LocalLifecycleOwner` to the entries and scenes it renders. That owner drops to STARTED state during transitions and while overlays are shown. An effect called inside a `NavDisplay` would therefore (wrongly) gain and lose the nav lease `NavLeaseCoordinator` manages as navigation animates, rather than as its Activity or Fragment comes and goes. + +## Lease policy + +`NavLeaseCoordinator` implements the lease policy that supports the scenarios from the Navigation for Android docs. The policy assumes that, +at any moment, the user is interacting with at most one nav root in the host app, and that the nav root being interacted with is the one +that was most recently resumed. (See the `NavRootInfo` KDoc for a definition of "nav root".) + +### A fundamental tradeoff + +While nav roots overlap (e.g., during an Activity transition), the nav transaction and scoped nav data can reflect **_either_**: + +1. the outgoing nav root that's still visible, or +2. the incoming nav root that may crash before it becomes visible, + +but not both. `NavLeaseCoordinator` opts for (2) so that the incoming destination populates crash context and any work performed is +associated with it – the idea being that start-up logic is more likely to cause a crash or produce interesting spans than an outgoing +destination's steady state. As a consequence, spans produced by the outgoing nav root may appear as if they were produced by the incoming +nav root (or vice versa, were our policy reversed). + +### Lease handoff policy + +The lease is acquired preemptively by an incoming nav root's `NavScopes` instance when it applies its first back stack update +(`onBackStackUpdate`)†. + +A displaced nav root remains eligible for lease restoration until it stops (`ON_STOP`). It gets the lease back when it resumes +(`ON_RESUME`), or sooner if the new nav root leaves or pauses while the displaced nav root is still visible. If restored, the displaced nav +root's nav data is reinstated, and so is its nav transaction if unfinished. Otherwise, the nav root gets a new nav transaction (see +[below](#returning-to-a-nav-root)). + +> † The exception is an incoming nav root that isn't resumed while the leaseholder or the incoming +nav root's host Activity is, e.g., a preloaded ViewPager2 Fragment page next to the current one, +whether or not the current page has a `SentryNavEffect`. The user isn't interacting with such a +nav root yet, so it acquires the lease when it resumes instead. + +The following diagram illustrates how handoff works: + +``` + Time + │ + ▼ + +Nav root A Shared IScope state Nav root B +────────── ─────────────────── ────────── + +attach() Navigation lease: none + │ +Initial back stack update + │ + ├── acquire lease ────────► Navigation lease: A + ├── create & bind txA ────► Scope transaction: txA + ├── publish nav data ─────► Published data: A + │ +ON_RESUME A is eligible for restoration + │ +ON_PAUSE + │ + ├────────────────────────► Navigation lease: A (no other resumed nav root) + │ A remains eligible for restoration + │ + │ attach() + │ │ + │ Navigation lease: A ◄────────────────────┤ + │ Scope transaction: txA │ + │ Published data: A │ + │ B registered, awaiting initial back │ + │ stack update │ + │ │ + │ Initial back stack update + │ │ + │ Suspend & unbind txA ◄───────────────────┤ + │ Navigation lease: B │ + │ Published data: B │ + │ Scope transaction: txB │ + │ (rollback point) │ + │ │ + │ ON_RESUME + │ │ + │ B eligible for restoration ◄─────────────┤ + │ │ +ON_STOP │ + │ │ + ├── retain txA; timers continue │ + ├────────────────────────► A no longer eligible for restoration │ + │ │ +ON_DESTROY │ + │ │ + ├── finish retained txA if unfinished │ + └────────────────────────► A no longer tracked │ + ON_PAUSE + │ + Navigation lease: B (no other resumed ◄─┤ + nav root) │ + │ + ON_STOP + │ + Navigation lease: B (no other resumed ◄─┤ + nav root); B keeps recording │ + navigation │ + B no longer eligible for restoration │ + │ + ON_DESTROY + │ + Finish txB if unfinished; ◄──────────────┤ + unbind if still bound │ + Clear B's remaining screen/back stack │ + Retain recorded nav events │ + Navigation lease: none │ + ▼ + +Alternative at rollback point: B disposes before A stops + Unbind txB ◄─────────────── dispose B ───┤ + Navigation lease: A │ + Republish A's staged data │ + Restore txA if unfinished, else start a │ + new txA; bind it if the scope is free │ + Finish txB if unfinished │ +``` + +### Non-candidate roots and lease withdrawal + +An Activity or Fragment without a `SentryNavEffect` (aka, a "non-candidate root") can't acquire the lease. When one replaces the +leaseholder, the coordinator "withdraws" the lease instead, i.e., it unpublishes the leaseholder's nav state without handing off the lease, +leaving the transaction unbound but running until the leaseholder resumes. + +Non-candidate roots never register, so the coordinator infers their presence from either of two signals: + +- another Activity is created or resumed while the leaseholder isn't resumed, unless the resumed + Activity is itself a nav root, which takes the lease when it resumes; or + +- the leaseholder pauses while its host Activity stays resumed (e.g., a ViewPager2 swipe). (Note + that an Activity pauses before its Fragments do when the Activity is backgrounded or covered.) + +**Limitations**: Leaseholders whose host Activity is unknown are never withdrawn. Fragments that cover the leaseholder without pausing it +(e.g., dialogs) go undetected. These two signals are deliberately the only ones: other surfaces that cover a leaseholder without pausing it +(e.g., bottom sheets or Compose dialogs) aren't detected, and shouldn't be by adding signals here. + +**Limitation (below API 29)**: An Activity created over the leaseholder doesn't get its `ui.load` transaction bound to the scope. There's no +`onActivityPreCreated` below API 29, so the lease is withdrawn only after `ActivityLifecycleIntegration` has tried to bind the Activity's +`ui.load` transaction and found the leaseholder's nav transaction in the scope's transaction slot. The integration doesn't try again, so its +`ui.load` transaction stays unbound, as it did before withdrawal existed. Withdrawal still keeps the Activity's errors and spans from being +attributed to the leaseholder: spans the Activity produces attach to no transaction until one is bound (e.g., the nav transaction for the +first destination of the Activity's own `SentryNavEffect`, if it has one). Closing this gap would take a change to +`ActivityLifecycleIntegration` that affects every app, so it's deliberately left open. + +As a result, an Activity with its own `SentryNavEffect` gets a different transaction bound for its spans depending on the API level. On +API 29+, its `ui.load` transaction is bound, and its first destination's nav transaction isn't started because the slot is taken. Below +API 29, when the leaseholder's nav transaction held the slot as the Activity was created, its first destination's nav transaction is bound +instead. Either way, `ActivityLifecycleIntegration` still sends the `ui.load` transaction, including its TTID and TTFD spans. Only the +parent of auto-instrumented spans (e.g., HTTP or database spans) differs. + +### Returning to a nav root + +A nav root is "returned to" when its candidate acquires the lease at any time other than on its first back stack update, e.g., when the +Activity covering it closes, or when the user swipes back to its ViewPager2 page. Spans produced on return (e.g., by work the nav root +resumes) need a nav transaction to attach to: + +- if the candidate's nav transaction is still active, that transaction is bound again, which + keeps the spans with the transaction that already holds the destination's earlier spans; and + +- if the candidate's nav transaction is finished (e.g., the transaction timed out while another + nav root held the lease, or it never started because another transaction held the scope's + transaction slot), a new nav transaction is started for the current destination. + +Either way, the transaction is bound only if the scope's transaction slot is free (see `StagedNavTransaction`). Rebinding and starting both +happen when the candidate publishes (`INavStatePublisher.publishTo`) its nav state, so the coordinator needn't tell a return from a first +acquisition: on its first back stack update, a candidate has no destination to start a transaction for yet. + +When the user returns by closing an Activity, that Activity's `ui.load` transaction may still be running and hold the slot. It normally +leaves the slot when the closed Activity is destroyed, which happens after the nav root has resumed. If the Activity is destroyed within +`UI_LOAD_RETRY_WINDOW_SECONDS` of the blocked attempt, binding the nav root's transaction is retried once (see `onAnyActivityDestroyed`). +Otherwise, the nav root goes without a bound nav transaction until its next navigation or return. + +Only the current leaseholder is asked to retry when an Activity is destroyed. Its publisher checks whether the blocked `ui.load` has left +the slot and whether the retry window is still open. A leaseholder that loses or withdraws its lease forgets the blocked publication. + +The retry has three gaps: + +- A `ui.action` transaction started by the gesture that caused the return (e.g., a ViewPager2 swipe or an in-app back button) can block the + nav transaction. Only Activity `ui.load` transactions trigger this retry. +- Spans produced between the nav root's resume and the closed Activity's destruction may attach to the closed Activity's `ui.load`. +- An Activity left without being destroyed (e.g., when another Activity is reordered to the front) triggers no retry. + +Unbinding a finishing Activity's `ui.load` when it pauses would close the last two gaps, but would change `ActivityLifecycleIntegration` +for every app. Giving navigation priority over `ui.action` is an SDK-wide scope-slot policy decision shared with other integrations. + +A nav root that's destroyed and recreated after losing the lease (e.g., on a configuration change) isn't returned to: it registers anew and +gets a transaction on its first back stack update. See [#6454](https://github.com/getsentry/sentry-java/issues/6454). + +Bringing the app back to the foreground isn't a return either: the leaseholder keeps the lease while the app is in the background (see +`stopCandidate`), so it starts no new nav transaction when it resumes. This matches the rest of the SDK, which starts no transaction when an +existing Activity comes back to the foreground. + +### Android ordering assumptions + +Besides the callback ordering `NavActivityWatcher` relies on, `NavLeaseCoordinator` relies on the following sequences, which Android doesn't +document but AOSP and androidx have historically upheld: + +- An Activity's `onActivityResumed` callbacks run before its `Lifecycle` dispatches + `ON_RESUME` (see `isActivityNavRoot`). + +- An Activity's `Lifecycle` dispatches `ON_PAUSE` before its Fragments' + lifecycles do. androidx's `ReportFragment` and `FragmentActivity` ensure this, not the + platform. + +- A visible Activity that finishes is destroyed once the Activity that replaces it reports idle, + or when the system's idle timeout fires (see `UI_LOAD_RETRY_WINDOW_SECONDS`). + +Going forward, if an order changes, nav data may be attributed to the wrong nav root, or a nav transaction may go unbound, but nothing would +throw. diff --git a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/StagedNavTransaction.kt b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/StagedNavTransaction.kt index 2851a10481c..d8ec37f45e3 100644 --- a/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/StagedNavTransaction.kt +++ b/sentry-android-navigation3/src/main/kotlin/io/sentry/compose/navigation3/lifecycle/StagedNavTransaction.kt @@ -4,152 +4,212 @@ import io.sentry.IScope import io.sentry.IScopes import io.sentry.ITransaction import io.sentry.SentryLevel -import io.sentry.TransactionContext -import io.sentry.TransactionOptions +import io.sentry.SpanStatus +import io.sentry.time.Deadline +import io.sentry.time.MonotonicTicker +import java.lang.ref.WeakReference +import java.util.concurrent.TimeUnit + +/** + * The origin of the `ui.load` transactions `ActivityLifecycleIntegration` starts for Activities. + * + * Mirrors `ActivityLifecycleIntegration.TRACE_ORIGIN`, which isn't public. + */ +internal const val ACTIVITY_UI_LOAD_ORIGIN: String = "auto.ui.activity" + +/** + * Maximum time to retry a nav transaction if an Activity’s `ui.load` transaction blocks its + * publication. + * + * Android usually destroys a closed Activity once the returned-to Activity goes idle, removing its + * `ui.load` transaction from the shared [IScope]. A busy main thread can delay destruction past + * this window; in that case, the return gets no nav transaction until the next navigation. + */ +internal const val UI_LOAD_RETRY_WINDOW_SECONDS: Long = 10 /** * Holds a nav transaction staged for publication to a shared [IScope]. * - * A transaction requested while publishing isn't permitted is [staged][stage] rather than started, - * and starts when it's next [published][publishTo]. That publication is its only chance to start: - * if it can't start then, it's discarded. A started transaction that's [unpublished][unpublishFrom] - * is unbound but keeps running, so that it can be bound again if it's republished while unfinished. - * Once [finished][finish], a transaction is forgotten and never bound again. + * A [staged][stage] request starts a transaction when it's next [published][publishTo], which + * happens right away if the caller holds the nav lease. An [unpublished][unpublishFrom] transaction + * keeps running and can be rebound. [finish] forgets both the transaction and its request. + * + * If a transaction ends on its own, cannot start, or is discarded, its request remains available to + * start a new transaction when the nav root returns. + * + * **Sampling** + * + * Sampled and unsampled transactions behave alike while running. Returning to a nav root reuses its + * unfinished transaction and sampling decision; starting a new transaction on return makes a new + * sampling decision. * - * Starting or publishing a nav transaction never displaces an unfinished transaction bound to the - * scope by someone else (e.g., the host app). + * **Precedence** + * + * Navigation doesn't displace an unfinished transaction already bound to the shared `IScope`. This + * includes `ui.load`, `ui.action`, and host-app transactions. Changing their relative priority + * requires an SDK-wide policy; this class only retries briefly after a closed Activity's `ui.load` + * releases the slot (see [retryPublishIfBlocked]). * * **Thread safety** * * This class is ***not*** thread-safe. Apply the thread safety policy from [NavScopes]. */ -internal class StagedNavTransaction(private val scopes: IScopes) { +@Suppress("TooManyFunctions") +internal class StagedNavTransaction( + private val scopes: IScopes, + private val ticker: MonotonicTicker, +) { /** - * The nav transaction most recently started or staged, unless it has been finished since then. + * The request most recently passed to [stage], whatever became of its transaction. Cleared when + * the nav transaction is [finished][finish] or [forgotten][forget], i.e., when the destination it + * describes is left. + * + * While there's a request but no [transaction], a transaction is started from the request when + * it's next [published][publishTo]: it's staged, or was discarded or blocked from starting. */ - private var navTransaction: NavTransaction? = null + private var request: NavTransactionRequest? = null + + /** The transaction most recently started for [request], unless it has been forgotten since. */ + private var transaction: ITransaction? = null /** - * Starts a nav transaction from [context] and [options] and binds it to [scope], unless another - * unfinished transaction is already bound to `scope`, in which case none is started, as it - * couldn't be bound. Returns `null` if no transaction was started (including when [scopes] - * returned a no-op transaction, e.g., because the SDK is disabled or ignores the transaction's - * origin), in which case the instance's current nav transaction, if any, is kept. + * The most recent [publication][publishTo], if an Activity `ui.load` transaction kept it from + * binding a nav transaction. Cleared when the publication is retried, and when the nav + * transaction is next published, unpublished, finished, or forgotten. * - * **Warning**: [Finish][finish] the current nav transaction before calling this method, as this - * method replaces the current transaction without finishing it. + * See [retryPublishIfBlocked]. */ - fun start( - scope: IScope, - context: TransactionContext, - options: TransactionOptions, - ): NavTransaction? { - if (!scope.isFreeFor(context.name, transaction = null)) { - return null - } - val transaction = - scopes.startTransaction(context, options).takeUnless { it.isNoOp } ?: return null + private var blockedPublication: BlockedPublication? = null - // Record the transaction before binding it: binding notifies the host app's scope observers, - // which can throw, and an unrecorded transaction might never be finished. - val started = NavTransaction.started(transaction) - navTransaction = started - - bind(scope, transaction) - return started + /** + * Stages [request], so that the next [publishTo] starts a transaction for it. + * + * Call [finish] first: staging replaces the current transaction without finishing it. + */ + fun stage(request: NavTransactionRequest) { + this.request = request + transaction = null } /** - * Stages a nav transaction that's started from [context] and [options] when it's - * [published][publishTo], and returns its handle, which records what's set on it in the meantime. + * Updates the saved request for a future start without changing a running transaction. * - * **Warning**: [Finish][finish] the current nav transaction before calling this method, as this - * method replaces the current transaction without finishing it. + * No-ops if no request has been [staged][stage]. */ - fun stage(context: TransactionContext, options: TransactionOptions): NavTransaction = - NavTransaction.deferred(context, options).also { navTransaction = it } + fun updateRequest(request: NavTransactionRequest) { + if (this.request == null) { + return + } + this.request = request + } /** - * Binds the nav transaction to [scope], starting it first if it's staged. A started transaction - * that has finished in the meantime is forgotten and unbound instead. + * Publishes the staged transaction by binding it to [scope], or starts a transaction from the + * staged request if needed. An occupied scope slot leaves the transaction unbound and the request + * available for later publication. * - * If another unfinished transaction is bound to [scope], a started transaction stays unbound, so - * it can be bound the next time it's published. A staged transaction is discarded instead, as it - * is if [scopes] return a no-op transaction for it (see [start]). + * If [canRetry] is true and an Activity's `ui.load` transaction occupies the scope slot, the + * publication can be retried once the `ui.load` transaction leaves the scope (see + * [retryPublishIfBlocked]). */ - fun publishTo(scope: IScope) { - val navTransaction = navTransaction ?: return - val started = navTransaction.transaction - when { - started?.isFinished == true -> { - this.navTransaction = null - unbind(scope, started) - } - started != null -> if (scope.isFreeFor(navTransaction.name, started)) bind(scope, started) - else -> { - val startedNow = - if (scope.isFreeFor(navTransaction.name, transaction = null)) { - navTransaction.start(scopes) - } else { - null - } - if (startedNow != null) { - bind(scope, startedNow) - } else { - this.navTransaction = null - navTransaction.finish(onFinished = {}) - } + fun publishTo(scope: IScope, canRetry: Boolean = true) { + blockedPublication = null + val request = request ?: return + val started = transaction + + if (started != null && !started.isFinished) { + if (scope.isFreeFor(request.name, started)) { + bind(scope, started) + } else if (canRetry) { + blockedPublication = scope.blockedPublicationFor(started) } + return + } + + transaction = null + started?.let { unbind(scope, it) } + // A start declined by the scopes (i.e., a no-op transaction) leaves the slot free, so it isn't + // retried. + if (startAndBind(scope, request) == null && canRetry) { + blockedPublication = scope.blockedPublicationFor(transaction = null) } } /** - * Unbinds the nav transaction from [scope], if it's bound, without finishing it, so it can be - * [published][publishTo] again. + * Retries publication to [scope] after the blocking Activity `ui.load` leaves its slot. Retries + * only within [UI_LOAD_RETRY_WINDOW_SECONDS] of the blocked attempt, and never arms another + * retry. Other blockers do not qualify. */ + fun retryPublishIfBlocked(scope: IScope) { + val blocked = blockedPublication ?: return + if (blocked.retryDeadline.hasPassed()) { + blockedPublication = null + return + } + val uiLoad = blocked.uiLoad.get() + if (uiLoad != null && !uiLoad.isFinished && scope.transaction === uiLoad) { + // The ui.load transaction still holds the slot; wait for it to leave. + return + } + + publishTo(scope, canRetry = false) + } + + /** Unbinds the transaction from [scope] without finishing it, allowing later publication. */ fun unpublishFrom(scope: IScope) { - navTransaction?.transaction?.let { unbind(scope, it) } + blockedPublication = null + transaction?.let { unbind(scope, it) } } /** - * Finishes the nav transaction and unbinds it from [scope], if it's bound. A staged transaction - * is discarded instead. + * Finishes and unbinds the transaction from [scope], or discards it if staged. Uses its current + * status, or [OK][SpanStatus.OK] if unset. Forgets the request in either case. */ fun finish(scope: IScope) { - val navTransaction = navTransaction ?: return + request = null + blockedPublication = null + val transaction = transaction ?: return // Forget the transaction before unbinding it: unbinding notifies the host app's scope // observers, which can throw, and a transaction left behind would be bound again later. - this.navTransaction = null - navTransaction.finish(onFinished = { unbind(scope, it) }) + this.transaction = null + if (!transaction.isFinished) { + transaction.finish(transaction.status ?: SpanStatus.OK) + } + unbind(scope, transaction) } - /** - * Forgets the nav transaction without finishing it, e.g., when there's no scope to unbind it - * from. If started, it will be left to time out. - */ + /** Forgets the transaction and request without finishing or unbinding a started transaction. */ fun forget() { - navTransaction = null + request = null + transaction = null + blockedPublication = null } + /** Whether the slot is empty, holds a finished transaction, or already holds [transaction]. */ + private fun canHold(current: ITransaction?, transaction: ITransaction?): Boolean = + current == null || current.isFinished || current === transaction + /** - * Reports whether the receiver's transaction slot can hold [transaction], or a new transaction - * given `null` (see [canHold]). + * Starts and binds a transaction based on the provided [request] if [scope]'s slot is free. + * + * Returns `null` if the slot is occupied or [scopes] declines the start. */ - private fun IScope.isFreeFor(name: String, transaction: ITransaction?): Boolean { - if (canHold(current = this.transaction, transaction)) { - return true + private fun startAndBind(scope: IScope, request: NavTransactionRequest): ITransaction? { + if (!scope.isFreeFor(request.name, transaction = null)) { + return null } + val transaction = request.start(scopes, publishingScope = scope) ?: return null - scopes.options.logger.log( - SentryLevel.DEBUG, - "Nav3 transaction for route %s is blocked by another active transaction.", - name, - ) - return false + // Record the transaction before binding it: binding notifies the host app's scope observers, + // which can throw, and an unrecorded transaction might never be finished. + this.transaction = transaction + + bind(scope, transaction) + return transaction } - /** Binds [transaction] to [scope] if the scope's transaction slot can hold it (see [canHold]). */ + /** Binds [transaction] if [scope]'s slot is empty, finished, or already holds it. */ private fun bind(scope: IScope, transaction: ITransaction) { scope.withTransaction { current -> if (current !== transaction && canHold(current, transaction)) { @@ -158,13 +218,6 @@ internal class StagedNavTransaction(private val scopes: IScopes) { } } - /** - * Whether a transaction slot holding [current] can hold [transaction], or a new transaction given - * `null`: it's empty, holds a finished transaction, or already holds `transaction`. - */ - private fun canHold(current: ITransaction?, transaction: ITransaction?): Boolean = - current == null || current.isFinished || current === transaction - /** Unbinds [transaction] from [scope] if it's the bound transaction. */ private fun unbind(scope: IScope, transaction: ITransaction) { scope.withTransaction { current -> @@ -173,4 +226,46 @@ internal class StagedNavTransaction(private val scopes: IScopes) { } } } + + /** + * Checks whether this scope can hold [transaction] (or a new one if `null`), logging a blocker. + */ + private fun IScope.isFreeFor(name: String, transaction: ITransaction?): Boolean { + if (canHold(current = this.transaction, transaction)) { + return true + } + + scopes.options.logger.log( + SentryLevel.DEBUG, + "Nav3 transaction for route %s is blocked by another active transaction.", + name, + ) + return false + } + + /** + * Returns a blocker only when this scope holds an Activity `ui.load` instead of [transaction]. + * Pass `null` to check whether it blocks a new transaction. + */ + private fun IScope.blockedPublicationFor(transaction: ITransaction?): BlockedPublication? { + val current = this.transaction ?: return null + if (canHold(current, transaction) || current.spanContext.origin != ACTIVITY_UI_LOAD_ORIGIN) { + return null + } + return BlockedPublication( + uiLoad = WeakReference(current), + retryDeadline = Deadline.after(ticker, UI_LOAD_RETRY_WINDOW_SECONDS, TimeUnit.SECONDS), + ) + } + + /** + * A nav publication blocked by [uiLoad], which may be retried until [retryDeadline]. + * + * The `ui.load` transaction is held weakly, as it's only compared with the scope's transaction. + * (A collected transaction can't be bound to the scope anymore.) + */ + private class BlockedPublication( + val uiLoad: WeakReference, + val retryDeadline: Deadline, + ) } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackConverterTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackConverterTest.kt index 1e332c67bd0..cb31be75fc7 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackConverterTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackConverterTest.kt @@ -37,7 +37,7 @@ class BackStackConverterTest { } private fun getSut( - entryMapper: BackStackEntryMapper = defaultEntryMapper + entryMapper: BackStackEntryMapper = defaultEntryMapper, ): BackStackConverter = BackStackConverter( entryMapper = ForwardingBackStackEntryMapper { entryMapper }, @@ -64,7 +64,7 @@ class BackStackConverterTest { else -> emptyMap() }, ) - } + }, ) val routes = @@ -154,7 +154,7 @@ class BackStackConverterTest { else -> emptyMap() }, ) - } + }, ) val routes = sut.convert(listOf(first, middle, last), RetentionPolicy.KEEP_FIRST) @@ -191,7 +191,7 @@ class BackStackConverterTest { else -> emptyMap() }, ) - } + }, ) val routes = sut.convert(listOf(first, middle, last), RetentionPolicy.KEEP_LAST) @@ -227,7 +227,7 @@ class BackStackConverterTest { else -> emptyMap() }, ) - } + }, ) val routes = sut.convert(listOf(first, middle, last), RetentionPolicy.KEEP_FIRST) @@ -263,7 +263,7 @@ class BackStackConverterTest { else -> emptyMap() }, ) - } + }, ) val routes = sut.convert(listOf(first, middle, last), RetentionPolicy.KEEP_LAST) @@ -313,14 +313,14 @@ class BackStackConverterTest { assertThat(sut.convert(HomeScreen())) .isEqualTo( - NormalizedSentryBackStackEntry(name = "/unknown", arguments = mapOf("userId" to "123")) + NormalizedSentryBackStackEntry(name = "/unknown", arguments = mapOf("userId" to "123")), ) verify(logger) .log( eq(WARNING), eq( "Nav3 backStackEntryMapper returned a blank name while processing this back stack update. " + - "Using /unknown instead." + "Using /unknown instead.", ), ) } @@ -342,13 +342,13 @@ class BackStackConverterTest { NormalizedSentryBackStackEntry( UNKNOWN_ENTRY_NAME, argumentDropReason = ArgumentDropReason.MAPPING_FAILED, - ) + ), ) verify(logger) .log( eq(WARNING), eq( - "Nav3 backStackEntryMapper threw while resolving an entry. Using /unknown without arguments instead." + "Nav3 backStackEntryMapper threw while resolving an entry. Using /unknown without arguments instead.", ), org.mockito.kotlin.any(), ) @@ -378,7 +378,7 @@ class BackStackConverterTest { "bytes" to byteArrayOf(4, 5), ), ) - } + }, ) assertThat(sut.convert(HomeScreen()).arguments) @@ -397,7 +397,7 @@ class BackStackConverterTest { "ints" to listOf(1, 2, 3), "chars" to listOf("a", "b"), "bytes" to listOf(4.toByte(), 5.toByte()), - ) + ), ) } @@ -417,19 +417,19 @@ class BackStackConverterTest { listOf('y', PrivacyMode.PRIVATE), booleanArrayOf(true, false), charArrayOf('q'), - ) - ) + ), + ), ), ) - } + }, ) assertThat(sut.convert(HomeScreen()).arguments) .isEqualTo( mapOf( "nested" to - mapOf("items" to listOf("x", listOf("y", "PRIVATE"), listOf(true, false), listOf("q"))) - ) + mapOf("items" to listOf("x", listOf("y", "PRIVATE"), listOf(true, false), listOf("q"))), + ), ) } @@ -461,7 +461,7 @@ class BackStackConverterTest { else -> emptyMap() }, ) - } + }, ) sut.convert(listOf(HomeScreen(), ProfileScreen("123")), RetentionPolicy.KEEP_FIRST) @@ -473,7 +473,7 @@ class BackStackConverterTest { "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." + "for reliable results.", ), eq("OpaqueValue"), ) @@ -499,7 +499,7 @@ class BackStackConverterTest { "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." + "for reliable results.", ), eq("OpaqueValue"), ) @@ -608,7 +608,7 @@ class BackStackConverterTest { else -> emptyMap() }, ) - } + }, ) val routes = @@ -638,7 +638,7 @@ class BackStackConverterTest { mapOf( "entry" to "/HomeScreen", "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "max_argument_count_exceeded"), - ) + ), ) } } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt index d331afabe69..df7c9512532 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/BackStackObserverTest.kt @@ -21,6 +21,7 @@ import io.sentry.TransactionOptions import io.sentry.compose.navigation3.ArgumentDropReason.Companion.ARGUMENT_DROP_REASON_KEY import io.sentry.compose.navigation3.lifecycle.NAVIGATION_CONTEXT_KEY import io.sentry.compose.navigation3.lifecycle.NavLeaseCoordinator +import io.sentry.compose.navigation3.lifecycle.NavRootInfo import io.sentry.compose.navigation3.lifecycle.NavScopes import io.sentry.protocol.App import io.sentry.protocol.TransactionNameSource @@ -62,6 +63,9 @@ class BackStackObserverTest { val breadcrumbHints = mutableListOf() val startedTransactions = mutableListOf() + /** The [NavScopes] passed to the observer created by [getSut]. */ + lateinit var navScopes: NavScopes + init { whenever(scopes.options).thenReturn(scope.options) whenever(scopes.getSpan()).thenAnswer { scope.span } @@ -94,9 +98,10 @@ class BackStackObserverTest { entryMapper: BackStackEntryMapper = defaultEntryMapper, ): BackStackObserver { scope.options.isEnableScreenTracking = config.enableScreenTracking + navScopes = leaseholderNavScopes() return BackStackObserver( - scopes = leaseholderNavScopes(), + scopes = navScopes, options = SentryNavOptions { enableNavigationBreadcrumbs = config.enableNavigationBreadcrumbs @@ -119,7 +124,7 @@ class BackStackObserverTest { LifecycleRegistry.createUnsafe(this).apply { currentState = Lifecycle.State.RESUMED } } return NavScopes(scopes, NavLeaseCoordinator()).apply { - attach(owner.lifecycle) + attach(NavRootInfo(owner.lifecycle, activity = null)) // The sole resumed owner's first update acquires the lease, which it then keeps. onBackStackUpdate() } @@ -204,7 +209,7 @@ class BackStackObserverTest { else -> emptyMap() }, ) - } + }, ) sut.onBackStackChanged(listOf(HomeScreen(), previousProfile)) @@ -264,7 +269,7 @@ class BackStackObserverTest { val fixture = Fixture() val sut = fixture.getSut( - config = ObserverConfig(captureBackStack = true, maxCapturedBackStackEntries = 2) + config = ObserverConfig(captureBackStack = true, maxCapturedBackStackEntries = 2), ) sut.onBackStackChanged(listOf(HomeScreen(), ProfileScreen("123"), SettingsScreen("privacy"))) @@ -301,7 +306,7 @@ class BackStackObserverTest { "entry" to "/HomeScreen", "entry_arguments" to mapOf(ARGUMENT_DROP_REASON_KEY to "max_argument_count_exceeded"), ), - ) + ), ) assertThat(fixture.startedTransactions.single().getData("arguments")) .isEqualTo(mapOf("userId" to "123")) @@ -326,7 +331,7 @@ class BackStackObserverTest { mapOf("entry" to "/ProfileScreen"), mapOf("entry" to "/SettingsScreen"), mapOf("entry" to "/HomeScreen"), - ) + ), ) } @@ -357,7 +362,7 @@ class BackStackObserverTest { val fixture = Fixture() val sut = fixture.getSut( - config = ObserverConfig(captureBackStack = true, maxCapturedBackStackEntries = 0) + config = ObserverConfig(captureBackStack = true, maxCapturedBackStackEntries = 0), ) fixture.scope.setContexts( NAVIGATION_CONTEXT_KEY, @@ -445,7 +450,7 @@ class BackStackObserverTest { else -> emptyMap() }, ) - } + }, ) sut.onBackStackChanged(listOf(home, profile)) @@ -486,7 +491,7 @@ class BackStackObserverTest { listOf( mapOf("entry" to "/ProfileScreen", "entry_arguments" to mapOf("userId" to "123")), mapOf("entry" to "/HomeScreen"), - ) + ), ) assertThat(fixture.scope.transaction).isSameInstanceAs(transaction) } @@ -501,7 +506,7 @@ class BackStackObserverTest { fixture.scopes.startTransaction( any(), transactionOptionsCaptor.capture(), - ) + ), ) .thenAnswer { val transactionContext = it.arguments[0] as TransactionContext @@ -651,9 +656,9 @@ class BackStackObserverTest { is CartScreen -> error("throwing in order to simulate a buggy entry mapper") is SettingsScreen -> "settings" else -> error("unknown entry: $entry") - } + }, ) - } + }, ) // Navigate to the home screen and verify that a transaction has started and related Sentry data @@ -688,7 +693,7 @@ class BackStackObserverTest { listOf( mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), mapOf("entry" to "/home"), - ) + ), ) // Navigate to the cart screen and verify the later failure is also recorded as /unknown rather @@ -724,7 +729,7 @@ class BackStackObserverTest { ), mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), mapOf("entry" to "/home"), - ) + ), ) // Navigate to the settings screen and verify a new /settings transaction is started and Sentry @@ -759,7 +764,7 @@ class BackStackObserverTest { ), mapOf("entry" to NormalizedSentryBackStackEntry.UNKNOWN_ENTRY_NAME), mapOf("entry" to "/home"), - ) + ), ) } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserverTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserverTest.kt index cf653c23e31..d36d46d814b 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserverTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/CoordinatedBackStackObserverTest.kt @@ -13,11 +13,14 @@ import io.sentry.Scope import io.sentry.ScopeCallback import io.sentry.SentryOptions import io.sentry.SentryTracer +import io.sentry.SpanContext import io.sentry.TransactionContext import io.sentry.TransactionOptions -import io.sentry.compose.navigation3.lifecycle.LeasedNavState +import io.sentry.compose.navigation3.lifecycle.INavStatePublisher import io.sentry.compose.navigation3.lifecycle.NAVIGATION_CONTEXT_KEY import io.sentry.compose.navigation3.lifecycle.NavLeaseCoordinator +import io.sentry.compose.navigation3.lifecycle.NavRootInfo +import io.sentry.protocol.TransactionNameSource import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer @@ -86,8 +89,8 @@ class CoordinatedBackStackObserverTest { .isEqualTo( mapOf( "Back Stack" to - listOf(mapOf("entry" to "/PageB", "entry_arguments" to mapOf("page" to "PageB"))) - ) + listOf(mapOf("entry" to "/PageB", "entry_arguments" to mapOf("page" to "PageB"))), + ), ) assertThat(fixture.scope.screen).isEqualTo("/PageB") } @@ -135,7 +138,7 @@ class CoordinatedBackStackObserverTest { val pageA = fixture.getSut(pageALifecycle) val pageB = fixture.getSut(pageBLifecycle) // E.g., the Activity's ui.load transaction, still running while the pager's pages load. - val hostTransaction = mock() + val hostTransaction = hostTransaction() fixture.scope.transaction = hostTransaction pageA.onBackStackChanged(listOf("PageA")) pageB.onBackStackChanged(listOf("PageB")) @@ -149,18 +152,19 @@ class CoordinatedBackStackObserverTest { } @Test - fun `a page swiped to while a host transaction is bound starts no nav transaction when swiped to again`() { + fun `pages whose nav transactions a host transaction blocked start them when swiped to after it finishes`() { val fixture = Fixture() val pageALifecycle = fixture.resumedLifecycle() val pageBLifecycle = fixture.resumedLifecycle().apply { currentState = Lifecycle.State.STARTED } val pageA = fixture.getSut(pageALifecycle) val pageB = fixture.getSut(pageBLifecycle) - val hostTransaction = mock() + val hostTransaction = hostTransaction() fixture.scope.transaction = hostTransaction pageA.onBackStackChanged(listOf("PageA")) pageB.onBackStackChanged(listOf("PageB")) pageBLifecycle.currentState = Lifecycle.State.RESUMED pageALifecycle.currentState = Lifecycle.State.STARTED + check(fixture.startedTransactions.isEmpty()) whenever(hostTransaction.isFinished).thenReturn(true) // Swipe back to page A, then to page B again. @@ -169,9 +173,12 @@ class CoordinatedBackStackObserverTest { pageBLifecycle.currentState = Lifecycle.State.RESUMED pageALifecycle.currentState = Lifecycle.State.STARTED - // As with page A, which navigated while the host transaction was bound, page B's destination - // gets no nav transaction: it couldn't start one when it first got the nav lease. - assertThat(fixture.startedTransactions).isEmpty() + // Neither page could start a nav transaction while the host transaction was bound, so each + // starts one when it's returned to. + assertThat(fixture.startedTransactions.map { it.name }) + .containsExactly("/PageA", "/PageB") + .inOrder() + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/PageB")) assertThat(fixture.scope.screen).isEqualTo("/PageB") } @@ -220,7 +227,7 @@ class CoordinatedBackStackObserverTest { } @Test - fun `swiping back to a page whose nav transaction finished starts no nav transaction`() { + fun `swiping back to a page whose nav transaction finished starts a new nav transaction for it`() { val fixture = Fixture() val pageALifecycle = fixture.resumedLifecycle() val pageBLifecycle = fixture.resumedLifecycle().apply { currentState = Lifecycle.State.STARTED } @@ -236,11 +243,118 @@ class CoordinatedBackStackObserverTest { pageALifecycle.currentState = Lifecycle.State.RESUMED pageBLifecycle.currentState = Lifecycle.State.STARTED + assertThat(fixture.startedTransactions.map { it.name }) + .containsExactly("/PageA", "/PageB", "/PageA") + .inOrder() + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransactions.last()) + assertThat(fixture.scope.screen).isEqualTo("/PageA") + assertThat(fixture.breadcrumbs.map { it.data["to"] }) + .containsExactly("/PageA", "/PageB") + .inOrder() + } + + @Test + fun `the new nav transaction started when swiping back to a page reflects the page's nav data`() { + val fixture = Fixture() + val pageALifecycle = fixture.resumedLifecycle() + val pageBLifecycle = fixture.resumedLifecycle().apply { currentState = Lifecycle.State.STARTED } + val pageA = fixture.getSut(pageALifecycle, arguments = { mapOf("page" to it) }) + val pageB = fixture.getSut(pageBLifecycle) + pageA.onBackStackChanged(listOf("Home", "PageA")) + fixture.startedTransaction("/PageA").finish() + pageB.onBackStackChanged(listOf("PageB")) + pageBLifecycle.currentState = Lifecycle.State.RESUMED + pageALifecycle.currentState = Lifecycle.State.STARTED + + pageALifecycle.currentState = Lifecycle.State.RESUMED + pageBLifecycle.currentState = Lifecycle.State.STARTED + + val restarted = fixture.startedTransactions.last() + assertThat(restarted.name).isEqualTo("/PageA") + assertThat(restarted.transactionNameSource).isEqualTo(TransactionNameSource.ROUTE) + assertThat(restarted.operation).isEqualTo("navigation") + assertThat(restarted.spanContext.origin).isEqualTo("auto.navigation.nav3") + assertThat(restarted.getData("arguments")).isEqualTo(mapOf("page" to "PageA")) + assertThat(restarted.contexts.app?.viewNames).containsExactly("/PageA") + assertThat(restarted.contexts[NAVIGATION_CONTEXT_KEY]) + .isEqualTo( + mapOf( + "Back Stack" to + listOf( + mapOf("entry" to "/PageA", "entry_arguments" to mapOf("page" to "PageA")), + mapOf("entry" to "/Home", "entry_arguments" to mapOf("page" to "Home")), + ), + ), + ) + } + + @Test + fun `the new nav transaction started when swiping back to a page reflects its updated back stack`() { + val fixture = Fixture() + val pageALifecycle = fixture.resumedLifecycle() + val pageBLifecycle = fixture.resumedLifecycle().apply { currentState = Lifecycle.State.STARTED } + val pageA = fixture.getSut(pageALifecycle) + val pageB = fixture.getSut(pageBLifecycle) + val pageATop = "PageA" + pageA.onBackStackChanged(listOf("Home", pageATop)) + fixture.startedTransaction("/PageA").finish() + pageB.onBackStackChanged(listOf("PageB")) + pageBLifecycle.currentState = Lifecycle.State.RESUMED + pageALifecycle.currentState = Lifecycle.State.STARTED + // Changes the entries below the top while page A is offscreen. + pageA.onBackStackChanged(listOf("Settings", pageATop)) + + pageALifecycle.currentState = Lifecycle.State.RESUMED + pageBLifecycle.currentState = Lifecycle.State.STARTED + + val restarted = fixture.startedTransactions.last() + assertThat(restarted.name).isEqualTo("/PageA") + assertThat(restarted.contexts[NAVIGATION_CONTEXT_KEY]) + .isEqualTo( + mapOf("Back Stack" to listOf(mapOf("entry" to "/PageA"), mapOf("entry" to "/Settings"))), + ) + } + + @Test + fun `swiping back to a page whose back stack became empty starts no nav transaction`() { + val fixture = Fixture() + val pageALifecycle = fixture.resumedLifecycle() + val pageBLifecycle = fixture.resumedLifecycle().apply { currentState = Lifecycle.State.STARTED } + val pageA = fixture.getSut(pageALifecycle) + val pageB = fixture.getSut(pageBLifecycle) + pageA.onBackStackChanged(listOf("PageA")) + pageB.onBackStackChanged(listOf("PageB")) + pageBLifecycle.currentState = Lifecycle.State.RESUMED + pageALifecycle.currentState = Lifecycle.State.STARTED + pageA.onBackStackChanged(emptyList()) + + pageALifecycle.currentState = Lifecycle.State.RESUMED + pageBLifecycle.currentState = Lifecycle.State.STARTED + assertThat(fixture.startedTransactions.map { it.name }) .containsExactly("/PageA", "/PageB") .inOrder() assertThat(fixture.scope.transaction).isNull() - assertThat(fixture.scope.screen).isEqualTo("/PageA") + } + + @Test + fun `with nav transactions disabled, swiping back to a page starts no nav transaction`() { + val fixture = Fixture() + val options = SentryNavOptions { enableNavigationTransactions = false } + val pageALifecycle = fixture.resumedLifecycle() + val pageBLifecycle = fixture.resumedLifecycle().apply { currentState = Lifecycle.State.STARTED } + val pageA = fixture.getSut(pageALifecycle, options) + val pageB = fixture.getSut(pageBLifecycle, options) + pageA.onBackStackChanged(listOf("PageA")) + pageB.onBackStackChanged(listOf("PageB")) + pageBLifecycle.currentState = Lifecycle.State.RESUMED + pageALifecycle.currentState = Lifecycle.State.STARTED + + pageALifecycle.currentState = Lifecycle.State.RESUMED + pageBLifecycle.currentState = Lifecycle.State.STARTED + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isNull() } @Test @@ -323,7 +437,7 @@ class CoordinatedBackStackObserverTest { tracesSampleRate = 1.0 idleTimeout = null deadlineTimeout = 0 - } + }, ) val coordinator = NavLeaseCoordinator() val startedTransactions = mutableListOf() @@ -360,7 +474,14 @@ class CoordinatedBackStackObserverTest { /** Registers another owner that takes the nav lease and then pauses, keeping the lease. */ fun givenPausedLeaseholder() { val otherLifecycle = resumedLifecycle() - val other = checkNotNull(coordinator.register(otherLifecycle, scopes, NoOpLeasedNavState)) + val other = + checkNotNull( + coordinator.register( + scopes, + NavRootInfo(otherLifecycle, activity = null), + NoOpNavStatePublisher, + ), + ) other.onBackStackUpdate() otherLifecycle.currentState = Lifecycle.State.STARTED check(other.hasLease) @@ -380,7 +501,7 @@ class CoordinatedBackStackObserverTest { }, coordinator = coordinator, ) - .apply { attach(lifecycle) } + .apply { attach(NavRootInfo(lifecycle, activity = null)) } /** * Owners of the lifecycles created by [resumedLifecycle]. `LifecycleRegistry` holds its owner @@ -397,12 +518,18 @@ class CoordinatedBackStackObserverTest { .lifecycle } - /** Nav state for a competing owner that has nothing to publish. */ - private object NoOpLeasedNavState : LeasedNavState { + /** Nav state publisher for a competing nav root that has nothing to publish. */ + private object NoOpNavStatePublisher : INavStatePublisher { override fun publishTo(scope: IScope) = Unit + override fun retryTransactionPublication(scope: IScope) = Unit + override fun unpublishFrom(scope: IScope) = Unit override fun onUnregistered(scope: IScope?) = Unit } } + +/** A transaction the host app bound to the scope, as identified by its manual origin. */ +private fun hostTransaction(): ITransaction = + mock().also { whenever(it.spanContext).thenReturn(SpanContext("host")) } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ForwardingBackStackEntryMapperTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ForwardingBackStackEntryMapperTest.kt index 313b21d53c2..35f1df879ba 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ForwardingBackStackEntryMapperTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/ForwardingBackStackEntryMapperTest.kt @@ -15,11 +15,13 @@ class ForwardingBackStackEntryMapperTest { fun `mapper returns name and arguments when present`() { val screen = ProfileScreen("123") val sut = - ForwardingBackStackEntryMapper({ - BackStackEntryMapper { entry -> - SentryBackStackEntry("profile-${entry.userId}", mapOf("userId" to entry.userId)) - } - }) + ForwardingBackStackEntryMapper( + { + BackStackEntryMapper { entry -> + SentryBackStackEntry("profile-${entry.userId}", mapOf("userId" to entry.userId)) + } + }, + ) assertThat(sut.map(screen)) .isEqualTo(SentryBackStackEntry("profile-123", mapOf("userId" to "123"))) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt index d5467b10b9a..f430e229c86 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectLifecycleIntegrationTest.kt @@ -27,11 +27,18 @@ import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.google.common.truth.Truth.assertThat import io.sentry.IScope +import io.sentry.IScopes import io.sentry.ISentryClient +import io.sentry.ITransaction import io.sentry.Scope import io.sentry.ScopeType import io.sentry.Scopes -import io.sentry.SentryOptions +import io.sentry.TransactionContext +import io.sentry.TransactionOptions +import io.sentry.android.core.ActivityLifecycleIntegration +import io.sentry.android.core.BuildInfoProvider +import io.sentry.android.core.SentryAndroidOptions +import io.sentry.android.core.performance.AppStartMetrics import io.sentry.compose.navigation3.lifecycle.NAVIGATION_CONTEXT_KEY import io.sentry.compose.navigation3.lifecycle.NavLeaseCoordinator import org.junit.After @@ -58,10 +65,12 @@ import org.robolectric.annotation.Config */ @RunWith(AndroidJUnit4::class) @Config(sdk = [30]) +@Suppress("LargeClass") class SentryNavEffectLifecycleIntegrationTest { @After fun tearDown() { + Fixture.current?.close() Fixture.current = null } @@ -89,6 +98,63 @@ class SentryNavEffectLifecycleIntegrationTest { .inOrder() } + /** + * On API 29+, core's `onActivityPreCreated` callback can run while the previous Activity's Nav3 + * transaction is still bound to the scope. Our Nav3 implementation releases it in its own + * `onActivityPreCreated` callback. Android runs all of those callbacks before + * `onActivityCreated`, when core binds the incoming Activity's `ui.load` transaction, so it takes + * the freed slot. + */ + @Test + fun `an incoming activity binds its own ui load transaction instead of its first nav transaction`() { + val fixture = Fixture.create() + fixture.installActivityLifecycleIntegration(CheckoutActivity::class.java) + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + + home.pause() + Robolectric.buildActivity(CheckoutActivity::class.java).setup() + fixture.idle() + + val uiLoadTransaction = fixture.uiLoadTransactions.single() + assertThat(uiLoadTransaction.operation).isEqualTo("ui.load") + assertThat(fixture.scope.transaction).isSameInstanceAs(uiLoadTransaction) + assertThat(homeTransaction.isFinished).isFalse() + assertThat(fixture.scope.screen).isEqualTo("/Checkout") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Checkout") + } + + /** + * Below API 29, there's no `onActivityPreCreated`, so the outgoing Activity's lease is withdrawn + * from `onActivityCreated` if `ActivityLifecycleIntegration` finds that the scope's transaction + * slot is taken. `ActivityLifecycleIntegration` doesn't try again, so its `ui.load` transaction + * remains unbound. The incoming Activity's first nav transaction takes the freed slot instead (a + * known limitation – see `NavLeaseCoordinator`). + */ + @Test + @Config(sdk = [28]) + fun `below API 29, first nav transaction binds when incoming ui load cannot`() { + val fixture = Fixture.create() + fixture.installActivityLifecycleIntegration(CheckoutActivity::class.java) + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + + home.pause() + Robolectric.buildActivity(CheckoutActivity::class.java).setup() + fixture.idle() + + val uiLoadTransaction = fixture.uiLoadTransactions.single() + assertThat(uiLoadTransaction.isFinished).isFalse() + val checkoutTransaction = requireNotNull(fixture.scope.transaction) + assertThat(checkoutTransaction.name).isEqualTo("/Checkout") + assertThat(checkoutTransaction.operation).isEqualTo("navigation") + assertThat(homeTransaction.isFinished).isFalse() + assertThat(fixture.scope.screen).isEqualTo("/Checkout") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Checkout") + } + @Test fun `an incoming activity's nav data and transaction survive the outgoing activity stopping`() { val fixture = Fixture.create() @@ -185,6 +251,115 @@ class SentryNavEffectLifecycleIntegrationTest { assertThat(fixture.scope.transaction).isSameInstanceAs(homeTransaction) } + @Test + fun `going back to an activity whose nav transaction finished while covered starts a new nav transaction for it`() { + val fixture = Fixture.create() + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + home.pause() + val checkout = Robolectric.buildActivity(CheckoutActivity::class.java).setup() + fixture.idle() + home.stop() + fixture.idle() + homeTransaction.finish() + + checkout.pause() + home.restart() + home.resume() + fixture.idle() + checkout.stop() + checkout.destroy() + fixture.idle() + + assertThat(fixture.scope.screen).isEqualTo("/Home") + assertThat(fixture.scope.transaction?.name).isEqualTo("/Home") + assertThat(fixture.scope.transaction).isNotSameInstanceAs(homeTransaction) + assertThat(fixture.scope.transaction?.isFinished).isFalse() + assertThat(fixture.scope.breadcrumbs.map { it.data["to"] }) + .containsExactly("/Home", "/Checkout") + .inOrder() + } + + /** + * Known limitation: until the closing Activity is destroyed, its unfinished `ui.load` transaction + * keeps the scope's transaction slot, so the Activity returned to has no nav transaction bound + * yet, and spans produced on return attach to the closing Activity's `ui.load` instead. + */ + @Test + fun `going back keeps the covering activity's unfinished ui load bound until it's destroyed`() { + val fixture = Fixture.create() + fixture.returnToHomeWhileCheckoutUiLoadIsUnfinished() + val uiLoadTransaction = fixture.uiLoadTransactions.single() + + assertThat(fixture.scope.transaction).isSameInstanceAs(uiLoadTransaction) + assertThat(fixture.scope.screen).isEqualTo("/Home") + } + + @Test + fun `going back during the covering activity's ui load starts a nav transaction once it's destroyed`() { + val fixture = Fixture.create() + val (_, checkout) = fixture.returnToHomeWhileCheckoutUiLoadIsUnfinished() + + checkout.stop() + checkout.destroy() + fixture.idle() + + val restarted = requireNotNull(fixture.scope.transaction) + assertThat(restarted.name).isEqualTo("/Home") + assertThat(restarted.operation).isEqualTo("navigation") + assertThat(fixture.uiLoadTransactions.single().isFinished).isTrue() + assertThat(fixture.scope.screen).isEqualTo("/Home") + } + + /** + * Below API 29, the covering Activity's `ui.load` transaction only binds if the scope's + * transaction slot is free when the Activity is created (see `NavLeaseCoordinator`), e.g., + * because Home's nav transaction has already finished. + */ + @Test + @Config(sdk = [28]) + fun `below API 29, going back during the covering activity's ui load starts a nav transaction once it's destroyed`() { + val fixture = Fixture.create() + fixture.installActivityLifecycleIntegration(CheckoutActivity::class.java) + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + requireNotNull(fixture.scope.transaction).finish() + home.pause() + val checkout = Robolectric.buildActivity(CheckoutActivity::class.java).setup() + fixture.idle() + home.stop() + checkout.pause() + home.restart() + home.resume() + fixture.idle() + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.uiLoadTransactions.single()) + + checkout.stop() + checkout.destroy() + fixture.idle() + + val restarted = requireNotNull(fixture.scope.transaction) + assertThat(restarted.name).isEqualTo("/Home") + assertThat(restarted.operation).isEqualTo("navigation") + assertThat(fixture.scope.screen).isEqualTo("/Home") + } + + @Test + fun `going back during the covering activity's ui load rebinds the unfinished nav transaction once it's destroyed`() { + val fixture = Fixture.create() + val (_, checkout) = + fixture.returnToHomeWhileCheckoutUiLoadIsUnfinished(finishHomeTransaction = false) + val homeTransaction = fixture.homeTransaction + + checkout.stop() + checkout.destroy() + fixture.idle() + + assertThat(fixture.scope.transaction).isSameInstanceAs(homeTransaction) + assertThat(homeTransaction.isFinished).isFalse() + } + // Activity recreation @Test fun `a recreated activity publishes its own nav data and transaction over the destroyed instance's`() { @@ -369,6 +544,31 @@ class SentryNavEffectLifecycleIntegrationTest { } // ViewPager2 pages + + /** + * All supported API levels, because below API 29 `ComponentActivity` reports that it paused from + * `ReportFragment` rather than from `onActivityPrePaused`, which must still precede its Fragments + * pausing. + */ + @Test + @Config(sdk = [28, 29, 30]) + fun `backgrounding a view pager activity keeps the current page's nav data and transaction`() { + val fixture = Fixture.create() + val activity = Robolectric.buildActivity(ViewPagerActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + + activity.pause() + activity.stop() + fixture.idle() + + assertThat(fixture.events).containsAtLeast("ViewPager:ON_PAUSE", "Home:view:ON_PAUSE").inOrder() + assertThat(fixture.scope.screen).isEqualTo("/Home") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Home") + assertThat(fixture.scope.transaction).isSameInstanceAs(homeTransaction) + assertThat(homeTransaction.isFinished).isFalse() + } + @Test fun `a preloaded view pager page does not displace the current page's nav data and transaction`() { val fixture = Fixture.create() @@ -440,7 +640,7 @@ class SentryNavEffectLifecycleIntegrationTest { } @Test - fun `switching back to a view pager page whose nav transaction finished starts no nav transaction`() { + fun `switching back to a view pager page whose nav transaction finished starts a new nav transaction for the page`() { val fixture = Fixture.create() val activity = Robolectric.buildActivity(ViewPagerActivity::class.java).setup() fixture.idle() @@ -452,8 +652,52 @@ class SentryNavEffectLifecycleIntegrationTest { activity.get().viewPager.setCurrentItem(0, false) fixture.idle() - assertThat(fixture.scope.transaction).isNull() + assertThat(fixture.scope.transaction?.name).isEqualTo("/Home") + assertThat(fixture.scope.transaction).isNotSameInstanceAs(homeTransaction) + assertThat(fixture.scope.transaction?.isFinished).isFalse() assertThat(fixture.scope.screen).isEqualTo("/Home") + assertThat(fixture.scope.breadcrumbs.map { it.data["to"] }) + .containsExactly("/Home", "/Checkout") + .inOrder() + } + + /** + * A transaction that isn't sampled is still started and bound, so a return while it's running + * binds it again rather than sampling a new one, just as for a sampled transaction. + */ + @Test + fun `switching back to a view pager page restores its unfinished unsampled nav transaction`() { + val fixture = Fixture.create(tracesSampleRate = 0.0) + val activity = Robolectric.buildActivity(ViewPagerActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + check(homeTransaction.isSampled == false) + activity.get().viewPager.setCurrentItem(1, false) + fixture.idle() + + activity.get().viewPager.setCurrentItem(0, false) + fixture.idle() + + assertThat(fixture.scope.transaction).isSameInstanceAs(homeTransaction) + } + + @Test + fun `switching back to a view pager page whose unsampled nav transaction finished samples a new one`() { + val fixture = Fixture.create(tracesSampleRate = 0.0) + val activity = Robolectric.buildActivity(ViewPagerActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + activity.get().viewPager.setCurrentItem(1, false) + fixture.idle() + homeTransaction.finish() + + activity.get().viewPager.setCurrentItem(0, false) + fixture.idle() + + val restarted = requireNotNull(fixture.scope.transaction) + assertThat(restarted).isNotSameInstanceAs(homeTransaction) + assertThat(restarted.name).isEqualTo("/Home") + assertThat(restarted.isSampled).isFalse() } // Dialogs @@ -539,10 +783,160 @@ class SentryNavEffectLifecycleIntegrationTest { assertThat(homeTransaction.isFinished).isFalse() } - // Screens without an effect + @Test + fun `dismissing a dialog fragment starts a new nav transaction for the still-resumed activity if its own finished`() { + val fixture = Fixture.create() + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + val dialog = PickerDialogFragment() + dialog.show(home.get().supportFragmentManager, "picker") + fixture.idle() + val pickerTransaction = requireNotNull(fixture.scope.transaction) + homeTransaction.finish() + + dialog.dismiss() + fixture.idle() + + assertThat(pickerTransaction.isFinished).isTrue() + assertThat(fixture.scope.transaction?.name).isEqualTo("/Home") + assertThat(fixture.scope.transaction).isNotSameInstanceAs(homeTransaction) + assertThat(fixture.scope.transaction?.isFinished).isFalse() + assertThat(fixture.scope.breadcrumbs.map { it.data["to"] }) + .containsExactly("/Home", "/Picker") + .inOrder() + } + + // Nav roots without a SentryNavEffect + + @Test + fun `swiping to a view pager page without an effect clears the outgoing page's nav data and transaction`() { + val fixture = Fixture.create() + val activity = Robolectric.buildActivity(PlainPageViewPagerActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + fixture.events.clear() + + activity.get().viewPager.setCurrentItem(1, false) + fixture.idle() + + assertThat(fixture.events) + .containsExactly("Home:view:ON_PAUSE", "Plain:view:ON_RESUME") + .inOrder() + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + assertThat(homeTransaction.isFinished).isFalse() + } + + @Test + fun `swiping back to a view pager page from one without an effect restores its nav data and transaction`() { + val fixture = Fixture.create() + val activity = Robolectric.buildActivity(PlainPageViewPagerActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + activity.get().viewPager.setCurrentItem(1, false) + fixture.idle() + + activity.get().viewPager.setCurrentItem(0, false) + fixture.idle() + + assertThat(fixture.scope.screen).isEqualTo("/Home") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Home") + assertThat(fixture.scope.transaction).isSameInstanceAs(homeTransaction) + assertThat(homeTransaction.isFinished).isFalse() + } + + @Test + fun `a view pager page preloaded next to a current page without an effect publishes no nav data or transaction`() { + val fixture = Fixture.create() + + Robolectric.buildActivity(PlainInitialPageViewPagerActivity::class.java).setup() + fixture.idle() + + assertThat(fixture.events) + .containsAtLeast("Plain:view:ON_RESUME", "Home:composed(CREATED)", "Home:view:ON_START") + assertThat(fixture.events).doesNotContain("Home:view:ON_RESUME") + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `swiping from a view pager page without an effect to a preloaded page publishes its nav data and transaction`() { + val fixture = Fixture.create() + val activity = Robolectric.buildActivity(PlainInitialPageViewPagerActivity::class.java).setup() + fixture.idle() + + activity.get().viewPager.setCurrentItem(0, false) + fixture.idle() + + assertThat(fixture.scope.screen).isEqualTo("/Home") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Home") + assertThat(fixture.scope.transaction?.name).isEqualTo("/Home") + } + + @Test + fun `recreating a view pager activity on a page without an effect publishes no nav data or transaction`() { + val fixture = Fixture.create() + val activity = Robolectric.buildActivity(PlainPageViewPagerActivity::class.java).setup() + fixture.idle() + activity.get().viewPager.setCurrentItem(1, false) + fixture.idle() + + activity.recreate() + fixture.idle() + + check(activity.get().viewPager.currentItem == 1) + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `restoring a view pager on a page without an effect after process death publishes no nav data`() { + val savedInstanceState = Bundle() + Fixture.create().run { + val activity = Robolectric.buildActivity(PlainPageViewPagerActivity::class.java).setup() + idle() + activity.get().viewPager.setCurrentItem(1, false) + idle() + activity.pause().stop().saveInstanceState(savedInstanceState).destroy() + idle() + } + + // A new process starts with a new scope and coordinator. + val fixture = Fixture.create() + val activity = + Robolectric.buildActivity(PlainPageViewPagerActivity::class.java).setup(savedInstanceState) + fixture.idle() + + check(activity.get().viewPager.currentItem == 1) + assertThat(fixture.events).contains("Home:composed(STARTED)") + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `recreating a view pager activity on a page with an effect publishes that page's nav data and transaction`() { + val fixture = Fixture.create() + val activity = Robolectric.buildActivity(ViewPagerActivity::class.java).setup() + fixture.idle() + activity.get().viewPager.setCurrentItem(1, false) + fixture.idle() + + activity.recreate() + fixture.idle() + + check(activity.get().viewPager.currentItem == 1) + assertThat(fixture.scope.screen).isEqualTo("/Checkout") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Checkout") + assertThat(fixture.scope.transaction?.name).isEqualTo("/Checkout") + } @Test - fun `an activity without an effect keeps the outgoing activity's nav data and transaction on the scope`() { + fun `an activity without an effect clears a covered activity's nav data and unbinds its unfinished transaction`() { val fixture = Fixture.create() val home = Robolectric.buildActivity(HomeActivity::class.java).setup() fixture.idle() @@ -557,6 +951,221 @@ class SentryNavEffectLifecycleIntegrationTest { assertThat(fixture.events) .containsAtLeast("Home:ON_PAUSE", "Plain:ON_RESUME", "Home:ON_STOP") .inOrder() + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + assertThat(homeTransaction.isFinished).isFalse() + } + + @Test + fun `an activity without an effect clears the nav data and transaction of an activity it only pauses`() { + val fixture = Fixture.create() + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + + home.pause() + Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + + assertThat(fixture.events).doesNotContain("Home:ON_STOP") + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + assertThat(homeTransaction.isFinished).isFalse() + } + + /** + * `ActivityLifecycleIntegration` binds an Activity's `ui.load` transaction when the Activity is + * created, and only if the scope's transaction slot is free. + */ + @Test + fun `an activity without an effect binds its own ui load transaction over a covered activity's nav transaction`() { + val fixture = Fixture.create() + fixture.installActivityLifecycleIntegration(PlainActivity::class.java) + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + + home.pause() + Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + + val uiLoadTransaction = fixture.uiLoadTransactions.single() + assertThat(uiLoadTransaction.operation).isEqualTo("ui.load") + assertThat(fixture.scope.screen).isEqualTo(PlainActivity::class.java.canonicalName) + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isSameInstanceAs(uiLoadTransaction) + assertThat(homeTransaction.isFinished).isFalse() + } + + /** + * Below API 29, there's no `onActivityPreCreated`, so the lease is withdrawn from + * `onActivityCreated`, after `ActivityLifecycleIntegration` has found the scope's transaction + * slot taken. `ActivityLifecycleIntegration` doesn't try again, so its `ui.load` transaction + * stays unbound (a known limitation – see `NavLeaseCoordinator`). The covered Activity's nav data + * and transaction are still removed, so they aren't attributed to the Activity. The screen + * `ActivityLifecycleIntegration` set for the Activity is left in place, as it isn't the covered + * Activity's. + */ + @Test + @Config(sdk = [28]) + fun `below API 29, activity without an effect leaves no transaction bound`() { + val fixture = Fixture.create() + fixture.installActivityLifecycleIntegration(PlainActivity::class.java) + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + + home.pause() + Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + + assertThat(fixture.uiLoadTransactions.single().isFinished).isFalse() + assertThat(fixture.scope.screen).isEqualTo(PlainActivity::class.java.canonicalName) + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + assertThat(homeTransaction.isFinished).isFalse() + } + + @Test + fun `going back to an activity covered by one without an effect restores its nav data and unfinished transaction`() { + val fixture = Fixture.create() + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + home.pause() + val plain = Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + home.stop() + fixture.idle() + + plain.pause() + home.restart() + home.resume() + fixture.idle() + plain.stop() + plain.destroy() + fixture.idle() + + assertThat(fixture.scope.screen).isEqualTo("/Home") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Home") + assertThat(fixture.scope.transaction).isSameInstanceAs(homeTransaction) + assertThat(homeTransaction.isFinished).isFalse() + } + + @Test + fun `going back to an activity covered by one without an effect starts a new nav transaction if its own finished`() { + val fixture = Fixture.create() + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + home.pause() + val plain = Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + home.stop() + fixture.idle() + homeTransaction.finish() + + plain.pause() + home.restart() + home.resume() + fixture.idle() + plain.stop() + plain.destroy() + fixture.idle() + + assertThat(fixture.scope.screen).isEqualTo("/Home") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Home") + assertThat(fixture.scope.transaction?.name).isEqualTo("/Home") + assertThat(fixture.scope.transaction).isNotSameInstanceAs(homeTransaction) + assertThat(fixture.scope.transaction?.isFinished).isFalse() + assertThat(fixture.scope.breadcrumbs.map { it.data["to"] }).containsExactly("/Home") + } + + @Test + fun `navigating while covered by an activity without an effect publishes no nav data or transaction`() { + val fixture = Fixture.create() + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + home.pause() + Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + + fixture.backStack("Home") += "Profile" + fixture.idle() + + assertThat(fixture.scope.breadcrumbs.map { it.data["to"] }) + .containsExactly("/Home", "/Profile") + .inOrder() + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `going back to an activity that navigated while covered publishes the destination's nav data and transaction`() { + val fixture = Fixture.create() + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + home.pause() + val plain = Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + fixture.backStack("Home") += "Profile" + fixture.idle() + + plain.pause() + home.resume() + fixture.idle() + + assertThat(homeTransaction.isFinished).isTrue() + assertThat(fixture.scope.screen).isEqualTo("/Profile") + assertThat(fixture.scope.navigationEntries()).containsExactly("/Profile", "/Home").inOrder() + assertThat(fixture.scope.transaction?.name).isEqualTo("/Profile") + assertThat(fixture.scope.transaction?.isFinished).isFalse() + } + + @Test + fun `an activity without an effect removes a covered fragment's nav data and transaction from the scope`() { + val fixture = Fixture.create() + val host = Robolectric.buildActivity(FragmentHostActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + + host.pause() + Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + host.stop() + fixture.idle() + + assertThat(fixture.events).containsAtLeast("Home:view:ON_PAUSE", "Plain:ON_RESUME").inOrder() + assertThat(fixture.scope.screen).isNull() + assertThat(fixture.scope.navigationEntries()).isNull() + assertThat(fixture.scope.transaction).isNull() + assertThat(homeTransaction.isFinished).isFalse() + } + + @Test + fun `going back to a fragment covered by an activity without an effect restores its nav data and transaction`() { + val fixture = Fixture.create() + val host = Robolectric.buildActivity(FragmentHostActivity::class.java).setup() + fixture.idle() + val homeTransaction = requireNotNull(fixture.scope.transaction) + host.pause() + val plain = Robolectric.buildActivity(PlainActivity::class.java).setup() + fixture.idle() + host.stop() + fixture.idle() + + plain.pause() + host.restart() + host.resume() + fixture.idle() + plain.stop() + plain.destroy() + fixture.idle() + assertThat(fixture.scope.screen).isEqualTo("/Home") assertThat(fixture.scope.navigationEntries()).containsExactly("/Home") assertThat(fixture.scope.transaction).isSameInstanceAs(homeTransaction) @@ -661,10 +1270,13 @@ class SentryNavEffectLifecycleIntegrationTest { } } + /** A [NavEffectActivity] whose SentryNavEffect observes the "Home" back stack. */ internal class HomeActivity : NavEffectActivity("Home") + /** A [NavEffectActivity] whose SentryNavEffect observes the "Checkout" back stack. */ internal class CheckoutActivity : NavEffectActivity("Checkout") + /** An Activity whose content has no SentryNavEffect. */ internal class PlainActivity : FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { @@ -674,6 +1286,7 @@ class SentryNavEffectLifecycleIntegrationTest { } } + /** An Activity with no SentryNavEffect of its own, hosting a [HomeFragment] that has one. */ internal class FragmentHostActivity : FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { @@ -689,7 +1302,15 @@ class SentryNavEffectLifecycleIntegrationTest { } } - internal class ViewPagerActivity : FragmentActivity() { + /** + * An Activity without a SentryNavEffect of its own whose ViewPager2 pages are a [HomeFragment] + * and, by default, a [CheckoutFragment], each with a SentryNavEffect. The page at [initialPage] + * is current when the Activity is created. + */ + internal open class ViewPagerActivity( + private val createSecondPage: () -> Fragment = ::CheckoutFragment, + private val initialPage: Int = 0, + ) : FragmentActivity() { lateinit var viewPager: ViewPager2 @@ -698,23 +1319,43 @@ class SentryNavEffectLifecycleIntegrationTest { lifecycle.addObserver(Fixture.require().eventRecorder("ViewPager")) viewPager = ViewPager2(this).apply { + // An ID lets the ViewPager2 save and restore its current page and pages. + id = VIEW_PAGER_ID // Preload the page next to the current one. FragmentStateAdapter caps a preloaded page // at STARTED and resumes only the current page. offscreenPageLimit = 1 - adapter = PagesAdapter(this@ViewPagerActivity) + adapter = PagesAdapter(this@ViewPagerActivity, createSecondPage) + setCurrentItem(initialPage, false) } setContentView(viewPager) } - private class PagesAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) { + private companion object { + const val VIEW_PAGER_ID = 0x7f0b0001 + } + + private class PagesAdapter( + activity: FragmentActivity, + private val createSecondPage: () -> Fragment, + ) : FragmentStateAdapter(activity) { override fun getItemCount(): Int = 2 override fun createFragment(position: Int): Fragment = - if (position == 0) HomeFragment() else CheckoutFragment() + if (position == 0) HomeFragment() else createSecondPage() } } + /** A [ViewPagerActivity] whose second page has no SentryNavEffect. */ + internal class PlainPageViewPagerActivity : ViewPagerActivity(::PlainFragment) + + /** + * Like [PlainPageViewPagerActivity], but its current page is initially the one without a + * SentryNavEffect, e.g., as after rotating the device on that page. + */ + internal class PlainInitialPageViewPagerActivity : + ViewPagerActivity(::PlainFragment, initialPage = 1) + internal open class NavEffectFragment(private val route: String) : Fragment() { override fun onCreateView( @@ -732,6 +1373,7 @@ class SentryNavEffectLifecycleIntegrationTest { internal class CheckoutFragment : NavEffectFragment("Checkout") + /** A Fragment whose content has no SentryNavEffect. */ internal class PlainFragment : Fragment() { override fun onCreateView( @@ -758,13 +1400,13 @@ class SentryNavEffectLifecycleIntegrationTest { } } - private class Fixture private constructor() { + private class Fixture private constructor(tracesSampleRate: Double) { val options = - SentryOptions().apply { + SentryAndroidOptions().apply { dsn = "http://key@localhost/1" defaultScopeType = ScopeType.CURRENT - setTracesSampleRate(1.0) + setTracesSampleRate(tracesSampleRate) isEnableScreenTracking = true idleTimeout = null deadlineTimeout = 0 @@ -802,6 +1444,73 @@ class SentryNavEffectLifecycleIntegrationTest { events += "$name:$event" } + /** `ui.load` transactions started by [installActivityLifecycleIntegration], in start order. */ + val uiLoadTransactions = mutableListOf() + + /** Home's nav transaction, as set up by [returnToHomeWhileCheckoutUiLoadIsUnfinished]. */ + lateinit var homeTransaction: ITransaction + + /** + * Opens Checkout over Home, binding Checkout's `ui.load` transaction, then returns to Home + * while that `ui.load` transaction is unfinished: Checkout is paused and Home resumed, but + * Checkout isn't stopped or destroyed yet. Finishes Home's nav transaction while Checkout + * covers it unless [finishHomeTransaction] is `false`. + * + * API 29+ only: below API 29, Checkout's `ui.load` transaction can't bind while Home's nav + * transaction holds the scope's transaction slot. + */ + fun returnToHomeWhileCheckoutUiLoadIsUnfinished( + finishHomeTransaction: Boolean = true, + ): Pair, ActivityController> { + installActivityLifecycleIntegration(CheckoutActivity::class.java) + val home = Robolectric.buildActivity(HomeActivity::class.java).setup() + idle() + homeTransaction = requireNotNull(scope.transaction) + home.pause() + val checkout = Robolectric.buildActivity(CheckoutActivity::class.java).setup() + idle() + home.stop() + idle() + if (finishHomeTransaction) { + homeTransaction.finish() + } + + checkout.pause() + home.restart() + home.resume() + idle() + return home to checkout + } + + private var activityLifecycleIntegration: ActivityLifecycleIntegration? = null + + /** + * Installs a real [ActivityLifecycleIntegration] that traces only instances of + * [tracedActivityClass], so that each such Activity gets a `ui.load` transaction that competes + * with nav transactions for the scope's transaction slot as it does in an app. + * + * Call it before building any Activity: the SDK registers the integration at initialization, so + * its callbacks run before those the coordinator registers when the first effect attaches. + * + * Limiting it to [tracedActivityClass] keeps the other Activities' nav transactions bindable, + * as the tests expect. + */ + fun installActivityLifecycleIntegration(tracedActivityClass: Class) { + val application: Application = ApplicationProvider.getApplicationContext() + val integration = + ActivityLifecycleIntegration( + TracedActivityApplication(application, tracedActivityClass), + BuildInfoProvider(options.logger), + ) + integration.register(UiLoadRecordingScopes(scopes, uiLoadTransactions), options) + activityLifecycleIntegration = integration + } + + fun close() { + activityLifecycleIntegration?.close() + AppStartMetrics.getInstance().clear() + } + /** * The host-app setup under test: one `SentryNavEffect` in an Activity's or Fragment's content. */ @@ -820,7 +1529,7 @@ class SentryNavEffectLifecycleIntegrationTest { fun require(): Fixture = checkNotNull(current) { "Fixture.create() was not called" } - fun create(): Fixture { + fun create(tracesSampleRate: Double = 1.0): Fixture { val application: Application = ApplicationProvider.getApplicationContext() val packageManager = shadowOf(application.packageManager) listOf( @@ -829,15 +1538,134 @@ class SentryNavEffectLifecycleIntegrationTest { PlainActivity::class.java, FragmentHostActivity::class.java, ViewPagerActivity::class.java, + PlainPageViewPagerActivity::class.java, + PlainInitialPageViewPagerActivity::class.java, ) .forEach { activityClass: Class -> packageManager.addActivityIfNotPresent( - ComponentName(application.packageName, activityClass.name) + ComponentName(application.packageName, activityClass.name), ) } - return Fixture().also { current = it } + return Fixture(tracesSampleRate).also { current = it } + } + } + } + + /** + * Stands in for [application] when [ActivityLifecycleIntegration] registers its callbacks, and + * relays the application's Activity lifecycle callbacks to it only for instances of + * [tracedActivityClass]. + */ + private class TracedActivityApplication( + private val application: Application, + private val tracedActivityClass: Class, + ) : Application() { + + private val relays = mutableMapOf() + + override fun registerActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks) { + val relay = TracedActivityCallbacks(callback, tracedActivityClass) + relays[callback] = relay + application.registerActivityLifecycleCallbacks(relay) + } + + override fun unregisterActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks) { + relays.remove(callback)?.let { application.unregisterActivityLifecycleCallbacks(it) } + } + } + + /** Relays each callback to [delegate] only for instances of [tracedActivityClass]. */ + @Suppress("TooManyFunctions") + private class TracedActivityCallbacks( + private val delegate: Application.ActivityLifecycleCallbacks, + private val tracedActivityClass: Class, + ) : Application.ActivityLifecycleCallbacks { + + private inline fun relay(activity: Activity, block: () -> Unit) { + if (tracedActivityClass.isInstance(activity)) { + block() } } + + override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) = + relay(activity) { delegate.onActivityPreCreated(activity, savedInstanceState) } + + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = + relay(activity) { delegate.onActivityCreated(activity, savedInstanceState) } + + override fun onActivityPostCreated(activity: Activity, savedInstanceState: Bundle?) = + relay(activity) { delegate.onActivityPostCreated(activity, savedInstanceState) } + + override fun onActivityPreStarted(activity: Activity) = + relay(activity) { delegate.onActivityPreStarted(activity) } + + override fun onActivityStarted(activity: Activity) = + relay(activity) { delegate.onActivityStarted(activity) } + + override fun onActivityPostStarted(activity: Activity) = + relay(activity) { delegate.onActivityPostStarted(activity) } + + override fun onActivityPreResumed(activity: Activity) = + relay(activity) { delegate.onActivityPreResumed(activity) } + + override fun onActivityResumed(activity: Activity) = + relay(activity) { delegate.onActivityResumed(activity) } + + override fun onActivityPostResumed(activity: Activity) = + relay(activity) { delegate.onActivityPostResumed(activity) } + + override fun onActivityPrePaused(activity: Activity) = + relay(activity) { delegate.onActivityPrePaused(activity) } + + override fun onActivityPaused(activity: Activity) = + relay(activity) { delegate.onActivityPaused(activity) } + + override fun onActivityPostPaused(activity: Activity) = + relay(activity) { delegate.onActivityPostPaused(activity) } + + override fun onActivityPreStopped(activity: Activity) = + relay(activity) { delegate.onActivityPreStopped(activity) } + + override fun onActivityStopped(activity: Activity) = + relay(activity) { delegate.onActivityStopped(activity) } + + override fun onActivityPostStopped(activity: Activity) = + relay(activity) { delegate.onActivityPostStopped(activity) } + + override fun onActivityPreSaveInstanceState(activity: Activity, outState: Bundle) = + relay(activity) { delegate.onActivityPreSaveInstanceState(activity, outState) } + + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = + relay(activity) { delegate.onActivitySaveInstanceState(activity, outState) } + + override fun onActivityPostSaveInstanceState(activity: Activity, outState: Bundle) = + relay(activity) { delegate.onActivityPostSaveInstanceState(activity, outState) } + + override fun onActivityPreDestroyed(activity: Activity) = + relay(activity) { delegate.onActivityPreDestroyed(activity) } + + override fun onActivityDestroyed(activity: Activity) = + relay(activity) { delegate.onActivityDestroyed(activity) } + + override fun onActivityPostDestroyed(activity: Activity) = + relay(activity) { delegate.onActivityPostDestroyed(activity) } + } + + /** Records each `ui.load` transaction started through [delegate] in [uiLoadTransactions]. */ + private class UiLoadRecordingScopes( + private val delegate: IScopes, + private val uiLoadTransactions: MutableList, + ) : IScopes by delegate { + + override fun startTransaction( + transactionContext: TransactionContext, + transactionOptions: TransactionOptions, + ): ITransaction = + delegate.startTransaction(transactionContext, transactionOptions).also { + if (transactionContext.operation == "ui.load") { + uiLoadTransactions += it + } + } } private companion object { diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt index 0ce82b832a6..dd4c3b29392 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/SentryNavEffectTest.kt @@ -3,11 +3,13 @@ package io.sentry.compose.navigation3 import android.app.Application import android.content.ComponentName import androidx.activity.ComponentActivity +import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner @@ -62,7 +64,7 @@ class SentryNavEffectTest { val appContext: Application = ApplicationProvider.getApplicationContext() Shadows.shadowOf(appContext.packageManager) .addActivityIfNotPresent( - ComponentName(appContext.packageName, ComponentActivity::class.java.name) + ComponentName(appContext.packageName, ComponentActivity::class.java.name), ) } } @@ -257,7 +259,7 @@ class SentryNavEffectTest { mapOf("entry" to "/ProfileRoute"), mapOf("entry" to "/HomeRoute"), mapOf("entry" to "/HomeRoute"), - ) + ), ) } @@ -359,7 +361,7 @@ class SentryNavEffectTest { mutableStateOf>( BackStackEntryMapper { entry -> SentryBackStackEntry(entry::class.simpleName ?: "") - } + }, ) composeRule.setContent { @@ -397,7 +399,7 @@ class SentryNavEffectTest { mutableStateOf>( BackStackEntryMapper { entry -> SentryBackStackEntry(entry::class.simpleName ?: "unknown") - } + }, ) composeRule.setContent { @@ -466,7 +468,7 @@ class SentryNavEffectTest { listOf( mapOf("entry" to "/ProfileRoute", "entry_arguments" to mapOf("userId" to "123")), mapOf("entry" to "/HomeRoute"), - ) + ), ) } @@ -576,7 +578,7 @@ class SentryNavEffectTest { val owner = NavTestLifecycle() val options = SentryNavOptions() composeRule.setContent { - CompositionLocalProvider(LocalLifecycleOwner provides owner) { + WithoutHostActivity(owner) { SentryNavEffect( backStack = listOf("Home"), backStackEntryMapper = BackStackEntryMapper { SentryBackStackEntry(it) }, @@ -605,7 +607,7 @@ class SentryNavEffectTest { val backStack = mutableStateListOf("Home") val options = SentryNavOptions() composeRule.setContent { - CompositionLocalProvider(LocalLifecycleOwner provides owner) { + WithoutHostActivity(owner) { SentryNavEffect( backStack = backStack, backStackEntryMapper = BackStackEntryMapper { SentryBackStackEntry(it) }, @@ -638,11 +640,11 @@ class SentryNavEffectTest { val options = SentryNavOptions() val mapper = BackStackEntryMapper { SentryBackStackEntry(it) } composeRule.setContent { - CompositionLocalProvider(LocalLifecycleOwner provides ownerA) { + WithoutHostActivity(ownerA) { SentryNavEffect(backStackA, mapper, options, fixture.scopes, fixture.coordinator) } if (showB.value) { - CompositionLocalProvider(LocalLifecycleOwner provides ownerB) { + WithoutHostActivity(ownerB) { SentryNavEffect(listOf("Picker"), mapper, options, fixture.scopes, fixture.coordinator) } } @@ -692,11 +694,11 @@ class SentryNavEffectTest { val options = SentryNavOptions() val mapper = BackStackEntryMapper { SentryBackStackEntry(it) } composeRule.setContent { - CompositionLocalProvider(LocalLifecycleOwner provides beneath) { + WithoutHostActivity(beneath) { SentryNavEffect(listOf("Products"), mapper, options, fixture.scopes, fixture.coordinator) } if (showTranslucent.value) { - CompositionLocalProvider(LocalLifecycleOwner provides translucent) { + WithoutHostActivity(translucent) { SentryNavEffect(listOf("Checkout"), mapper, options, fixture.scopes, fixture.coordinator) } } @@ -734,7 +736,7 @@ class SentryNavEffectTest { val owner = NavTestLifecycle(Lifecycle.State.RESUMED) val options = SentryNavOptions() composeRule.setContent { - CompositionLocalProvider(LocalLifecycleOwner provides owner) { + WithoutHostActivity(owner) { SentryNavEffect( backStack = listOf("Home"), backStackEntryMapper = BackStackEntryMapper { SentryBackStackEntry(it) }, @@ -766,7 +768,7 @@ class SentryNavEffectTest { val owner = mutableStateOf(originalOwner) val options = SentryNavOptions() composeRule.setContent { - CompositionLocalProvider(LocalLifecycleOwner provides owner.value) { + WithoutHostActivity(owner.value) { SentryNavEffect( backStack = listOf("Home"), backStackEntryMapper = BackStackEntryMapper { SentryBackStackEntry(it) }, @@ -794,6 +796,21 @@ class SentryNavEffectTest { } } + /** + * Provides [owner] to [content] without a host Activity. Useful for tests whose owners stand in + * for Activities. Otherwise, the compose rule's Activity, which stays resumed, would be treated + * as the owner's host. Pausing the owner would then withdraw the lease, and an owner that isn't + * resumed yet couldn't acquire it on its first back stack update. + */ + @Composable + private fun WithoutHostActivity(owner: LifecycleOwner, content: @Composable () -> Unit) { + CompositionLocalProvider( + LocalLifecycleOwner provides owner, + LocalContext provides LocalContext.current.applicationContext, + content = content, + ) + } + private fun IScope.navigationBackStack(): List>? { val navigationContext = contexts[NAVIGATION_CONTEXT_KEY] as? Map<*, *> ?: return null diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/FindActivityTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/FindActivityTest.kt new file mode 100644 index 00000000000..1c8853155d1 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/FindActivityTest.kt @@ -0,0 +1,56 @@ +package io.sentry.compose.navigation3.lifecycle + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.view.ContextThemeWrapper +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.robolectric.Robolectric +import org.robolectric.annotation.Config + +@RunWith(AndroidJUnit4::class) +@Config(sdk = [30]) +class FindActivityTest { + + @Test + fun `findActivity() - returns the context when the context is an activity`() { + val activity = Robolectric.buildActivity(Activity::class.java).get() + + val found = activity.findActivity() + + assertThat(found).isSameInstanceAs(activity) + } + + @Test + fun `findActivity() - returns the wrapped activity when the context wraps an activity`() { + val activity = Robolectric.buildActivity(Activity::class.java).get() + val context = ContextWrapper(ContextThemeWrapper(activity, 0)) + + val found = context.findActivity() + + assertThat(found).isSameInstanceAs(activity) + } + + @Test + fun `findActivity() - returns null when the context wraps no activity`() { + val context: Context = ApplicationProvider.getApplicationContext() + + val found = context.findActivity() + + assertThat(found).isNull() + } + + @Test + fun `findActivity() - returns null when the context isn't a context wrapper`() { + val context = mock() + + val found = context.findActivity() + + assertThat(found).isNull() + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavLeaseCoordinatorTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavLeaseCoordinatorTest.kt index 9a521312f68..c30e88fd792 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavLeaseCoordinatorTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavLeaseCoordinatorTest.kt @@ -1,5 +1,8 @@ package io.sentry.compose.navigation3.lifecycle +import android.app.Activity +import android.app.Application +import android.app.Application.ActivityLifecycleCallbacks import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle.State.CREATED import androidx.lifecycle.Lifecycle.State.DESTROYED @@ -8,16 +11,20 @@ import androidx.lifecycle.Lifecycle.State.STARTED import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import com.google.common.truth.Truth.assertThat +import io.sentry.ILogger import io.sentry.IScope import io.sentry.IScopes import io.sentry.Scope import io.sentry.ScopeCallback +import io.sentry.SentryLevel import io.sentry.SentryOptions import org.junit.Assert.assertThrows import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever @Suppress("LargeClass") @@ -32,7 +39,11 @@ class NavLeaseCoordinatorTest { val owner = TestOwner(DESTROYED) val registration = - navLeaseCoordinator.register(owner.lifecycle, fixture.scopes, fixture.navState("owner")) + navLeaseCoordinator.register( + fixture.scopes, + NavRootInfo(owner.lifecycle, activity = null), + fixture.publisher("owner"), + ) assertThat(registration).isNull() assertThat(owner.lifecycle.observerCount).isEqualTo(0) @@ -50,6 +61,44 @@ class NavLeaseCoordinatorTest { assertThat(second.hasLease).isTrue() } + @Test + fun `register() - registers activity lifecycle callbacks with the host activity's application`() { + val fixture = Fixture.create() + + fixture.register("owner", TestOwner(CREATED), host = fixture.hostActivity) + + assertThat(fixture.registeredActivityCallbacks).hasSize(1) + } + + @Test + fun `register() - registers activity lifecycle callbacks only once for several hosted candidates`() { + val fixture = Fixture.create() + fixture.register("first", TestOwner(CREATED), host = fixture.hostActivity) + + fixture.register("second", TestOwner(CREATED), host = fixture.coveringActivity) + + assertThat(fixture.registeredActivityCallbacks).hasSize(1) + } + + @Test + fun `register() - doesn't register activity lifecycle callbacks without a host activity`() { + val fixture = Fixture.create() + + fixture.register("owner", TestOwner(CREATED)) + + assertThat(fixture.registeredActivityCallbacks).isEmpty() + } + + @Test + fun `register() - registers activity lifecycle callbacks for a later host activity if an earlier one has no app`() { + val fixture = Fixture.create() + fixture.register("detached", TestOwner(CREATED), host = fixture.activity(application = null)) + + fixture.register("owner", TestOwner(CREATED), host = fixture.hostActivity) + + assertThat(fixture.registeredActivityCallbacks).hasSize(1) + } + // endregion // region acquiring the nav lease on the first back stack update @@ -214,6 +263,80 @@ class NavLeaseCoordinatorTest { assertThat(registration.hasLease).isTrue() } + @Test + fun `a non-resumed owner doesn't acquire the nav lease on its first update while its host activity is resumed`() { + val fixture = Fixture.create() + val host = fixture.lifecycleOwnerActivity(TestOwner(RESUMED).lifecycle) + val registration = fixture.register("owner", TestOwner(STARTED), host = host) + + registration.onBackStackUpdate() + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.published).isEmpty() + } + + @Test + fun `an owner kept from the nav lease by its resumed host activity acquires it when it resumes`() { + val fixture = Fixture.create() + val host = fixture.lifecycleOwnerActivity(TestOwner(RESUMED).lifecycle) + val owner = TestOwner(STARTED) + val registration = fixture.acquireLease("owner", owner, host = host) + + owner.lifecycle.currentState = RESUMED + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.published).containsExactly("owner") + } + + @Test + fun `a non-resumed owner doesn't take the nav lease from a paused leaseholder while its host activity is resumed`() { + val fixture = Fixture.create() + val host = fixture.lifecycleOwnerActivity(TestOwner(RESUMED).lifecycle) + val incumbentOwner = TestOwner(RESUMED) + val incumbent = fixture.acquireLease("incumbent", incumbentOwner) + incumbentOwner.lifecycle.currentState = STARTED + + fixture.acquireLease("owner", TestOwner(STARTED), host = host) + + assertThat(incumbent.hasLease).isTrue() + assertThat(fixture.published).containsExactly("incumbent") + } + + @Test + fun `a non-resumed owner acquires the nav lease on its first update while its host activity isn't resumed`() { + val fixture = Fixture.create() + val host = fixture.lifecycleOwnerActivity(TestOwner(STARTED).lifecycle) + val registration = fixture.register("owner", TestOwner(STARTED), host = host) + + registration.onBackStackUpdate() + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.published).containsExactly("owner") + } + + @Test + fun `a non-resumed owner acquires the nav lease on its first update if its host activity isn't a lifecycle owner`() { + val fixture = Fixture.create() + val registration = fixture.register("owner", TestOwner(STARTED), host = fixture.hostActivity) + + registration.onBackStackUpdate() + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.published).containsExactly("owner") + } + + @Test + fun `a resumed owner acquires the nav lease on its first back stack update while its host activity is resumed`() { + val fixture = Fixture.create() + val host = fixture.lifecycleOwnerActivity(TestOwner(RESUMED).lifecycle) + val registration = fixture.register("owner", TestOwner(RESUMED), host = host) + + registration.onBackStackUpdate() + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.published).containsExactly("owner") + } + @Test fun `acquiring the nav lease unpublishes the previous publisher's nav state before publishing its own`() { val fixture = Fixture.create() @@ -221,8 +344,8 @@ class NavLeaseCoordinatorTest { fixture.acquireLease( "previous", TestOwner(RESUMED), - navState = - fixture.navState( + publisher = + fixture.publisher( "previous", onPublishTo = { calls += "publish previous" }, onUnpublishFrom = { calls += "unpublish previous" }, @@ -232,7 +355,7 @@ class NavLeaseCoordinatorTest { fixture.register( "incoming", TestOwner(RESUMED), - fixture.navState( + fixture.publisher( "incoming", onPublishTo = { calls += "publish incoming" }, onUnpublishFrom = { calls += "unpublish incoming" }, @@ -288,7 +411,7 @@ class NavLeaseCoordinatorTest { fixture.acquireLease( "first", TestOwner(RESUMED), - navState = fixture.navState("first", onUnpublishFrom = { throw failure }), + publisher = fixture.publisher("first", onUnpublishFrom = { throw failure }), ) val second = fixture.register("second", TestOwner(RESUMED)) @@ -618,6 +741,542 @@ class NavLeaseCoordinatorTest { // endregion + // region lease withdrawal when another Activity covers the leaseholder + + @Test + fun `another activity being pre-created while the leaseholder is paused withdraws the nav lease`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityPreCreated(fixture.coveringActivity, null) + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `another activity being created while the leaseholder is paused withdraws the lease and unpublishes nav state`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityCreated(fixture.coveringActivity, null) + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `another activity being created while the leaseholder is resumed keeps the nav lease`() { + val fixture = Fixture.create() + val registration = + fixture.acquireLease("owner", TestOwner(RESUMED), host = fixture.hostActivity) + + fixture.activityCallbacks.onActivityCreated(fixture.coveringActivity, null) + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `another activity being created while the leaseholder is paused logs the withdrawal`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityCreated(fixture.coveringActivity, null) + + verify(fixture.logger) + .log( + SentryLevel.DEBUG, + "Withdrew the Nav3 lease from a nav root hosted by %s: %s.", + fixture.hostActivity.javaClass.name, + "${fixture.coveringActivity.javaClass.name} was created while the nav root wasn't resumed", + ) + } + + @Test + fun `another activity resuming while the leaseholder is paused withdraws the nav lease`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `another activity resuming while the leaseholder is stopped withdraws the nav lease`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = CREATED + + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `another activity resuming while the leaseholder is resumed keeps the nav lease`() { + val fixture = Fixture.create() + val registration = + fixture.acquireLease("owner", TestOwner(RESUMED), host = fixture.hostActivity) + + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `another activity resuming while the leaseholder is paused logs the withdrawal`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + verify(fixture.logger) + .log( + SentryLevel.DEBUG, + "Withdrew the Nav3 lease from a nav root hosted by %s: %s.", + fixture.hostActivity.javaClass.name, + "${fixture.coveringActivity.javaClass.name} was resumed while the nav root wasn't resumed", + ) + } + + @Test + fun `another activity resuming while the leaseholder is resumed logs nothing`() { + val fixture = Fixture.create() + fixture.acquireLease("owner", TestOwner(RESUMED), host = fixture.hostActivity) + + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + verifyNoInteractions(fixture.logger) + } + + @Test + fun `an activity nav root resuming while the leaseholder is paused takes the nav lease without a withdrawal`() { + val fixture = Fixture.create() + val returnedTo = TestOwner(RESUMED) + val returnedToActivity = fixture.lifecycleOwnerActivity(returnedTo.lifecycle) + val returnedToRegistration = + fixture.acquireLease("returnedTo", returnedTo, host = returnedToActivity) + returnedTo.lifecycle.currentState = STARTED + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + returnedTo.lifecycle.currentState = CREATED + owner.lifecycle.currentState = STARTED + + // Android calls back onActivityResumed before dispatching ON_RESUME to the Activity's + // lifecycle. + fixture.activityCallbacks.onActivityResumed(returnedToActivity) + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.unpublished).containsExactly("returnedTo") + verifyNoInteractions(fixture.logger) + + returnedTo.lifecycle.currentState = RESUMED + + assertThat(returnedToRegistration.hasLease).isTrue() + assertThat(fixture.unpublished).containsExactly("returnedTo", "owner").inOrder() + verifyNoInteractions(fixture.logger) + } + + @Test + fun `an activity nav root that hasn't applied a back stack update resuming withdraws the nav lease`() { + val fixture = Fixture.create() + val returnedTo = TestOwner(CREATED) + val returnedToActivity = fixture.lifecycleOwnerActivity(returnedTo.lifecycle) + fixture.register("returnedTo", returnedTo, host = returnedToActivity) + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityResumed(returnedToActivity) + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `an activity hosting a fragment nav root resuming while the leaseholder is paused withdraws the nav lease`() { + val fixture = Fixture.create() + val activityOwner = TestOwner(RESUMED) + val hostingActivity = fixture.lifecycleOwnerActivity(activityOwner.lifecycle) + // A Fragment page that isn't resumed applies its first update without acquiring the lease. + fixture.acquireLease("page", TestOwner(STARTED), host = hostingActivity) + activityOwner.lifecycle.currentState = STARTED + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityResumed(hostingActivity) + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `the leaseholder's host activity resuming keeps the nav lease`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityResumed(fixture.hostActivity) + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `another activity resuming keeps the nav lease of a leaseholder whose host activity is unknown`() { + val fixture = Fixture.create() + fixture.register("hosted", TestOwner(CREATED), host = fixture.hostActivity) + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `another activity resuming without a leaseholder doesn't unpublish any nav state`() { + val fixture = Fixture.create() + val registration = fixture.register("owner", TestOwner(RESUMED), host = fixture.hostActivity) + + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `withdrawing the nav lease doesn't hand it to another paused owner`() { + val fixture = Fixture.create() + val previousOwner = TestOwner(RESUMED) + val previous = fixture.acquireLease("previous", previousOwner, host = fixture.hostActivity) + previousOwner.lifecycle.currentState = STARTED + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + assertThat(registration.hasLease).isFalse() + assertThat(previous.hasLease).isFalse() + assertThat(fixture.published).containsExactly("previous", "owner").inOrder() + } + + @Test + fun `a withdrawn owner reacquires the nav lease and republishes its nav state when it resumes`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + owner.lifecycle.currentState = RESUMED + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.published).containsExactly("owner", "owner") + } + + @Test + fun `an owner acquiring the nav lease after a withdrawal doesn't unpublish the withdrawn owner's nav state again`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + + val covering = + fixture.acquireLease("covering", TestOwner(CREATED), host = fixture.coveringActivity) + + assertThat(covering.hasLease).isTrue() + assertThat(fixture.published).containsExactly("owner", "covering").inOrder() + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `withdrawing the nav lease without a scope releases it but leaves its nav state published`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + + fixture.withoutScope { + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + } + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `acquiring the nav lease after a withdrawal without a scope unpublishes the withdrawn owner's nav state`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + fixture.withoutScope { + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + } + + fixture.acquireLease("covering", TestOwner(CREATED), host = fixture.coveringActivity) + + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `if unpublishing throws during a withdrawal, the lease is released and the nav state isn't unpublished again`() { + val fixture = Fixture.create() + val failure = IllegalStateException("unpublish failed") + var unpublishAttempts = 0 + val owner = TestOwner(RESUMED) + val registration = + fixture.acquireLease( + "owner", + owner, + publisher = + fixture.publisher( + "owner", + onUnpublishFrom = { + unpublishAttempts++ + throw failure + }, + ), + host = fixture.hostActivity, + ) + owner.lifecycle.currentState = STARTED + + val thrown = + assertThrows(IllegalStateException::class.java) { + fixture.activityCallbacks.onActivityResumed(fixture.coveringActivity) + } + + assertThat(thrown).isSameInstanceAs(failure) + assertThat(registration.hasLease).isFalse() + + val covering = fixture.acquireLease("covering", TestOwner(CREATED)) + + assertThat(covering.hasLease).isTrue() + assertThat(unpublishAttempts).isEqualTo(1) + } + + // endregion + + // region retrying nav transaction publication when an Activity is destroyed + + @Test + fun `another activity being post-destroyed retries the leaseholder's transaction publication`() { + val fixture = Fixture.create() + fixture.acquireLease("owner", TestOwner(RESUMED), host = fixture.hostActivity) + + fixture.activityCallbacks.onActivityPostDestroyed(fixture.coveringActivity) + + assertThat(fixture.retried).containsExactly("owner") + } + + /** Unit tests run against a stubbed `Build.VERSION.SDK_INT` of 0, i.e., below API 29. */ + @Test + fun `below API 29, another activity being destroyed retries the leaseholder's transaction publication`() { + val fixture = Fixture.create() + fixture.acquireLease("owner", TestOwner(RESUMED), host = fixture.hostActivity) + + fixture.activityCallbacks.onActivityDestroyed(fixture.coveringActivity) + + assertThat(fixture.retried).containsExactly("owner") + } + + @Test + fun `the leaseholder's host activity being destroyed doesn't retry its transaction publication`() { + val fixture = Fixture.create() + fixture.acquireLease("owner", TestOwner(RESUMED), host = fixture.hostActivity) + + fixture.activityCallbacks.onActivityPostDestroyed(fixture.hostActivity) + + assertThat(fixture.retried).isEmpty() + } + + @Test + fun `an activity being destroyed without a leaseholder retries no transaction publication`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = fixture.hostActivity) + owner.lifecycle.currentState = STARTED + fixture.activityCallbacks.onActivityCreated(fixture.coveringActivity, null) + + fixture.activityCallbacks.onActivityPostDestroyed(fixture.coveringActivity) + + assertThat(fixture.retried).isEmpty() + } + + @Test + fun `an activity being destroyed without a scope retries no transaction publication`() { + val fixture = Fixture.create() + fixture.acquireLease("owner", TestOwner(RESUMED), host = fixture.hostActivity) + + fixture.withoutScope { + fixture.activityCallbacks.onActivityPostDestroyed(fixture.coveringActivity) + } + + assertThat(fixture.retried).isEmpty() + } + + // endregion + + // region lease withdrawal when the leaseholder pauses within a resumed Activity + + @Test + fun `pausing the leaseholder while its host activity is resumed withdraws the lease and unpublishes nav state`() { + val fixture = Fixture.create() + val host = fixture.lifecycleOwnerActivity(TestOwner(RESUMED).lifecycle) + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = host) + + owner.lifecycle.currentState = STARTED + + assertThat(registration.hasLease).isFalse() + assertThat(fixture.unpublished).containsExactly("owner") + } + + @Test + fun `pausing the leaseholder while its host activity is resumed logs the withdrawal`() { + val fixture = Fixture.create() + val host = fixture.lifecycleOwnerActivity(TestOwner(RESUMED).lifecycle) + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = host) + + owner.lifecycle.currentState = STARTED + + verify(fixture.logger) + .log( + SentryLevel.DEBUG, + "Withdrew the Nav3 lease from a nav root hosted by %s: %s.", + host.javaClass.name, + "the nav root paused while its host Activity stayed resumed", + ) + } + + @Test + fun `pausing the leaseholder while its host activity is paused logs nothing`() { + val fixture = Fixture.create() + val hostOwner = TestOwner(RESUMED) + val host = fixture.lifecycleOwnerActivity(hostOwner.lifecycle) + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = host) + hostOwner.lifecycle.currentState = STARTED + + owner.lifecycle.currentState = STARTED + + verifyNoInteractions(fixture.logger) + } + + @Test + fun `pausing the leaseholder while its host activity is paused keeps the nav lease`() { + val fixture = Fixture.create() + val hostOwner = TestOwner(RESUMED) + val host = fixture.lifecycleOwnerActivity(hostOwner.lifecycle) + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = host) + hostOwner.lifecycle.currentState = STARTED + + owner.lifecycle.currentState = STARTED + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `pausing a leaseholder that observes its host activity's own lifecycle keeps the nav lease`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val host = fixture.lifecycleOwnerActivity(owner.lifecycle) + val registration = fixture.acquireLease("owner", owner, host = host) + + owner.lifecycle.currentState = STARTED + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `pausing the leaseholder keeps the nav lease if its host activity isn't a lifecycle owner`() { + val fixture = Fixture.create() + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = fixture.hostActivity) + + owner.lifecycle.currentState = STARTED + + assertThat(registration.hasLease).isTrue() + assertThat(fixture.unpublished).isEmpty() + } + + @Test + fun `pausing the leaseholder within its resumed host activity hands the nav lease to a resumed owner`() { + val fixture = Fixture.create() + val host = fixture.lifecycleOwnerActivity(TestOwner(RESUMED).lifecycle) + val other = fixture.acquireLease("other", TestOwner(RESUMED), host = host) + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = host) + + owner.lifecycle.currentState = STARTED + + assertThat(other.hasLease).isTrue() + assertThat(fixture.published).containsExactly("other", "owner", "other").inOrder() + } + + @Test + fun `pausing a leaseholder whose host is paused keeps the lease from a resumed owner in the same activity`() { + val fixture = Fixture.create() + val hostOwner = TestOwner(RESUMED) + val host = fixture.lifecycleOwnerActivity(hostOwner.lifecycle) + val other = fixture.acquireLease("other", TestOwner(RESUMED), host = host) + val owner = TestOwner(RESUMED) + val registration = fixture.acquireLease("owner", owner, host = host) + hostOwner.lifecycle.currentState = STARTED + + owner.lifecycle.currentState = STARTED + + assertThat(registration.hasLease).isTrue() + assertThat(other.hasLease).isFalse() + assertThat(fixture.published).containsExactly("other", "owner").inOrder() + } + + @Test + fun `pausing a leaseholder whose host is paused hands the lease to a resumed owner in another activity`() { + val fixture = Fixture.create() + val otherHost = fixture.lifecycleOwnerActivity(TestOwner(RESUMED).lifecycle) + val other = fixture.acquireLease("other", TestOwner(RESUMED), host = otherHost) + val hostOwner = TestOwner(RESUMED) + val host = fixture.lifecycleOwnerActivity(hostOwner.lifecycle) + val owner = TestOwner(RESUMED) + fixture.acquireLease("owner", owner, host = host) + hostOwner.lifecycle.currentState = STARTED + + owner.lifecycle.currentState = STARTED + + assertThat(other.hasLease).isTrue() + assertThat(fixture.published).containsExactly("other", "owner", "other").inOrder() + } + + // endregion + // region unregistering @Test @@ -718,7 +1377,7 @@ class NavLeaseCoordinatorTest { fixture.acquireLease( "owner", owner, - navState = fixture.navState("owner", onUnpublishFrom = { throw failure }), + publisher = fixture.publisher("owner", onUnpublishFrom = { throw failure }), ) val thrown = assertThrows(IllegalStateException::class.java) { registration.dispose() } @@ -755,8 +1414,8 @@ class NavLeaseCoordinatorTest { fixture.acquireLease( "owner", TestOwner(RESUMED), - navState = - fixture.navState( + publisher = + fixture.publisher( "owner", onUnpublishFrom = { calls += "unpublish" }, onUnregistered = { calls += "unregistered" }, @@ -796,7 +1455,7 @@ class NavLeaseCoordinatorTest { fixture.acquireLease( "owner", TestOwner(RESUMED), - navState = fixture.navState("owner", onUnpublishFrom = { throw failure }), + publisher = fixture.publisher("owner", onUnpublishFrom = { throw failure }), ) val thrown = assertThrows(IllegalStateException::class.java) { registration.dispose() } @@ -856,13 +1515,24 @@ class NavLeaseCoordinatorTest { private class Fixture private constructor() { val navLeaseCoordinator = NavLeaseCoordinator() - val scope = Scope(SentryOptions()) + + val logger = mock() + + // Shared by scope and scopes, as in production. + private val options = + SentryOptions().apply { + setLogger(this@Fixture.logger) + isDebug = true + } + + val scope = Scope(options) /** Whether [scopes] runs `configureScope` callbacks; when false, it skips them. */ private var providesScope = true val scopes = mock().also { scopes -> + whenever(scopes.options).thenReturn(options) doAnswer { if (providesScope) { (it.arguments[0] as ScopeCallback).run(scope) @@ -879,6 +1549,9 @@ class NavLeaseCoordinatorTest { /** Names of the nav states unpublished, in the order they were unpublished. */ val unpublished = mutableListOf() + /** Names of the nav states asked to retry publishing their nav transactions, in order. */ + val retried = mutableListOf() + /** Names of the nav states notified of unregistration, with the scope they were given. */ val unregistered = mutableListOf>() @@ -889,35 +1562,85 @@ class NavLeaseCoordinatorTest { private val owners = mutableListOf() /** - * Nav state named [name] that, by default, records its publication in [published], its - * unpublishing in [unpublished], and its unregistration in [unregistered]. + * Publisher named [name] that, by default, records its publication in [published], its + * transaction publication retries in [retried], its unpublishing in [unpublished], and its + * unregistration in [unregistered]. */ - fun navState( + fun publisher( name: String, onPublishTo: (IScope) -> Unit = { published += name }, + onRetryTransactionPublication: (IScope) -> Unit = { retried += name }, onUnpublishFrom: (IScope) -> Unit = { unpublished += name }, onUnregistered: (IScope?) -> Unit = { unregistered += name to it }, - ): LeasedNavState = FakeLeasedNavState(onPublishTo, onUnpublishFrom, onUnregistered) + ): INavStatePublisher = + FakeNavStatePublisher( + onPublishTo, + onRetryTransactionPublication, + onUnpublishFrom, + onUnregistered, + ) - /** Registers a candidate for [owner]'s lifecycle with the nav state named [name]. */ + /** The application of [hostActivity] and [coveringActivity]. */ + val application = mock() + + /** Activity lifecycle callbacks registered with [application], in registration order. */ + val registeredActivityCallbacks = mutableListOf() + + /** The activity lifecycle callbacks the coordinator registered with [application]. */ + val activityCallbacks: ActivityLifecycleCallbacks + get() = registeredActivityCallbacks.single() + + /** An Activity of [application] that hosts candidates. */ + val hostActivity: Activity = activity(application) + + /** Another Activity of [application], which can cover [hostActivity]. */ + val coveringActivity: Activity = activity(application) + + init { + doAnswer { + registeredActivityCallbacks += it.arguments[0] as ActivityLifecycleCallbacks + null + } + .whenever(application) + .registerActivityLifecycleCallbacks(any()) + } + + /** An Activity whose application is [application], or that has none given `null`. */ + fun activity(application: Application?): Activity = + mock().also { whenever(it.application).thenReturn(application) } + + /** An Activity of [application] that's a [LifecycleOwner] of [lifecycle]. */ + fun lifecycleOwnerActivity(lifecycle: Lifecycle): Activity = + mock(extraInterfaces = arrayOf(LifecycleOwner::class)).also { + whenever(it.application).thenReturn(application) + whenever((it as LifecycleOwner).lifecycle).thenReturn(lifecycle) + } + + /** + * Registers a candidate with the publisher named [name] for a nav root whose lifecycle is + * [owner]'s and whose Activity is [host]. + */ fun register( name: String, owner: TestOwner, - navState: LeasedNavState = navState(name), + publisher: INavStatePublisher = publisher(name), + host: Activity? = null, ): NavLeaseRegistration { owners += owner - return checkNotNull(navLeaseCoordinator.register(owner.lifecycle, scopes, navState)) + val rootInfo = NavRootInfo(owner.lifecycle, activity = host) + return checkNotNull(navLeaseCoordinator.register(scopes, rootInfo, publisher)) } /** - * Registers a candidate for [owner]'s lifecycle and applies its first back stack update, which - * acquires the nav lease if the owner's lifecycle permits it. + * Registers a candidate for [owner]'s lifecycle, hosted by [host], and applies its first back + * stack update, which acquires the nav lease if the owner's lifecycle permits it. */ fun acquireLease( name: String, owner: TestOwner, - navState: LeasedNavState = navState(name), - ): NavLeaseRegistration = register(name, owner, navState).also { it.onBackStackUpdate() } + publisher: INavStatePublisher = publisher(name), + host: Activity? = null, + ): NavLeaseRegistration = register(name, owner, publisher, host).also { it.onBackStackUpdate() } /** Runs [block] while `configureScope` skips its callbacks, e.g., as if the SDK is disabled. */ fun withoutScope(block: () -> Unit) { @@ -934,13 +1657,16 @@ class NavLeaseCoordinatorTest { } } - private class FakeLeasedNavState( + private class FakeNavStatePublisher( private val onPublishTo: (IScope) -> Unit, + private val onRetryTransactionPublication: (IScope) -> Unit, private val onUnpublishFrom: (IScope) -> Unit, private val onUnregistered: (IScope?) -> Unit, - ) : LeasedNavState { + ) : INavStatePublisher { override fun publishTo(scope: IScope) = onPublishTo(scope) + override fun retryTransactionPublication(scope: IScope) = onRetryTransactionPublication(scope) + override fun unpublishFrom(scope: IScope) = onUnpublishFrom(scope) override fun onUnregistered(scope: IScope?) = onUnregistered.invoke(scope) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopeTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopeTest.kt index 57be6d68d5d..d294a7ae01e 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopeTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopeTest.kt @@ -13,7 +13,6 @@ import io.sentry.SentryOptions import io.sentry.SpanStatus import io.sentry.TransactionContext import io.sentry.TransactionOptions -import io.sentry.protocol.App import org.junit.Assert.assertThrows import org.junit.Test import org.mockito.kotlin.any @@ -76,29 +75,6 @@ class NavScopeTest { assertThat(fixture.scope.screen).isEqualTo("Profile") } - @Test - fun `getApp() - returns a copy of the scope's app context`() { - val fixture = Fixture.create() - val navScopes = fixture.navScopes - val hostApp = App().apply { appName = "Host" } - fixture.scope.contexts.setApp(hostApp) - - val app = navScopes.withNavScope { it.app } - - assertThat(app?.appName).isEqualTo("Host") - assertThat(app).isNotSameInstanceAs(hostApp) - } - - @Test - fun `getApp() - returns null when the scope has no app context`() { - val fixture = Fixture.create() - val navScopes = fixture.navScopes - - val app = navScopes.withNavScope { it.app } - - assertThat(app).isNull() - } - @Test fun `setNavigationContext() - publishes the navigation context with the nav lease`() { val fixture = Fixture.create(ownsLease = true) @@ -163,9 +139,8 @@ class NavScopeTest { val fixture = Fixture.create(ownsLease = true) val navScopes = fixture.navScopes - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Profile") } + navScopes.withNavScope { it.startNavTransaction("/Profile") } - assertThat(navTransaction).isNotNull() assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransactions.single()) } @@ -176,9 +151,8 @@ class NavScopeTest { val hostTransaction = mock() fixture.scope.transaction = hostTransaction - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Profile") } + navScopes.withNavScope { it.startNavTransaction("/Profile") } - assertThat(navTransaction).isNull() assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) } @@ -190,9 +164,8 @@ class NavScopeTest { fixture.scope.transaction = mock().also { whenever(it.isFinished).thenReturn(true) } - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Profile") } + navScopes.withNavScope { it.startNavTransaction("/Profile") } - assertThat(navTransaction).isNotNull() assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransactions.single()) } @@ -203,9 +176,8 @@ class NavScopeTest { val hostTransaction = mock() fixture.scope.transaction = hostTransaction - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Profile") } + navScopes.withNavScope { it.startNavTransaction("/Profile") } - assertThat(navTransaction).isNotNull() assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) } @@ -229,9 +201,8 @@ class NavScopeTest { val navScopes = fixture.navScopes val otherTransaction = fixture.startAnotherOwnersNavTransaction() - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Profile") } + navScopes.withNavScope { it.startNavTransaction("/Profile") } - assertThat(navTransaction).isNotNull() assertThat(fixture.startedTransactions).containsExactly(otherTransaction) assertThat(fixture.scope.transaction).isSameInstanceAs(otherTransaction) } @@ -243,9 +214,8 @@ class NavScopeTest { val finished = mock().also { whenever(it.isFinished).thenReturn(true) } fixture.scope.transaction = finished - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Profile") } + navScopes.withNavScope { it.startNavTransaction("/Profile") } - assertThat(navTransaction).isNotNull() assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isSameInstanceAs(finished) } @@ -257,9 +227,8 @@ class NavScopeTest { navScopes.withNavScope { it.startNavTransaction("/Profile") } val previous = fixture.startedTransactions.single() - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Settings") } + navScopes.withNavScope { it.startNavTransaction("/Settings") } - assertThat(navTransaction).isNull() verify(previous, never()).finish(any()) assertThat(fixture.startedTransactions).containsExactly(previous) assertThat(fixture.scope.transaction).isSameInstanceAs(previous) @@ -272,9 +241,8 @@ class NavScopeTest { navScopes.withNavScope { it.startNavTransaction("/Profile") } navScopes.withNavScope { it.finishNavTransaction() } - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Settings") } + navScopes.withNavScope { it.startNavTransaction("/Settings") } - assertThat(navTransaction).isNotNull() assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransactions.last()) } @@ -282,13 +250,11 @@ class NavScopeTest { fun `startNavTransaction() - replaces the previous deferred transaction without the nav lease`() { val fixture = Fixture.create() val navScopes = fixture.navScopes - val previous = navScopes.withNavScope { it.startNavTransaction("/Profile") } as NavTransaction + navScopes.withNavScope { it.startNavTransaction("/Profile") } - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Settings") } + navScopes.withNavScope { it.startNavTransaction("/Settings") } fixture.acquireLease() - assertThat(navTransaction).isNotNull() - assertThat(previous.transaction).isNull() assertThat(fixture.startedTransactions.map { it.name }).containsExactly("/Settings") assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransactions.single()) } @@ -303,9 +269,8 @@ class NavScopeTest { fixture.scope.transaction = hostTransaction navScopes.withNavScope { it.finishNavTransaction() } - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Settings") } + navScopes.withNavScope { it.startNavTransaction("/Settings") } - assertThat(navTransaction).isNull() verify(previous).finish(SpanStatus.OK) assertThat(fixture.startedTransactions).containsExactly(previous) assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) @@ -315,15 +280,13 @@ class NavScopeTest { fun `startNavTransaction() - replaces the previous deferred transaction while a host transaction is bound`() { val fixture = Fixture.create() val navScopes = fixture.navScopes - val previous = navScopes.withNavScope { it.startNavTransaction("/Profile") } as NavTransaction + navScopes.withNavScope { it.startNavTransaction("/Profile") } fixture.scope.transaction = mock() - val navTransaction = navScopes.withNavScope { it.startNavTransaction("/Settings") } + navScopes.withNavScope { it.startNavTransaction("/Settings") } fixture.scope.clearTransaction() fixture.acquireLease() - assertThat(navTransaction).isNotNull() - assertThat(previous.transaction).isNull() assertThat(fixture.startedTransactions.map { it.name }).containsExactly("/Settings") assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransactions.single()) } @@ -367,7 +330,7 @@ class NavScopeTest { override fun setTransaction(transaction: String?) { throw ThrowingScopeObserverException() } - } + }, ) assertThrows(ThrowingScopeObserverException::class.java) { @@ -414,8 +377,9 @@ class NavScopeTest { return results.single() } - private fun INavScope.startNavTransaction(name: String): INavTransaction? = - startNavTransaction(TransactionContext(name, "navigation"), TransactionOptions()) + private fun INavScope.startNavTransaction(name: String) { + startNavTransaction(navTransactionRequest(name)) + } /** Thrown by a scope observer, to stand in for one the host app registered. */ private class ThrowingScopeObserverException : RuntimeException() @@ -470,14 +434,16 @@ class NavScopeTest { val other = resumedNavScopes() other.onBackStackUpdate() other.configureScope { - it.startNavTransaction(TransactionContext("/Other", "navigation"), TransactionOptions()) + it.startNavTransaction(navTransactionRequest("/Other")) } return startedTransactions.single { it.name == "/Other" } } private fun resumedNavScopes(): NavScopes = NavScopes(scopes, coordinator).also { - it.attach(TestLifecycleOwner().also(lifecycleOwners::add).lifecycle) + it.attach( + NavRootInfo(TestLifecycleOwner().also(lifecycleOwners::add).lifecycle, activity = null), + ) } companion object { @@ -490,3 +456,9 @@ class NavScopeTest { } } } + +private fun navTransactionRequest(name: String): NavTransactionRequest = + NavTransactionRequest( + name = name, + newOptions = ::TransactionOptions, + ) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopesIntegrationTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopesIntegrationTest.kt index 4f01197a0f7..b77500c7ef5 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopesIntegrationTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopesIntegrationTest.kt @@ -10,7 +10,6 @@ import io.sentry.Scope import io.sentry.ScopeType import io.sentry.Scopes import io.sentry.SentryOptions -import io.sentry.TransactionContext import io.sentry.TransactionOptions import org.junit.Test import org.mockito.kotlin.mock @@ -24,11 +23,11 @@ class NavScopesIntegrationTest { val fixture = Fixture.create() val incumbentOwner = TestLifecycleOwner(Lifecycle.State.RESUMED) val incumbent = fixture.navScopes() - incumbent.attach(incumbentOwner.lifecycle) + incumbent.attach(NavRootInfo(incumbentOwner.lifecycle, activity = null)) incumbent.onBackStackUpdate() val incomingOwner = TestLifecycleOwner(Lifecycle.State.STARTED) val incoming = fixture.navScopes() - incoming.attach(incomingOwner.lifecycle) + incoming.attach(NavRootInfo(incomingOwner.lifecycle, activity = null)) incoming.onBackStackUpdate() val contextBeforeResume = fixture.scope.propagationContext val contextsAtSampling = mutableListOf() @@ -37,7 +36,12 @@ class NavScopesIntegrationTest { 1.0 } incoming.configureScope { - it.startNavTransaction(TransactionContext("/Checkout", "navigation"), TransactionOptions()) + it.startNavTransaction( + NavTransactionRequest( + name = "/Checkout", + newOptions = ::TransactionOptions, + ), + ) } assertThat(contextsAtSampling).isEmpty() assertThat(fixture.scope.propagationContext).isSameInstanceAs(contextBeforeResume) diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopesTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopesTest.kt index 3d03fbca09f..49c856bb062 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopesTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavScopesTest.kt @@ -15,13 +15,16 @@ import io.sentry.ScopeCallback import io.sentry.ScopeObserverAdapter import io.sentry.SentryLevel import io.sentry.SentryOptions +import io.sentry.SpanContext import io.sentry.SpanStatus import io.sentry.TransactionContext import io.sentry.TransactionOptions +import io.sentry.protocol.App import io.sentry.protocol.Contexts import org.junit.Assert.assertThrows import org.junit.Test import org.mockito.kotlin.any +import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.doAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.mock @@ -36,7 +39,7 @@ class NavScopesTest { fun `attach() - lets the first back stack update acquire the nav lease`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle()) + navScopes.attach(NavRootInfo(fixture.lifecycle(), activity = null)) navScopes.applyFirstBackStackUpdate() @@ -48,9 +51,9 @@ class NavScopesTest { val fixture = Fixture.create() val navScopes = fixture.navScopes() val lifecycle = fixture.lifecycle() - navScopes.attach(lifecycle) + navScopes.attach(NavRootInfo(lifecycle, activity = null)) - navScopes.attach(lifecycle) + navScopes.attach(NavRootInfo(lifecycle, activity = null)) assertThat(lifecycle.observerCount).isEqualTo(1) } @@ -61,9 +64,9 @@ class NavScopesTest { val navScopes = fixture.navScopes() val first = TestLifecycleOwner() val second = TestLifecycleOwner() - navScopes.attach(first.lifecycle) + navScopes.attach(NavRootInfo(first.lifecycle, activity = null)) - navScopes.attach(second.lifecycle) + navScopes.attach(NavRootInfo(second.lifecycle, activity = null)) assertThat(first.lifecycle.observerCount).isEqualTo(1) assertThat(second.lifecycle.observerCount).isEqualTo(0) @@ -75,7 +78,7 @@ class NavScopesTest { val navScopes = fixture.navScopes() val lifecycle = fixture.lifecycle(Lifecycle.State.DESTROYED) - navScopes.attach(lifecycle) + navScopes.attach(NavRootInfo(lifecycle, activity = null)) navScopes.applyFirstBackStackUpdate() assertThat(fixture.hasLease(navScopes)).isFalse() @@ -86,12 +89,12 @@ class NavScopesTest { val fixture = Fixture.create() val navScopes = fixture.navScopes() val first = fixture.lifecycle(Lifecycle.State.RESUMED) - navScopes.attach(first) + navScopes.attach(NavRootInfo(first, activity = null)) navScopes.applyFirstBackStackUpdate() first.currentState = Lifecycle.State.DESTROYED val second = fixture.lifecycle(Lifecycle.State.RESUMED) - navScopes.attach(second) + navScopes.attach(NavRootInfo(second, activity = null)) navScopes.applyFirstBackStackUpdate() assertThat(second.observerCount).isEqualTo(1) @@ -113,7 +116,7 @@ class NavScopesTest { val fixture = Fixture.create() val navScopes = fixture.navScopes() val lifecycle = fixture.lifecycle(Lifecycle.State.RESUMED) - navScopes.attach(lifecycle) + navScopes.attach(NavRootInfo(lifecycle, activity = null)) navScopes.applyFirstBackStackUpdate() navScopes.startNavTransaction("/Home") val started = fixture.startedTransaction("/Home") @@ -129,7 +132,7 @@ class NavScopesTest { val fixture = Fixture.create() val navScopes = fixture.navScopes() val lifecycle = fixture.lifecycle(Lifecycle.State.RESUMED) - navScopes.attach(lifecycle) + navScopes.attach(NavRootInfo(lifecycle, activity = null)) navScopes.applyFirstBackStackUpdate() navScopes.startNavTransaction("/Home") val started = fixture.startedTransaction("/Home") @@ -144,10 +147,10 @@ class NavScopesTest { fun `addBreadcrumb() - records breadcrumbs immediately without the nav lease`() { val fixture = Fixture.create() val leaseholder = fixture.navScopes() - leaseholder.attach(TestLifecycleOwner().lifecycle) + leaseholder.attach(NavRootInfo(TestLifecycleOwner().lifecycle, activity = null)) leaseholder.applyFirstBackStackUpdate() val other = fixture.navScopes() - other.attach(TestLifecycleOwner().lifecycle) + other.attach(NavRootInfo(TestLifecycleOwner().lifecycle, activity = null)) val breadcrumb = Breadcrumb() val hint = Hint() @@ -184,7 +187,7 @@ class NavScopesTest { override fun setContexts(contexts: Contexts) { throw failure } - } + }, ) val thrown = assertThrows(IllegalStateException::class.java) { fixture.incoming.dispose() } @@ -197,7 +200,7 @@ class NavScopesTest { fun `dispose() - doesn't finish the nav transaction without a scope`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() navScopes.startNavTransaction("/Home") val started = fixture.startedTransaction("/Home") @@ -215,7 +218,7 @@ class NavScopesTest { navScopes.startNavTransaction("/Home") navScopes.dispose() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() assertThat(fixture.hasLease(navScopes)).isTrue() @@ -226,35 +229,34 @@ class NavScopesTest { fun `startNavTransaction() - starts and binds a nav transaction with the nav lease`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() - val transaction = navScopes.startNavTransaction("/Home") + navScopes.startNavTransaction("/Home") val started = fixture.startedTransaction("/Home") - assertThat(transaction).isNotNull() assertThat(fixture.scope.transaction).isSameInstanceAs(started) } @Test - fun `startNavTransaction() - returns null when the delegate declines with the nav lease`() { + fun `startNavTransaction() - binds no transaction when the delegate declines with the nav lease`() { val fixture = Fixture.create(declinesTransactions = true) val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() - val transaction = navScopes.startNavTransaction("/Home") + navScopes.startNavTransaction("/Home") - assertThat(transaction).isNull() + assertThat(fixture.scope.transaction).isNull() } @Test fun `startNavTransaction() - logs the route when another transaction blocks the start`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() - fixture.scope.transaction = mockTransaction() + fixture.scope.transaction = hostTransaction() navScopes.startNavTransaction("/Home") @@ -266,10 +268,9 @@ class NavScopesTest { val fixture = Fixture.create() val covered = fixture.coveredNavScopes() - val transaction = covered.startNavTransaction("/Result") + covered.startNavTransaction("/Result") assertThat(fixture.hasLease(covered)).isFalse() - assertThat(transaction).isNotNull() assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isNull() } @@ -293,7 +294,7 @@ class NavScopesTest { fun `startNavTransaction() - starts no nav transaction after dispose`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle()) + navScopes.attach(NavRootInfo(fixture.lifecycle(), activity = null)) navScopes.applyFirstBackStackUpdate() navScopes.dispose() @@ -306,7 +307,7 @@ class NavScopesTest { fun `finishNavTransaction() - finishes the started nav transaction`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() navScopes.startNavTransaction("/Home") val started = fixture.startedTransaction("/Home") @@ -320,7 +321,7 @@ class NavScopesTest { fun `finishNavTransaction() - finishes the started nav transaction only once`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() navScopes.startNavTransaction("/Home") val started = fixture.startedTransaction("/Home") @@ -335,9 +336,9 @@ class NavScopesTest { fun `finishNavTransaction() - does nothing without a nav transaction`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() - val hostTransaction = mockTransaction() + val hostTransaction = hostTransaction() fixture.scope.transaction = hostTransaction navScopes.finishNavTransaction() @@ -350,14 +351,13 @@ class NavScopesTest { fun `a nav transaction starts and is bound after the previous one is finished`() { val fixture = Fixture.create() val navScopes = fixture.navScopes() - navScopes.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + navScopes.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) navScopes.applyFirstBackStackUpdate() navScopes.startNavTransaction("/Home") navScopes.finishNavTransaction() - val transaction = navScopes.startNavTransaction("/Profile") + navScopes.startNavTransaction("/Profile") - assertThat(transaction).isNotNull() assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) } @@ -393,7 +393,7 @@ class NavScopesTest { override fun setTransaction(transaction: String?) { if (transaction == "/Home") screensAtBinding += fixture.scope.screen } - } + }, ) fixture.incoming.dispose() @@ -402,7 +402,7 @@ class NavScopesTest { } @Test - fun `a finished nav transaction is discarded when the nav lease is regained`() { + fun `a finished nav transaction is not bound again when the nav lease is regained`() { val fixture = Fixture.create() val covered = fixture.coveredNavScopes(startedRoute = "/Home") val started = fixture.startedTransaction("/Home") @@ -411,7 +411,7 @@ class NavScopesTest { fixture.incoming.dispose() assertThat(fixture.hasLease(covered)).isTrue() - assertThat(fixture.scope.transaction).isNull() + assertThat(fixture.scope.transaction).isNotSameInstanceAs(started) } @Test @@ -424,6 +424,103 @@ class NavScopesTest { fixture.incoming.dispose() assertThat(fixture.hasLease(covered)).isTrue() + assertThat(fixture.startedTransactions).hasSize(1) + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `regaining the nav lease after the nav transaction finished starts a new one for its request`() { + val fixture = Fixture.create() + fixture.coveredNavScopes(startedRoute = "/Home") + val finished = fixture.startedTransaction("/Home") + whenever(finished.isFinished).thenReturn(true) + + fixture.incoming.dispose() + + val restarted = fixture.startedTransactions.last() + assertThat(fixture.startedTransactions).hasSize(2) + assertThat(restarted).isNotSameInstanceAs(finished) + assertThat(restarted.name).isEqualTo("/Home") + assertThat(fixture.scope.transaction).isSameInstanceAs(restarted) + } + + @Test + fun `regaining the nav lease after another transaction blocked the nav transaction starts one for its request`() { + val fixture = Fixture.create() + fixture.scope.transaction = hostTransaction() + fixture.coveredNavScopes(startedRoute = "/Home") + check(fixture.startedTransactions.isEmpty()) + fixture.scope.clearTransaction() + + fixture.incoming.dispose() + + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Home")) + } + + @Test + fun `regaining the nav lease again after a host transaction blocked the deferred transaction starts one`() { + val fixture = Fixture.create() + val covered = fixture.coveredNavScopes() + covered.startNavTransaction("/Result") + val hostTransaction = hostTransaction() + fixture.scope.transaction = hostTransaction + fixture.incoming.dispose() + check(fixture.startedTransactions.isEmpty()) + fixture.scope.clearTransaction() + val nextIncoming = fixture.navScopes() + nextIncoming.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) + nextIncoming.applyFirstBackStackUpdate() + + nextIncoming.dispose() + + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Result")) + } + + @Test + fun `regaining the nav lease with an unfinished nav transaction starts no new one`() { + val fixture = Fixture.create() + fixture.coveredNavScopes(startedRoute = "/Home") + val started = fixture.startedTransaction("/Home") + + fixture.incoming.dispose() + + assertThat(fixture.startedTransactions).containsExactly(started) + } + + @Test + fun `regaining the nav lease with a deferred transaction starts only the deferred one`() { + val fixture = Fixture.create() + val covered = fixture.coveredNavScopes() + covered.startNavTransaction("/Result") + + fixture.incoming.dispose() + + assertThat(fixture.startedTransactions.map { it.name }).containsExactly("/Result") + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Result")) + } + + @Test + fun `regaining the nav lease with a deferred transaction blocked by a host transaction starts none`() { + val fixture = Fixture.create() + val covered = fixture.coveredNavScopes() + covered.startNavTransaction("/Result") + val hostTransaction = hostTransaction() + fixture.scope.transaction = hostTransaction + + fixture.incoming.dispose() + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) + } + + @Test + fun `regaining the nav lease without ever starting a nav transaction starts none`() { + val fixture = Fixture.create() + fixture.coveredNavScopes() + + fixture.incoming.dispose() + + assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isNull() } @@ -439,26 +536,42 @@ class NavScopesTest { } @Test - fun `a deferred transaction receives the data recorded on its handle once it starts`() { + fun `a deferred transaction is started from its request when the nav lease is acquired`() { val fixture = Fixture.create() val covered = fixture.coveredNavScopes() - val transaction = covered.startNavTransaction("/Result") - transaction?.setData("arguments", "id=1") + covered.startNavTransaction( + navTransactionRequest("/Result", data = mapOf("arguments" to "id=1")), + ) fixture.incoming.dispose() verify(fixture.startedTransaction("/Result")).setData("arguments", "id=1") } + @Test + fun `a deferred transaction copies the scope's app context as it is when the nav lease is acquired`() { + val fixture = Fixture.create() + val covered = fixture.coveredNavScopes() + fixture.scope.contexts.setApp(App().apply { appVersion = "1.0.0" }) + covered.startNavTransaction(navTransactionRequest("/Result", viewNames = listOf("/Result"))) + fixture.scope.contexts.setApp(App().apply { appVersion = "2.0.0" }) + + fixture.incoming.dispose() + + val app = fixture.startedTransaction("/Result").contexts.app + assertThat(app?.appVersion).isEqualTo("2.0.0") + assertThat(app?.viewNames).containsExactly("/Result") + } + @Test fun `a preloaded owner's deferred transaction starts when the owner resumes`() { val fixture = Fixture.create() val current = fixture.navScopes() - current.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + current.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) current.applyFirstBackStackUpdate() val preloaded = fixture.navScopes() val preloadedLifecycle = fixture.lifecycle(Lifecycle.State.STARTED) - preloaded.attach(preloadedLifecycle) + preloaded.attach(NavRootInfo(preloadedLifecycle, activity = null)) preloaded.applyFirstBackStackUpdate() preloaded.startNavTransaction("/PageB") check(!fixture.hasLease(preloaded)) @@ -476,7 +589,7 @@ class NavScopesTest { fixture.incoming.dispose() val started = fixture.startedTransaction("/Result") val nextIncoming = fixture.navScopes() - nextIncoming.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + nextIncoming.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) nextIncoming.applyFirstBackStackUpdate() check(fixture.scope.transaction == null) @@ -493,7 +606,7 @@ class NavScopesTest { covered.startNavTransaction("/Result") fixture.incoming.dispose() val nextIncoming = fixture.navScopes() - nextIncoming.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + nextIncoming.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) nextIncoming.applyFirstBackStackUpdate() nextIncoming.dispose() @@ -520,7 +633,7 @@ class NavScopesTest { val fixture = Fixture.create() val covered = fixture.coveredNavScopes() covered.startNavTransaction("/Result") - val hostTransaction = mockTransaction() + val hostTransaction = hostTransaction() fixture.scope.transaction = hostTransaction fixture.incoming.dispose() @@ -534,11 +647,12 @@ class NavScopesTest { val fixture = Fixture.create() val covered = fixture.coveredNavScopes() covered.startNavTransaction("/Result") - fixture.scope.transaction = mockTransaction() + fixture.scope.transaction = hostTransaction() fixture.incoming.dispose() - verify(fixture.logger).log(eq(SentryLevel.DEBUG), any(), eq("/Result")) + // Logged again when the restart for the same request is blocked, too. + verify(fixture.logger, atLeastOnce()).log(eq(SentryLevel.DEBUG), any(), eq("/Result")) } @Test @@ -605,14 +719,14 @@ class NavScopesTest { override fun setContexts(contexts: Contexts) { if (observerThrows) throw failure } - } + }, ) val thrown = assertThrows(IllegalStateException::class.java) { fixture.incoming.dispose() } assertThat(thrown).isSameInstanceAs(failure) check(fixture.startedTransactions.isEmpty()) observerThrows = false val nextIncoming = fixture.navScopes() - nextIncoming.attach(fixture.lifecycle(Lifecycle.State.RESUMED)) + nextIncoming.attach(NavRootInfo(fixture.lifecycle(Lifecycle.State.RESUMED), activity = null)) nextIncoming.applyFirstBackStackUpdate() check(!fixture.hasLease(covered)) @@ -650,12 +764,13 @@ class NavScopesTest { } /** Starts a nav transaction for [name] through the [INavScope] handed out by [NavScopes]. */ - private fun NavScopes.startNavTransaction(name: String): INavTransaction? { - var transaction: INavTransaction? = null - configureScope { - transaction = it.startNavTransaction(TransactionContext(name, "op"), TransactionOptions()) - } - return transaction + private fun NavScopes.startNavTransaction(name: String) { + startNavTransaction(navTransactionRequest(name)) + } + + /** Starts a nav transaction for [request] through the [INavScope] handed out by [NavScopes]. */ + private fun NavScopes.startNavTransaction(request: NavTransactionRequest) { + configureScope { it.startNavTransaction(request) } } /** Finishes the nav transaction through the [INavScope] handed out by [NavScopes]. */ @@ -689,7 +804,7 @@ class NavScopesTest { SentryOptions().apply { setLogger(this@Fixture.logger) isDebug = true - } + }, ) doAnswer { if (isEnabled) { @@ -705,8 +820,12 @@ class NavScopesTest { NoOpTransaction.getInstance() } else { val name = (it.arguments[0] as TransactionContext).name + val contexts = Contexts() mockTransaction() - .also { transaction -> whenever(transaction.name).thenReturn(name) } + .also { transaction -> + whenever(transaction.name).thenReturn(name) + whenever(transaction.contexts).thenReturn(contexts) + } .also(startedTransactions::add) } } @@ -741,15 +860,13 @@ class NavScopesTest { */ fun coveredNavScopes(startedRoute: String? = null): NavScopes { val covered = navScopes() - covered.attach(lifecycle(Lifecycle.State.RESUMED)) + covered.attach(NavRootInfo(lifecycle(Lifecycle.State.RESUMED), activity = null)) covered.onBackStackUpdate() if (startedRoute != null) { - covered.configureScope { - it.startNavTransaction(TransactionContext(startedRoute, "op"), TransactionOptions()) - } + covered.configureScope { it.startNavTransaction(navTransactionRequest(startedRoute)) } } incoming = navScopes() - incoming.attach(lifecycle(Lifecycle.State.RESUMED)) + incoming.attach(NavRootInfo(lifecycle(Lifecycle.State.RESUMED), activity = null)) incoming.onBackStackUpdate() check(!hasLease(covered)) return covered @@ -776,3 +893,19 @@ class NavScopesTest { } } } + +private fun navTransactionRequest( + name: String, + data: Map = emptyMap(), + viewNames: List? = null, +): NavTransactionRequest = + NavTransactionRequest( + name = name, + newOptions = ::TransactionOptions, + data = data, + viewNames = viewNames, + ) + +/** A transaction the host app bound to the scope, as identified by its manual origin. */ +private fun hostTransaction(): ITransaction = + mock().also { whenever(it.spanContext).thenReturn(SpanContext("host")) } diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionRequestTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionRequestTest.kt new file mode 100644 index 00000000000..f7155b67878 --- /dev/null +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionRequestTest.kt @@ -0,0 +1,244 @@ +package io.sentry.compose.navigation3.lifecycle + +import com.google.common.truth.Truth.assertThat +import io.sentry.IScopes +import io.sentry.ITransaction +import io.sentry.NoOpTransaction +import io.sentry.Scope +import io.sentry.SentryOptions +import io.sentry.TransactionContext +import io.sentry.TransactionOptions +import io.sentry.protocol.App +import io.sentry.protocol.Contexts +import io.sentry.protocol.TransactionNameSource +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class NavTransactionRequestTest { + + private val navigationContext = mapOf("backstack" to listOf(mapOf("route" to "/Checkout"))) + + private val scope = Scope(SentryOptions()) + + @Test + fun `forDestination() - reads transaction options when each transaction starts`() { + val fixture = Fixture.create() + val options = SentryOptions().apply { idleTimeout = 100L } + val request = + NavTransactionRequest.forDestination( + name = "/Checkout", + arguments = mapOf("id" to "1"), + contexts = emptyMap(), + viewNames = null, + options = options, + ) + + options.idleTimeout = 200L + request.start(fixture.scopes, scope) + options.idleTimeout = 300L + request.start(fixture.scopes, scope) + + assertThat(fixture.startedOptions.map { it.idleTimeout }).containsExactly(200L, 300L).inOrder() + assertThat(fixture.startedOptions.map { it.origin }) + .containsExactly("auto.navigation.nav3", "auto.navigation.nav3") + verify(fixture.startedTransactions.first()).setData("arguments", mapOf("id" to "1")) + } + + @Test + fun `start() - starts a navigation transaction named by route with the request's name`() { + val fixture = Fixture.create() + val request = fixture.request() + + val transaction = request.start(fixture.scopes, scope) + + val context = fixture.startedContexts.single() + assertThat(transaction).isSameInstanceAs(fixture.startedTransactions.single()) + assertThat(context.name).isEqualTo("/Checkout") + assertThat(context.transactionNameSource).isEqualTo(TransactionNameSource.ROUTE) + assertThat(context.operation).isEqualTo("navigation") + } + + @Test + fun `start() - starts each transaction with a new transaction context`() { + val fixture = Fixture.create() + val request = fixture.request() + + request.start(fixture.scopes, scope) + request.start(fixture.scopes, scope) + + val (first, second) = fixture.startedContexts + assertThat(second).isNotSameInstanceAs(first) + assertThat(second.spanId).isNotEqualTo(first.spanId) + assertThat(second.traceId).isNotEqualTo(first.traceId) + } + + @Test + fun `start() - starts each transaction with new options from the options factory`() { + val fixture = Fixture.create() + val createdOptions = mutableListOf() + val request = fixture.request(newOptions = { TransactionOptions().also(createdOptions::add) }) + + request.start(fixture.scopes, scope) + request.start(fixture.scopes, scope) + + assertThat(createdOptions).hasSize(2) + assertThat(fixture.startedOptions).containsExactlyElementsIn(createdOptions).inOrder() + assertThat(createdOptions[1]).isNotSameInstanceAs(createdOptions[0]) + } + + @Test + fun `start() - sets the request's data on the transaction`() { + val fixture = Fixture.create() + val request = fixture.request(data = mapOf("arguments" to mapOf("id" to "1"))) + + val transaction = request.start(fixture.scopes, scope)!! + + verify(transaction).setData("arguments", mapOf("id" to "1")) + } + + @Test + fun `start() - sets the request's contexts on the transaction`() { + val fixture = Fixture.create() + val request = fixture.request(contexts = mapOf(NAVIGATION_CONTEXT_KEY to navigationContext)) + + val transaction = request.start(fixture.scopes, scope)!! + + verify(transaction).setContext(NAVIGATION_CONTEXT_KEY, navigationContext) + } + + @Test + fun `start() - sets the view names on a copy of the scope's app context`() { + val fixture = Fixture.create() + val scopeApp = + App().apply { + appName = "Sample" + appVersion = "1.2.3" + viewNames = listOf("/Previous") + } + scope.contexts.setApp(scopeApp) + val request = fixture.request(viewNames = listOf("/Checkout")) + + val transaction = request.start(fixture.scopes, scope)!! + + val transactionApp = transaction.contexts.app + assertThat(transactionApp).isNotSameInstanceAs(scopeApp) + assertThat(transactionApp?.viewNames).containsExactly("/Checkout") + assertThat(transactionApp?.appName).isEqualTo("Sample") + assertThat(transactionApp?.appVersion).isEqualTo("1.2.3") + assertThat(scope.contexts.app?.viewNames).containsExactly("/Previous") + } + + @Test + fun `start() - copies the scope's app context anew for each transaction`() { + val fixture = Fixture.create() + val request = fixture.request(viewNames = listOf("/Checkout")) + scope.contexts.setApp(App().apply { appVersion = "1.0.0" }) + request.start(fixture.scopes, scope) + scope.contexts.setApp(App().apply { appVersion = "2.0.0" }) + + val transaction = request.start(fixture.scopes, scope)!! + + assertThat(transaction.contexts.app?.appVersion).isEqualTo("2.0.0") + } + + @Test + fun `start() - sets the view names on a new app context when the scope has none`() { + val fixture = Fixture.create() + val request = fixture.request(viewNames = listOf("/Checkout")) + + val transaction = request.start(fixture.scopes, scope)!! + + assertThat(transaction.contexts.app?.viewNames).containsExactly("/Checkout") + assertThat(scope.contexts.app).isNull() + } + + @Test + fun `start() - leaves the transaction's app context alone without view names`() { + val fixture = Fixture.create() + scope.contexts.setApp(App().apply { appName = "Sample" }) + val request = fixture.request(viewNames = null) + + val transaction = request.start(fixture.scopes, scope)!! + + assertThat(transaction.contexts.app).isNull() + } + + @Test + fun `start() - returns null when the scopes start a no-op transaction`() { + val fixture = Fixture.create(declinesTransactions = true) + val request = + fixture.request( + data = mapOf("arguments" to "id=1"), + contexts = mapOf(NAVIGATION_CONTEXT_KEY to navigationContext), + viewNames = listOf("/Checkout"), + ) + + val transaction = request.start(fixture.scopes, scope) + + assertThat(transaction).isNull() + } + + @Test + fun `start() - sets nothing on a no-op transaction`() { + val fixture = Fixture.create() + val noOpTransaction = + mock().also { + whenever(it.isNoOp).thenReturn(true) + whenever(fixture.scopes.startTransaction(any(), any())).thenReturn(it) + } + val request = fixture.request(data = mapOf("arguments" to "id=1")) + + request.start(fixture.scopes, scope) + + verify(noOpTransaction, never()).setData(any(), any()) + } + + private class Fixture private constructor() { + /** Whether [scopes] declines to start transactions, returning a no-op transaction instead. */ + var declinesTransactions = false + + val startedContexts = mutableListOf() + val startedOptions = mutableListOf() + val startedTransactions = mutableListOf() + + val scopes = + mock().also { scopes -> + whenever(scopes.startTransaction(any(), any())) + .thenAnswer { + if (declinesTransactions) { + NoOpTransaction.getInstance() + } else { + startedContexts += it.arguments[0] as TransactionContext + startedOptions += it.arguments[1] as TransactionOptions + val contexts = Contexts() + mock() + .also { transaction -> whenever(transaction.contexts).thenReturn(contexts) } + .also(startedTransactions::add) + } + } + } + + fun request( + newOptions: () -> TransactionOptions = ::TransactionOptions, + data: Map = emptyMap(), + contexts: Map = emptyMap(), + viewNames: List? = null, + ): NavTransactionRequest = + NavTransactionRequest( + name = "/Checkout", + newOptions = newOptions, + data = data, + contexts = contexts, + viewNames = viewNames, + ) + + companion object { + fun create(declinesTransactions: Boolean = false): Fixture = + Fixture().also { it.declinesTransactions = declinesTransactions } + } + } +} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionTest.kt deleted file mode 100644 index 1eca057f395..00000000000 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/NavTransactionTest.kt +++ /dev/null @@ -1,348 +0,0 @@ -package io.sentry.compose.navigation3.lifecycle - -import com.google.common.truth.Truth.assertThat -import io.sentry.IScopes -import io.sentry.ITransaction -import io.sentry.NoOpTransaction -import io.sentry.SpanStatus -import io.sentry.TransactionContext -import io.sentry.TransactionOptions -import io.sentry.protocol.App -import io.sentry.protocol.Contexts -import org.junit.Test -import org.mockito.kotlin.any -import org.mockito.kotlin.inOrder -import org.mockito.kotlin.mock -import org.mockito.kotlin.never -import org.mockito.kotlin.verify -import org.mockito.kotlin.verifyNoInteractions -import org.mockito.kotlin.whenever - -class NavTransactionTest { - - private val transactionContext = TransactionContext("/Checkout", "navigation") - private val transactionOptions = TransactionOptions() - - private val app = App().apply { viewNames = listOf("/Checkout") } - private val navigationContext = mapOf("Back Stack" to listOf(mapOf("entry" to "/Checkout"))) - - @Test - fun `started() - is named after the transaction`() { - val fixture = Fixture.create() - - val handle = NavTransaction.started(fixture.transaction) - - assertThat(handle.name).isEqualTo("/Checkout") - } - - @Test - fun `deferred() - is named after the transaction context`() { - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - assertThat(handle.name).isEqualTo("/Checkout") - } - - @Test - fun `transaction - is null for a deferred handle`() { - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - assertThat(handle.transaction).isNull() - } - - @Test - fun `transaction - is the backing transaction for a started handle`() { - val fixture = Fixture.create() - - val handle = NavTransaction.started(fixture.transaction) - - assertThat(handle.transaction).isSameInstanceAs(fixture.transaction) - } - - @Test - fun `transaction - is the started transaction once a deferred handle has started`() { - val fixture = Fixture.create() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - handle.start(fixture.scopes) - - assertThat(handle.transaction).isSameInstanceAs(fixture.transaction) - } - - @Test - fun `transaction - stays null when the scopes decline to start a deferred handle's transaction`() { - val fixture = Fixture.create(declinesTransactions = true) - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - handle.start(fixture.scopes) - - assertThat(handle.transaction).isNull() - } - - @Test - fun `transaction - is null once a deferred handle is finished before it starts`() { - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - handle.finish(onFinished = {}) - - assertThat(handle.transaction).isNull() - } - - @Test - fun `a started handle sets data, contexts, and the app context on the transaction`() { - val fixture = Fixture.create() - val handle = NavTransaction.started(fixture.transaction) - - handle.setData("arguments", "id=1") - handle.setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - handle.setApp(app) - - verify(fixture.transaction).setData("arguments", "id=1") - verify(fixture.transaction).setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - assertThat(fixture.transaction.contexts.app).isSameInstanceAs(app) - } - - @Test - fun `a deferred handle sets data, contexts, and the app context on the transaction once it has started`() { - val fixture = Fixture.create() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - handle.start(fixture.scopes) - - handle.setData("arguments", "id=1") - handle.setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - handle.setApp(app) - - verify(fixture.transaction).setData("arguments", "id=1") - verify(fixture.transaction).setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - assertThat(fixture.transaction.contexts.app).isSameInstanceAs(app) - } - - @Test - fun `start() - starts and returns the transaction with the deferred context and options`() { - val fixture = Fixture.create() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - val started = handle.start(fixture.scopes) - - verify(fixture.scopes).startTransaction(transactionContext, transactionOptions) - assertThat(started).isSameInstanceAs(fixture.transaction) - } - - @Test - fun `start() - replays data, contexts, and the app context set before the start`() { - val fixture = Fixture.create() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - handle.setData("arguments", "id=1") - handle.setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - handle.setApp(app) - - handle.start(fixture.scopes) - - verify(fixture.transaction).setData("arguments", "id=1") - verify(fixture.transaction).setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - assertThat(fixture.transaction.contexts.app).isSameInstanceAs(app) - } - - @Test - fun `start() - replays only the latest value set for each key`() { - val fixture = Fixture.create() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - val latestNavigationContext = mapOf("Back Stack" to listOf(mapOf("entry" to "/Receipt"))) - val latestApp = App().apply { viewNames = listOf("/Receipt") } - handle.setData("arguments", "id=1") - handle.setData("arguments", "id=2") - handle.setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - handle.setContext(NAVIGATION_CONTEXT_KEY, latestNavigationContext) - handle.setApp(app) - handle.setApp(latestApp) - - handle.start(fixture.scopes) - - verify(fixture.transaction, never()).setData("arguments", "id=1") - verify(fixture.transaction).setData("arguments", "id=2") - verify(fixture.transaction, never()).setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - verify(fixture.transaction).setContext(NAVIGATION_CONTEXT_KEY, latestNavigationContext) - assertThat(fixture.transaction.contexts.app).isSameInstanceAs(latestApp) - } - - @Test - fun `start() - returns null when the scopes decline to start a transaction`() { - val fixture = Fixture.create(declinesTransactions = true) - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - val started = handle.start(fixture.scopes) - - assertThat(started).isNull() - } - - @Test - fun `start() - starts the transaction on a retry after the scopes declined to start one`() { - val fixture = Fixture.create(declinesTransactions = true) - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - handle.setData("arguments", "id=1") - handle.start(fixture.scopes) - fixture.declinesTransactions = false - - val started = handle.start(fixture.scopes) - - assertThat(started).isSameInstanceAs(fixture.transaction) - verify(fixture.transaction).setData("arguments", "id=1") - } - - @Test - fun `start() - starts no transaction a second time`() { - val fixture = Fixture.create() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - handle.start(fixture.scopes) - - val started = handle.start(fixture.scopes) - - assertThat(started).isNull() - verify(fixture.scopes).startTransaction(any(), any()) - } - - @Test - fun `start() - starts no transaction for a started handle`() { - val fixture = Fixture.create() - val handle = NavTransaction.started(fixture.transaction) - - val started = handle.start(fixture.scopes) - - assertThat(started).isNull() - verify(fixture.scopes, never()).startTransaction(any(), any()) - } - - @Test - fun `finish() - finishes a started handle's transaction with the transaction's status`() { - val fixture = Fixture.create() - whenever(fixture.transaction.status).thenReturn(SpanStatus.CANCELLED) - val handle = NavTransaction.started(fixture.transaction) - - handle.finish(onFinished = {}) - - verify(fixture.transaction).finish(SpanStatus.CANCELLED) - } - - @Test - fun `finish() - finishes a started handle's transaction with OK when the transaction has no status`() { - val fixture = Fixture.create() - val handle = NavTransaction.started(fixture.transaction) - - handle.finish(onFinished = {}) - - verify(fixture.transaction).finish(SpanStatus.OK) - } - - @Test - fun `finish() - passes a started handle's transaction to the callback after finishing it`() { - val fixture = Fixture.create() - val onFinished = mock<(ITransaction) -> Unit>() - val handle = NavTransaction.started(fixture.transaction) - - handle.finish(onFinished) - - inOrder(fixture.transaction, onFinished) { - verify(fixture.transaction).finish(SpanStatus.OK) - verify(onFinished).invoke(fixture.transaction) - } - } - - @Test - fun `finish() - doesn't finish a started handle's transaction that has already finished`() { - val fixture = Fixture.create() - whenever(fixture.transaction.isFinished).thenReturn(true) - val handle = NavTransaction.started(fixture.transaction) - - handle.finish(onFinished = {}) - - verify(fixture.transaction, never()).finish(any()) - } - - @Test - fun `finish() - passes a started handle's already finished transaction to the callback`() { - val fixture = Fixture.create() - val onFinished = mock<(ITransaction) -> Unit>() - whenever(fixture.transaction.isFinished).thenReturn(true) - val handle = NavTransaction.started(fixture.transaction) - - handle.finish(onFinished) - - verify(onFinished).invoke(fixture.transaction) - } - - @Test - fun `finish() - finishes a deferred handle's transaction once it has started`() { - val fixture = Fixture.create() - val onFinished = mock<(ITransaction) -> Unit>() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - handle.start(fixture.scopes) - - handle.finish(onFinished) - - verify(fixture.transaction).finish(SpanStatus.OK) - verify(onFinished).invoke(fixture.transaction) - } - - @Test - fun `finish() - discards a pending handle so that it never starts a transaction`() { - val fixture = Fixture.create() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - handle.finish(onFinished = {}) - val started = handle.start(fixture.scopes) - - assertThat(started).isNull() - verify(fixture.scopes, never()).startTransaction(any(), any()) - } - - @Test - fun `finish() - does not call back for a pending handle`() { - val onFinished = mock<(ITransaction) -> Unit>() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - - handle.finish(onFinished) - - verifyNoInteractions(onFinished) - } - - @Test - fun `a discarded handle ignores later writes and finishes`() { - val fixture = Fixture.create() - val onFinished = mock<(ITransaction) -> Unit>() - val handle = NavTransaction.deferred(transactionContext, transactionOptions) - handle.finish(onFinished = {}) - - handle.setData("arguments", "id=1") - handle.setContext(NAVIGATION_CONTEXT_KEY, navigationContext) - handle.setApp(app) - handle.finish(onFinished) - val started = handle.start(fixture.scopes) - - assertThat(started).isNull() - verifyNoInteractions(fixture.transaction, onFinished) - } - - private class Fixture private constructor(val scopes: IScopes, val transaction: ITransaction) { - - /** Whether [scopes] declines to start transactions, returning a no-op transaction instead. */ - var declinesTransactions = false - - companion object { - fun create(declinesTransactions: Boolean = false): Fixture { - val contexts = Contexts() - val transaction = - mock().also { - whenever(it.name).thenReturn("/Checkout") - whenever(it.contexts).thenReturn(contexts) - } - val scopes = mock() - val fixture = Fixture(scopes, transaction) - fixture.declinesTransactions = declinesTransactions - whenever(scopes.startTransaction(any(), any())) - .thenAnswer { - if (fixture.declinesTransactions) NoOpTransaction.getInstance() else transaction - } - return fixture - } - } - } -} diff --git a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/StagedNavTransactionTest.kt b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/StagedNavTransactionTest.kt index 7f9798f01f9..be1a7f40bd4 100644 --- a/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/StagedNavTransactionTest.kt +++ b/sentry-android-navigation3/src/test/kotlin/io/sentry/compose/navigation3/lifecycle/StagedNavTransactionTest.kt @@ -9,9 +9,12 @@ import io.sentry.Scope import io.sentry.ScopeObserverAdapter import io.sentry.SentryLevel import io.sentry.SentryOptions +import io.sentry.SpanContext import io.sentry.SpanStatus import io.sentry.TransactionContext import io.sentry.TransactionOptions +import io.sentry.time.TestMonotonicTicker +import java.util.concurrent.TimeUnit import org.junit.Assert.assertThrows import org.junit.Test import org.mockito.kotlin.any @@ -24,223 +27,282 @@ import org.mockito.kotlin.whenever @Suppress("LargeClass") class StagedNavTransactionTest { - private val transactionContext = TransactionContext("/Profile", "navigation") - private val transactionOptions = TransactionOptions() + private val request = navTransactionRequest("/Profile") + private val updatedContexts = mapOf("Navigation" to "updated") private val finishedTransaction = mockTransaction().also { whenever(it.isFinished).thenReturn(true) } - private val hostTransaction = mockTransaction() + private val hostTransaction = transactionWithOrigin("manual") + private val uiLoadTransaction = transactionWithOrigin(ACTIVITY_UI_LOAD_ORIGIN) @Test - fun `start() - starts a nav transaction and binds it to a free scope`() { + fun `publishTo() - keeps the started nav transaction when binding it throws`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.transactionObserverThrows = true - val navTransaction = - stagedNavTransaction.start(fixture.scope, transactionContext, transactionOptions) - + assertThrows(ThrowingScopeObserverException::class.java) { + stagedNavTransaction.publishTo(fixture.scope) + } + fixture.transactionObserverThrows = false val started = fixture.startedTransaction("/Profile") - verify(fixture.scopes).startTransaction(transactionContext, transactionOptions) - assertThat(navTransaction?.transaction).isSameInstanceAs(started) - assertThat(fixture.scope.transaction).isSameInstanceAs(started) + stagedNavTransaction.finish(fixture.scope) + + verify(started).finish(SpanStatus.OK) } @Test - fun `start() - starts no nav transaction while another transaction is bound`() { + fun `stage() - starts no transaction`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - fixture.scope.transaction = hostTransaction - val navTransaction = - stagedNavTransaction.start(fixture.scope, transactionContext, transactionOptions) + stagedNavTransaction.stage(request) - assertThat(navTransaction).isNull() assertThat(fixture.startedTransactions).isEmpty() - assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) + assertThat(fixture.scope.transaction).isNull() } @Test - fun `start() - logs the route when another transaction blocks the start`() { + fun `stage() - replaces the current nav transaction without finishing it`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - fixture.scope.transaction = hostTransaction + val current = fixture.start("/Home") - stagedNavTransaction.start(fixture.scope, transactionContext, transactionOptions) + stagedNavTransaction.stage(request) + stagedNavTransaction.finish(fixture.scope) - verify(fixture.logger).log(eq(SentryLevel.DEBUG), any(), eq("/Profile")) + verify(current, never()).finish(any()) } @Test - fun `start() - binds the nav transaction in place of a finished bound transaction`() { + fun `publishTo() - starts a staged nav transaction and binds it to a free scope`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - fixture.scope.transaction = finishedTransaction + stagedNavTransaction.stage(request) - val navTransaction = - stagedNavTransaction.start(fixture.scope, transactionContext, transactionOptions) + stagedNavTransaction.publishTo(fixture.scope) - val started = fixture.startedTransaction("/Profile") - assertThat(navTransaction?.transaction).isSameInstanceAs(started) - assertThat(fixture.scope.transaction).isSameInstanceAs(started) + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) } @Test - fun `start() - returns null and keeps the current nav transaction when the start is declined`() { + fun `publishTo() - starts a staged nav transaction in place of a finished bound transaction`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val current = fixture.start("/Home") - fixture.declinesTransactions = true + stagedNavTransaction.stage(request) + fixture.scope.transaction = finishedTransaction - val navTransaction = - stagedNavTransaction.start(fixture.scope, transactionContext, transactionOptions) + stagedNavTransaction.publishTo(fixture.scope) - assertThat(navTransaction).isNull() - assertThat(fixture.scope.transaction).isSameInstanceAs(current) - stagedNavTransaction.finish(fixture.scope) - verify(current).finish(SpanStatus.OK) + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) } @Test - fun `start() - replaces the current nav transaction without finishing it`() { + fun `publishTo() - doesn't start a staged nav transaction while another transaction is bound`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val current = fixture.start("/Home") - // Unbound, so that it doesn't block the start. - stagedNavTransaction.unpublishFrom(fixture.scope) + stagedNavTransaction.stage(request) + fixture.scope.transaction = hostTransaction - stagedNavTransaction.start(fixture.scope, transactionContext, transactionOptions) - verify(current, never()).finish(any()) + stagedNavTransaction.publishTo(fixture.scope) - stagedNavTransaction.finish(fixture.scope) - verify(fixture.startedTransaction("/Profile")).finish(SpanStatus.OK) - verify(current, never()).finish(any()) + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) } @Test - fun `start() - keeps the started nav transaction when binding it throws`() { + fun `publishTo() - logs the route when another transaction blocks the nav transaction`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - fixture.transactionObserverThrows = true + stagedNavTransaction.stage(request) + fixture.scope.transaction = hostTransaction - assertThrows(ThrowingScopeObserverException::class.java) { - stagedNavTransaction.start(fixture.scope, transactionContext, transactionOptions) - } - fixture.transactionObserverThrows = false - val started = fixture.startedTransaction("/Profile") - stagedNavTransaction.finish(fixture.scope) + stagedNavTransaction.publishTo(fixture.scope) - verify(started).finish(SpanStatus.OK) + verify(fixture.logger).log(eq(SentryLevel.DEBUG), any(), eq("/Profile")) } @Test - fun `stage() - returns a pending nav transaction without starting a transaction`() { - val fixture = Fixture.create() + fun `publishTo() - binds nothing when a staged nav transaction's start is declined`() { + val fixture = Fixture.create(declinesTransactions = true) val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) - val navTransaction = stagedNavTransaction.stage(transactionContext, transactionOptions) + stagedNavTransaction.publishTo(fixture.scope) - assertThat(navTransaction.transaction).isNull() - assertThat(navTransaction.name).isEqualTo("/Profile") - assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isNull() } @Test - fun `stage() - replaces the current nav transaction without finishing it`() { + fun `publishTo() - starts a nav transaction for a request whose staged one was declined`() { + val fixture = Fixture.create(declinesTransactions = true) + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + stagedNavTransaction.publishTo(fixture.scope) + fixture.declinesTransactions = false + + stagedNavTransaction.publishTo(fixture.scope) + + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) + } + + @Test + fun `publishTo() - binds an unpublished unfinished nav transaction again`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val current = fixture.start("/Home") + val started = fixture.start() + stagedNavTransaction.unpublishFrom(fixture.scope) - stagedNavTransaction.stage(transactionContext, transactionOptions) - stagedNavTransaction.finish(fixture.scope) + stagedNavTransaction.publishTo(fixture.scope) - verify(current, never()).finish(any()) + assertThat(fixture.scope.transaction).isSameInstanceAs(started) + assertThat(fixture.startedTransactions).containsExactly(started) } @Test - fun `publishTo() - starts a staged nav transaction and binds it to a free scope`() { + fun `publishTo() - keeps the bound nav transaction bound`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val navTransaction = stagedNavTransaction.stage(transactionContext, transactionOptions) + val started = fixture.start() stagedNavTransaction.publishTo(fixture.scope) - val started = fixture.startedTransaction("/Profile") - assertThat(navTransaction.transaction).isSameInstanceAs(started) assertThat(fixture.scope.transaction).isSameInstanceAs(started) + verify(fixture.logger, never()).log(eq(SentryLevel.DEBUG), any(), any()) } @Test - fun `publishTo() - starts a staged nav transaction in place of a finished bound transaction`() { + fun `publishTo() - binds an unpublished nav transaction in place of a finished bound transaction`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - stagedNavTransaction.stage(transactionContext, transactionOptions) + val started = fixture.start() + stagedNavTransaction.unpublishFrom(fixture.scope) fixture.scope.transaction = finishedTransaction stagedNavTransaction.publishTo(fixture.scope) - assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) + assertThat(fixture.scope.transaction).isSameInstanceAs(started) } @Test - fun `publishTo() - doesn't start a staged nav transaction while another transaction is bound`() { + fun `publishTo() - doesn't bind an unpublished nav transaction while another transaction is bound`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - stagedNavTransaction.stage(transactionContext, transactionOptions) + val started = fixture.start() + stagedNavTransaction.unpublishFrom(fixture.scope) fixture.scope.transaction = hostTransaction stagedNavTransaction.publishTo(fixture.scope) - assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) + stagedNavTransaction.finish(fixture.scope) + verify(started).finish(SpanStatus.OK) } @Test - fun `publishTo() - logs the route when another transaction blocks the nav transaction`() { + fun `publishTo() - forgets an unpublished nav transaction that has finished and keeps another transaction`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - stagedNavTransaction.stage(transactionContext, transactionOptions) + val started = fixture.start() + stagedNavTransaction.unpublishFrom(fixture.scope) + whenever(started.isFinished).thenReturn(true) fixture.scope.transaction = hostTransaction stagedNavTransaction.publishTo(fixture.scope) - verify(fixture.logger).log(eq(SentryLevel.DEBUG), any(), eq("/Profile")) + assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) + } + + @Test + fun `publishTo() - leaves the scope untouched without a nav transaction`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + fixture.scope.transaction = finishedTransaction + + stagedNavTransaction.publishTo(fixture.scope) + + assertThat(fixture.scope.transaction).isSameInstanceAs(finishedTransaction) + } + + @Test + fun `publishTo() - starts a new nav transaction for the last request once the last one finished`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + val finished = fixture.start() + whenever(finished.isFinished).thenReturn(true) + + stagedNavTransaction.publishTo(fixture.scope) + + val restarted = fixture.startedTransactions.last() + assertThat(fixture.startedTransactions).hasSize(2) + assertThat(restarted).isNotSameInstanceAs(finished) + assertThat(restarted.name).isEqualTo("/Profile") + assertThat(fixture.scope.transaction).isSameInstanceAs(restarted) } @Test - fun `publishTo() - discards a staged nav transaction blocked by another transaction`() { + fun `publishTo() - starts a nav transaction for a request whose staged one was discarded`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val navTransaction = stagedNavTransaction.stage(transactionContext, transactionOptions) + stagedNavTransaction.stage(request) fixture.scope.transaction = hostTransaction stagedNavTransaction.publishTo(fixture.scope) fixture.scope.clearTransaction() stagedNavTransaction.publishTo(fixture.scope) - assertThat(navTransaction.start(fixture.scopes)).isNull() - assertThat(fixture.startedTransactions).isEmpty() - assertThat(fixture.scope.transaction).isNull() + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) } @Test - fun `publishTo() - binds nothing when a staged nav transaction's start is declined`() { - val fixture = Fixture.create(declinesTransactions = true) + fun `publishTo() - starts a nav transaction for the most recent of several requests`() { + val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - stagedNavTransaction.stage(transactionContext, transactionOptions) + fixture.scope.transaction = hostTransaction + stagedNavTransaction.stage(navTransactionRequest("/Home")) + stagedNavTransaction.publishTo(fixture.scope) + stagedNavTransaction.stage(request) + stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.clearTransaction() stagedNavTransaction.publishTo(fixture.scope) + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) + assertThat(fixture.startedTransactions).hasSize(1) + } + + @Test + fun `publishTo() - makes the restarted nav transaction the one that finish() finishes`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + val finished = fixture.start() + whenever(finished.isFinished).thenReturn(true) + stagedNavTransaction.publishTo(fixture.scope) + val restarted = fixture.startedTransactions.last() + + stagedNavTransaction.finish(fixture.scope) + + verify(restarted).finish(SpanStatus.OK) assertThat(fixture.scope.transaction).isNull() } @Test - fun `publishTo() - discards a staged nav transaction whose start was declined`() { - val fixture = Fixture.create(declinesTransactions = true) + fun `publishTo() - starts no nav transaction while the started one is unfinished`() { + val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - stagedNavTransaction.stage(transactionContext, transactionOptions) + val started = fixture.start() + stagedNavTransaction.unpublishFrom(fixture.scope) + stagedNavTransaction.publishTo(fixture.scope) - fixture.declinesTransactions = false + + assertThat(fixture.startedTransactions).containsExactly(started) + } + + @Test + fun `publishTo() - starts no nav transaction without a request`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction stagedNavTransaction.publishTo(fixture.scope) @@ -249,93 +311,394 @@ class StagedNavTransactionTest { } @Test - fun `publishTo() - binds an unpublished unfinished nav transaction again`() { + fun `updateRequest() - restarts the nav transaction from the updated request`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val started = fixture.start() - stagedNavTransaction.unpublishFrom(fixture.scope) + val finished = fixture.start() + whenever(finished.isFinished).thenReturn(true) + stagedNavTransaction.updateRequest( + navTransactionRequest("/Profile", contexts = updatedContexts), + ) stagedNavTransaction.publishTo(fixture.scope) + verify(fixture.startedTransactions.last()).setContext("Navigation", "updated") + } + + @Test + fun `updateRequest() - starts a staged nav transaction from the updated request`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + + stagedNavTransaction.updateRequest( + navTransactionRequest("/Profile", contexts = updatedContexts), + ) + stagedNavTransaction.publishTo(fixture.scope) + + val started = fixture.startedTransaction("/Profile") + verify(started).setContext("Navigation", "updated") assertThat(fixture.scope.transaction).isSameInstanceAs(started) - assertThat(fixture.startedTransactions).containsExactly(started) } @Test - fun `publishTo() - keeps the bound nav transaction bound`() { + fun `updateRequest() - leaves a started nav transaction alone`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction val started = fixture.start() + stagedNavTransaction.updateRequest( + navTransactionRequest("/Profile", contexts = updatedContexts), + ) stagedNavTransaction.publishTo(fixture.scope) + assertThat(fixture.startedTransactions).containsExactly(started) + verify(started, never()).setContext(any(), any()) assertThat(fixture.scope.transaction).isSameInstanceAs(started) - verify(fixture.logger, never()).log(eq(SentryLevel.DEBUG), any(), any()) } @Test - fun `publishTo() - binds an unpublished nav transaction in place of a finished bound transaction`() { + fun `updateRequest() - keeps no request after the nav transaction is finished`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + fixture.start() + stagedNavTransaction.finish(fixture.scope) + + stagedNavTransaction.updateRequest( + navTransactionRequest("/Profile", contexts = updatedContexts), + ) + stagedNavTransaction.publishTo(fixture.scope) + + assertThat(fixture.startedTransactions).hasSize(1) + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `updateRequest() - keeps no request without a request`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + + stagedNavTransaction.updateRequest(request) + stagedNavTransaction.publishTo(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + } + + @Test + fun `publishTo() - starts no nav transaction after the nav transaction is finished`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction val started = fixture.start() - stagedNavTransaction.unpublishFrom(fixture.scope) - fixture.scope.transaction = finishedTransaction + stagedNavTransaction.finish(fixture.scope) stagedNavTransaction.publishTo(fixture.scope) - assertThat(fixture.scope.transaction).isSameInstanceAs(started) + assertThat(fixture.startedTransactions).containsExactly(started) + assertThat(fixture.scope.transaction).isNull() } @Test - fun `publishTo() - doesn't bind an unpublished nav transaction while another transaction is bound`() { + fun `publishTo() - starts no nav transaction after a staged nav transaction is finished`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + stagedNavTransaction.finish(fixture.scope) + + stagedNavTransaction.publishTo(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + } + + @Test + fun `publishTo() - starts no nav transaction after the nav transaction is forgotten`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction val started = fixture.start() - stagedNavTransaction.unpublishFrom(fixture.scope) + whenever(started.isFinished).thenReturn(true) + stagedNavTransaction.forget() + + stagedNavTransaction.publishTo(fixture.scope) + + assertThat(fixture.startedTransactions).containsExactly(started) + } + + @Test + fun `publishTo() - starts no nav transaction while another transaction is bound`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + val finished = fixture.start() + whenever(finished.isFinished).thenReturn(true) fixture.scope.transaction = hostTransaction stagedNavTransaction.publishTo(fixture.scope) + assertThat(fixture.startedTransactions).containsExactly(finished) assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) - stagedNavTransaction.finish(fixture.scope) - verify(started).finish(SpanStatus.OK) } @Test - fun `publishTo() - forgets and unbinds a bound nav transaction that has finished`() { + fun `retryPublishIfBlocked() - starts a nav transaction blocked by a ui load once it leaves the slot`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.clearTransaction() + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) + } + + @Test + fun `retryPublishIfBlocked() - binds an unfinished nav transaction blocked by a ui load once it leaves the slot`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction val started = fixture.start() - whenever(started.isFinished).thenReturn(true) + stagedNavTransaction.unpublishFrom(fixture.scope) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.clearTransaction() + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.scope.transaction).isSameInstanceAs(started) + assertThat(fixture.startedTransactions).containsExactly(started) + } + + @Test + fun `retryPublishIfBlocked() - starts a nav transaction blocked by a ui load once it finishes`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + val uiLoad = transactionWithOrigin(ACTIVITY_UI_LOAD_ORIGIN) + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoad + stagedNavTransaction.publishTo(fixture.scope) + whenever(uiLoad.isFinished).thenReturn(true) + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) + } + + @Test + fun `retryPublishIfBlocked() - waits while the blocking ui load holds the slot`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isSameInstanceAs(uiLoadTransaction) + + fixture.scope.clearTransaction() + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) + } + + @Test + fun `retryPublishIfBlocked() - retries within the retry window`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.clearTransaction() + fixture.ticker.advance( + TimeUnit.SECONDS.toNanos(UI_LOAD_RETRY_WINDOW_SECONDS) - 1, + TimeUnit.NANOSECONDS, + ) + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) + } + + @Test + fun `retryPublishIfBlocked() - measures the retry window from the blocked publication`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.ticker.advance(UI_LOAD_RETRY_WINDOW_SECONDS, TimeUnit.SECONDS) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.clearTransaction() + fixture.ticker.advance(UI_LOAD_RETRY_WINDOW_SECONDS - 1, TimeUnit.SECONDS) + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.scope.transaction).isSameInstanceAs(fixture.startedTransaction("/Profile")) + } + + @Test + fun `retryPublishIfBlocked() - retries nothing exactly at the end of the retry window`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.clearTransaction() + fixture.ticker.advance(UI_LOAD_RETRY_WINDOW_SECONDS, TimeUnit.SECONDS) + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isNull() } @Test - fun `publishTo() - forgets an unpublished nav transaction that has finished and keeps another transaction`() { + fun `retryPublishIfBlocked() - retries nothing after the retry window`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.clearTransaction() + fixture.ticker.advance(UI_LOAD_RETRY_WINDOW_SECONDS + 1, TimeUnit.SECONDS) + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `retryPublishIfBlocked() - retries nothing once the retry window passes while the ui load holds the slot`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + fixture.ticker.advance(UI_LOAD_RETRY_WINDOW_SECONDS, TimeUnit.SECONDS) + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + fixture.scope.clearTransaction() + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + } + + @Test + fun `retryPublishIfBlocked() - retries only once`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.transaction = transactionWithOrigin(ACTIVITY_UI_LOAD_ORIGIN) + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + fixture.scope.clearTransaction() + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `retryPublishIfBlocked() - retries nothing after a transaction other than a ui load blocked it`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = hostTransaction + stagedNavTransaction.publishTo(fixture.scope) + fixture.scope.clearTransaction() + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `retryPublishIfBlocked() - starts no new nav transaction when the publication wasn't blocked`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction val started = fixture.start() - stagedNavTransaction.unpublishFrom(fixture.scope) + stagedNavTransaction.publishTo(fixture.scope) whenever(started.isFinished).thenReturn(true) - fixture.scope.transaction = hostTransaction + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).containsExactly(started) + } + + @Test + fun `retryPublishIfBlocked() - retries nothing after a start the scopes declined`() { + val fixture = Fixture.create(declinesTransactions = true) + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) stagedNavTransaction.publishTo(fixture.scope) + fixture.declinesTransactions = false - assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() } @Test - fun `publishTo() - leaves the scope untouched without a nav transaction`() { + fun `retryPublishIfBlocked() - retries nothing once the nav transaction is unpublished`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - fixture.scope.transaction = finishedTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope) + stagedNavTransaction.unpublishFrom(fixture.scope) + fixture.scope.clearTransaction() + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isNull() + } + @Test + fun `retryPublishIfBlocked() - retries nothing once the nav transaction is finished`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction stagedNavTransaction.publishTo(fixture.scope) + stagedNavTransaction.finish(fixture.scope) + fixture.scope.clearTransaction() - assertThat(fixture.scope.transaction).isSameInstanceAs(finishedTransaction) + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + } + + @Test + fun `retryPublishIfBlocked() - starts nothing after a ui load blocked a publication that can't be retried`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + stagedNavTransaction.stage(request) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope, canRetry = false) + fixture.scope.clearTransaction() + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.startedTransactions).isEmpty() + assertThat(fixture.scope.transaction).isNull() + } + + @Test + fun `retryPublishIfBlocked() - binds nothing after a ui load blocked a rebind that can't be retried`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + fixture.start() + stagedNavTransaction.unpublishFrom(fixture.scope) + fixture.scope.transaction = uiLoadTransaction + stagedNavTransaction.publishTo(fixture.scope, canRetry = false) + fixture.scope.clearTransaction() + + stagedNavTransaction.retryPublishIfBlocked(fixture.scope) + + assertThat(fixture.scope.transaction).isNull() } @Test @@ -367,13 +730,13 @@ class StagedNavTransactionTest { fun `unpublishFrom() - keeps the bound transaction while the nav transaction is staged`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val navTransaction = stagedNavTransaction.stage(transactionContext, transactionOptions) + stagedNavTransaction.stage(request) fixture.scope.transaction = hostTransaction stagedNavTransaction.unpublishFrom(fixture.scope) assertThat(fixture.scope.transaction).isSameInstanceAs(hostTransaction) - assertThat(navTransaction.transaction).isNull() + assertThat(fixture.startedTransactions).isEmpty() } @Test @@ -388,6 +751,31 @@ class StagedNavTransactionTest { assertThat(fixture.scope.transaction).isNull() } + @Test + fun `finish() - finishes the nav transaction with its own status`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + val started = fixture.start() + whenever(started.status).thenReturn(SpanStatus.CANCELLED) + + stagedNavTransaction.finish(fixture.scope) + + verify(started).finish(SpanStatus.CANCELLED) + } + + @Test + fun `finish() - unbinds a nav transaction that already finished without finishing it again`() { + val fixture = Fixture.create() + val stagedNavTransaction = fixture.stagedNavTransaction + val started = fixture.start() + whenever(started.isFinished).thenReturn(true) + + stagedNavTransaction.finish(fixture.scope) + + verify(started, never()).finish(any()) + assertThat(fixture.scope.transaction).isNull() + } + @Test fun `finish() - finishes an unpublished nav transaction and keeps another bound transaction`() { val fixture = Fixture.create() @@ -418,12 +806,11 @@ class StagedNavTransactionTest { fun `finish() - discards a staged nav transaction so that publishing never starts it`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - val navTransaction = stagedNavTransaction.stage(transactionContext, transactionOptions) + stagedNavTransaction.stage(request) stagedNavTransaction.finish(fixture.scope) stagedNavTransaction.publishTo(fixture.scope) - assertThat(navTransaction.start(fixture.scopes)).isNull() assertThat(fixture.startedTransactions).isEmpty() assertThat(fixture.scope.transaction).isNull() } @@ -473,7 +860,7 @@ class StagedNavTransactionTest { fun `forget() - forgets a staged nav transaction so that publishing never starts it`() { val fixture = Fixture.create() val stagedNavTransaction = fixture.stagedNavTransaction - stagedNavTransaction.stage(transactionContext, transactionOptions) + stagedNavTransaction.stage(request) stagedNavTransaction.forget() stagedNavTransaction.publishTo(fixture.scope) @@ -485,10 +872,18 @@ class StagedNavTransactionTest { /** Thrown by a scope observer, to stand in for one the host app registered. */ private class ThrowingScopeObserverException : RuntimeException() + private fun transactionWithOrigin(origin: String): ITransaction = + mock().also { + whenever(it.spanContext).thenReturn(SpanContext("op").apply { this.origin = origin }) + } + private class Fixture private constructor() { val scope = Scope(SentryOptions()) val logger = mock() + /** Measures [stagedNavTransaction]'s retry window. */ + val ticker = TestMonotonicTicker() + /** Whether [scopes] declines to start transactions, returning a no-op transaction instead. */ var declinesTransactions = false val startedTransactions = mutableListOf() @@ -503,7 +898,7 @@ class StagedNavTransactionTest { SentryOptions().apply { setLogger(this@Fixture.logger) isDebug = true - } + }, ) whenever(scopes.startTransaction(any(), any())) .thenAnswer { @@ -518,7 +913,7 @@ class StagedNavTransactionTest { } } - val stagedNavTransaction = StagedNavTransaction(scopes) + val stagedNavTransaction = StagedNavTransaction(scopes, ticker) init { scope.options.addScopeObserver( @@ -528,7 +923,7 @@ class StagedNavTransactionTest { throw ThrowingScopeObserverException() } } - } + }, ) } @@ -538,11 +933,8 @@ class StagedNavTransactionTest { /** Starts a nav transaction for [name], binding it if the scope is free, and returns it. */ fun start(name: String = "/Profile"): ITransaction { - stagedNavTransaction.start( - scope, - TransactionContext(name, "navigation"), - TransactionOptions(), - ) + stagedNavTransaction.stage(navTransactionRequest(name)) + stagedNavTransaction.publishTo(scope) return startedTransaction(name) } @@ -552,3 +944,13 @@ class StagedNavTransactionTest { } } } + +private fun navTransactionRequest( + name: String, + contexts: Map = emptyMap(), +): NavTransactionRequest = + NavTransactionRequest( + name = name, + newOptions = ::TransactionOptions, + contexts = contexts, + ) diff --git a/sentry-android-ndk-outproc/README.md b/sentry-android-ndk-outproc/README.md new file mode 100644 index 00000000000..fefcd96da8d --- /dev/null +++ b/sentry-android-ndk-outproc/README.md @@ -0,0 +1,21 @@ +# sentry-android-ndk-outproc + +Experimental opt-in alternative to the inproc native backend, with an Android +service that runs the native crash daemon. Builds on `sentry-android-ndk` and +replaces its `sentry-native-ndk` with `sentry-native-ndk-outproc`. + +The default is the inproc backend. + +To select it, add `sentry-android-ndk-outproc`. With the `sentry-android` +bundle, which brings `sentry-native-ndk`, also exclude it: + +```kotlin +configurations.configureEach { + exclude(group = "io.sentry", module = "sentry-native-ndk") +} +``` + +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/api/sentry-android-ndk-outproc.api b/sentry-android-ndk-outproc/api/sentry-android-ndk-outproc.api new file mode 100644 index 00000000000..45ea4895289 --- /dev/null +++ b/sentry-android-ndk-outproc/api/sentry-android-ndk-outproc.api @@ -0,0 +1,19 @@ +public final class io/sentry/android/ndk/outproc/BuildConfig { + public static final field BUILD_TYPE Ljava/lang/String; + public static final field DEBUG Z + public static final field LIBRARY_PACKAGE_NAME Ljava/lang/String; + public static final field VERSION_NAME Ljava/lang/String; + public fun ()V +} + +public final class io/sentry/android/ndk/outproc/SentryNdkCrashService : android/app/Service { + public fun ()V + public fun onBind (Landroid/content/Intent;)Landroid/os/IBinder; +} + +public final class io/sentry/android/ndk/outproc/SentryNdkOutproc { + public static fun close ()V + public static fun init (Landroid/content/Context;Lio/sentry/android/core/SentryAndroidOptions;)V + public static fun init (Lio/sentry/android/core/SentryAndroidOptions;)V +} + diff --git a/sentry-android-ndk-outproc/build.gradle.kts b/sentry-android-ndk-outproc/build.gradle.kts new file mode 100644 index 00000000000..bb8fd5151a4 --- /dev/null +++ b/sentry-android-ndk-outproc/build.gradle.kts @@ -0,0 +1,89 @@ +import org.jetbrains.kotlin.config.KotlinCompilerVersion + +plugins { + id("com.android.library") + alias(libs.plugins.kotlin.android) + alias(libs.plugins.gradle.versions) + id("io.sentry.spotless") + id("io.sentry.jdk-target") + id("io.sentry.publish") + id("io.sentry.api-validation") + id("io.sentry.robolectric") +} + +android { + compileSdk = libs.versions.compileSdk.get().toInt() + compileSdkMinor = libs.versions.compileSdkMinor.get().toInt() + namespace = "io.sentry.android.ndk.outproc" + + defaultConfig { + minSdk = libs.versions.minSdk.get().toInt() + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + + ndk { abiFilters.addAll(Config.Android.abiFilters) } + + // for AGP 4.1 + buildConfigField("String", "VERSION_NAME", "\"${project.version}\"") + } + + buildTypes { + getByName("debug") { consumerProguardFiles("proguard-rules.pro") } + getByName("release") { consumerProguardFiles("proguard-rules.pro") } + } + + // AGP 9 only generates unit tests for the testBuildType. The debug variant is + // disabled, so unit tests must target release to run at all. + testBuildType = "release" + + kotlin { compilerOptions.jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_1_8 } + + testOptions { + animationsDisabled = true + unitTests.apply { + isReturnDefaultValues = true + isIncludeAndroidResources = true + } + } + + lint { + warningsAsErrors = true + checkDependencies = true + + // We run a full lint analysis as build part in CI, so skip vital checks for assemble tasks. + checkReleaseBuilds = false + } + + // needed because of Kotlin 1.4.x + configurations.all { resolutionStrategy.force(libs.jetbrains.annotations.get()) } + + buildFeatures { buildConfig = true } + + androidComponents.beforeVariants { + it.enable = !Config.Android.shouldSkipDebugVariant(it.buildType) + } + + // the default AGP version is too high, we keep this low for compatibility reasons + // see https://developer.android.com/build/releases/past-releases/ to find the AGP-NDK mapping + ndkVersion = "23.1.7779620" + + @Suppress("UnstableApiUsage") packagingOptions { jniLibs { useLegacyPackaging = true } } +} + +dependencies { + api(projects.sentry) + api(projects.sentryAndroidCore) + // the outproc backend replaces the inproc one + api(projects.sentryAndroidNdk) { exclude(group = "io.sentry", module = "sentry-native-ndk") } + + compileOnly(libs.jetbrains.annotations) + + implementation(libs.sentry.native.ndk.outproc) + + testImplementation(kotlin(Config.kotlinStdLib, KotlinCompilerVersion.VERSION)) + testImplementation(libs.kotlin.test.junit) + testImplementation(libs.mockito.kotlin) + testImplementation(projects.sentryTestSupport) + testImplementation(libs.google.truth) + testImplementation(libs.roboelectric) +} diff --git a/sentry-android-ndk-outproc/proguard-rules.pro b/sentry-android-ndk-outproc/proguard-rules.pro new file mode 100644 index 00000000000..022d5bb3a1e --- /dev/null +++ b/sentry-android-ndk-outproc/proguard-rules.pro @@ -0,0 +1,6 @@ +##---------------Begin: proguard configuration for NDK outproc ---------- + +# The Android SDK checks at runtime if this class is available via Class.forName +-keep class io.sentry.android.ndk.outproc.SentryNdkOutproc { *; } + +##---------------End: proguard configuration for NDK outproc ---------- diff --git a/sentry-android-ndk-outproc/src/main/AndroidManifest.xml b/sentry-android-ndk-outproc/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..360057efb94 --- /dev/null +++ b/sentry-android-ndk-outproc/src/main/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + 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 new file mode 100644 index 00000000000..985e3b1af5e --- /dev/null +++ b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkCrashService.java @@ -0,0 +1,813 @@ +package io.sentry.android.ndk.outproc; + +import android.annotation.SuppressLint; +import android.app.ActivityManager; +import android.app.ApplicationExitInfo; +import android.app.Service; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.Binder; +import android.os.Build; +import android.os.IBinder; +import android.os.Parcel; +import android.os.ParcelFileDescriptor; +import android.os.Process; +import android.os.RemoteException; +import io.sentry.DateUtils; +import io.sentry.ILogger; +import io.sentry.SentryEnvelope; +import io.sentry.SentryEnvelopeItem; +import io.sentry.SentryEvent; +import io.sentry.SentryItemType; +import io.sentry.SentryLevel; +import io.sentry.android.core.AndroidLogger; +import io.sentry.android.core.SentryAndroidOptions; +import io.sentry.android.core.TombstoneIntegration; +import io.sentry.android.core.cache.AndroidEnvelopeCache; +import io.sentry.android.core.internal.tombstone.TombstoneParser; +import io.sentry.ndk.SentryNdk.CrashDaemon; +import io.sentry.time.Deadline; +import io.sentry.util.ExceptionUtils; +import io.sentry.util.FileUtils; +import java.io.BufferedInputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.VisibleForTesting; + +@ApiStatus.Internal +public final class SentryNdkCrashService extends Service { + + private static final @NotNull String BINDER_DESCRIPTOR = "io.sentry.android.ndk.CrashService"; + private static final int TRANSACTION_CONFIGURE = IBinder.FIRST_CALL_TRANSACTION; + + 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 final @NotNull IBinder binder = + new Binder() { + @Override + protected boolean onTransact( + final int code, + final @NotNull Parcel data, + final @Nullable Parcel reply, + final int flags) + throws RemoteException { + if (code != TRANSACTION_CONFIGURE) { + return super.onTransact(code, data, reply, flags); + } + + data.enforceInterface(BINDER_DESCRIPTOR); + final @Nullable String nativeDatabasePath = data.readString(); + final @Nullable String nativeLibraryDir = data.readString(); + final int appPid = data.readInt(); + final long appTid = data.readLong(); + final boolean tombstoneEnabled = data.readInt() == 1; + final boolean debug = data.readInt() == 1; + final long shutdownTimeoutMillis = data.readLong(); + final @Nullable ArrayList includes = data.createStringArrayList(); + final @Nullable ArrayList excludes = data.createStringArrayList(); + final @Nullable ParcelFileDescriptor notifyRead = data.readFileDescriptor(); + final @Nullable ParcelFileDescriptor readyWrite = data.readFileDescriptor(); + final @Nullable ParcelFileDescriptor messageRead = data.readFileDescriptor(); + final @Nullable ParcelFileDescriptor shm = data.readFileDescriptor(); + + final boolean configured = + configureDaemon( + nativeDatabasePath, + nativeLibraryDir, + shm, + appPid, + appTid, + tombstoneEnabled, + debug, + shutdownTimeoutMillis, + includes, + excludes, + notifyRead, + readyWrite, + messageRead); + if (reply != null) { + reply.writeNoException(); + reply.writeInt(configured ? 1 : 0); + } + return true; + } + }; + + static @Nullable ServiceConnection 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(); + + final @Nullable String outboxPath = options.getOutboxPath(); + if (outboxPath == null) { + options + .getLogger() + .log(SentryLevel.DEBUG, "Outbox path is null, not starting NDK crash service."); + return null; + } + + final @Nullable File cacheDir = new File(outboxPath).getParentFile(); + if (cacheDir == null) { + options + .getLogger() + .log(SentryLevel.DEBUG, "Cache dir is null, not starting NDK crash service."); + return null; + } + + final File nativeDatabaseDir = new File(cacheDir, ".sentry-native"); + if (!nativeDatabaseDir.exists() && !nativeDatabaseDir.mkdirs()) { + options.getLogger().log(SentryLevel.DEBUG, "Failed to create NDK database directory."); + return null; + } + + final int shmFd = io.sentry.ndk.SentryNdk.createCrashShm(); + if (shmFd < 0) { + options.getLogger().log(SentryLevel.DEBUG, "Failed to create NDK crash shared memory."); + return null; + } + + final ParcelFileDescriptor shm = ParcelFileDescriptor.adoptFd(shmFd); + ParcelFileDescriptor notifyRead = null; + ParcelFileDescriptor notifyWrite = null; + ParcelFileDescriptor readyRead = null; + ParcelFileDescriptor readyWrite = null; + ParcelFileDescriptor messageWrite = null; + ParcelFileDescriptor messageRead = null; + try { + final ParcelFileDescriptor[] notifyPipe = ParcelFileDescriptor.createPipe(); + final ParcelFileDescriptor[] readyPipe = ParcelFileDescriptor.createPipe(); + notifyRead = notifyPipe[0]; + notifyWrite = notifyPipe[1]; + readyRead = readyPipe[0]; + readyWrite = readyPipe[1]; + final ParcelFileDescriptor[] messageSocket = ParcelFileDescriptor.createSocketPair(); + messageWrite = messageSocket[0]; + messageRead = messageSocket[1]; + + final Intent intent = new Intent(context, SentryNdkCrashService.class); + final @Nullable ServiceConnection connection = + configureService( + context, + intent, + options.getLogger(), + nativeDatabaseDir.getPath(), + context.getApplicationInfo().nativeLibraryDir, + shm, + Process.myPid(), + Process.myTid(), + options.isTombstoneEnabled() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S, + options.isDebug(), + options.getShutdownTimeoutMillis(), + new ArrayList<>(options.getInAppIncludes()), + new ArrayList<>(options.getInAppExcludes()), + notifyRead, + readyWrite, + messageRead); + if (connection == null) { + options.getLogger().log(SentryLevel.DEBUG, "NDK crash service did not configure."); + return null; + } + + 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 { + closeQuietly(shm); + closeQuietly(notifyRead); + closeQuietly(notifyWrite); + closeQuietly(readyRead); + closeQuietly(readyWrite); + closeQuietly(messageWrite); + closeQuietly(messageRead); + } + } + + @Override + public @Nullable IBinder onBind(final @NotNull Intent intent) { + return binder; + } + + private static void closeQuietly(final @Nullable Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException ignored) { + // ignored + } + } + } + + private static @Nullable ServiceConnection configureService( + final @NotNull Context context, + final @NotNull Intent intent, + final @NotNull ILogger logger, + final @NotNull String nativeDatabasePath, + final @Nullable String nativeLibraryDir, + final @NotNull ParcelFileDescriptor shm, + final int appPid, + final long appTid, + final boolean tombstoneEnabled, + final boolean debug, + 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}; + // 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; + + @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( + service, + logger, + nativeDatabasePath, + nativeLibraryDir, + appPid, + appTid, + tombstoneEnabled, + debug, + shutdownTimeoutMillis, + includes, + excludes); + return; + } + connected = true; + configured[0] = + transactConfigure( + service, + nativeDatabasePath, + nativeLibraryDir, + shm, + appPid, + appTid, + tombstoneEnabled, + debug, + shutdownTimeoutMillis, + includes, + excludes, + notifyRead, + readyWrite, + messageRead); + latch.countDown(); + } + + @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]) { + context.unbindService(this); + bind(context, intent, flags, this); + } + } + }; + + if (!bind(context, intent, flags, connection)) { + return null; + } + boolean ready = 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; + } finally { + if (!ready) { + context.unbindService(connection); + } + } + } + + private static boolean bind( + final @NotNull Context context, + final @NotNull Intent intent, + 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 + return context.bindService(intent, flags, Runnable::run, connection); + } + return context.bindService(intent, connection, flags); + } + + private static void reattach( + final @NotNull IBinder service, + final @NotNull ILogger logger, + final @NotNull String nativeDatabasePath, + final @Nullable String nativeLibraryDir, + final int appPid, + final long appTid, + final boolean tombstoneEnabled, + final boolean debug, + final long shutdownTimeoutMillis, + final @NotNull ArrayList includes, + final @NotNull ArrayList excludes) { + 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; + } + + final ParcelFileDescriptor shm = ParcelFileDescriptor.adoptFd(shmFd); + ParcelFileDescriptor notifyRead = null; + ParcelFileDescriptor notifyWrite = null; + ParcelFileDescriptor readyRead = null; + ParcelFileDescriptor readyWrite = null; + ParcelFileDescriptor messageWrite = null; + ParcelFileDescriptor messageRead = null; + try { + final ParcelFileDescriptor[] notifyPipe = ParcelFileDescriptor.createPipe(); + final ParcelFileDescriptor[] readyPipe = ParcelFileDescriptor.createPipe(); + notifyRead = notifyPipe[0]; + notifyWrite = notifyPipe[1]; + readyRead = readyPipe[0]; + readyWrite = readyPipe[1]; + final ParcelFileDescriptor[] messageSocket = ParcelFileDescriptor.createSocketPair(); + messageWrite = messageSocket[0]; + messageRead = messageSocket[1]; + + final boolean reattached = + transactConfigure( + service, + nativeDatabasePath, + nativeLibraryDir, + shm, + appPid, + appTid, + tombstoneEnabled, + debug, + shutdownTimeoutMillis, + includes, + excludes, + notifyRead, + readyWrite, + messageRead) + && io.sentry.ndk.SentryNdk.reattachCrashDaemon( + notifyWrite.detachFd(), readyRead.detachFd(), messageWrite.detachFd()); + if (reattached) { + logger.log(SentryLevel.WARNING, "NDK crash service restarted, reattached the app."); + } else { + logger.log(SentryLevel.ERROR, "NDK crash service restarted, failed to reattach the app."); + } + } catch (IOException | SecurityException e) { + logger.log(SentryLevel.ERROR, e, "Failed to reattach to the NDK crash service."); + } finally { + closeQuietly(shm); + closeQuietly(notifyRead); + closeQuietly(notifyWrite); + closeQuietly(readyRead); + closeQuietly(readyWrite); + closeQuietly(messageWrite); + closeQuietly(messageRead); + } + } + + private static boolean transactConfigure( + final @NotNull IBinder service, + final @NotNull String nativeDatabasePath, + final @Nullable String nativeLibraryDir, + final @NotNull ParcelFileDescriptor shm, + final int appPid, + final long appTid, + final boolean tombstoneEnabled, + final boolean debug, + final long shutdownTimeoutMillis, + final @NotNull ArrayList includes, + final @NotNull ArrayList excludes, + final @NotNull ParcelFileDescriptor notifyRead, + final @NotNull ParcelFileDescriptor readyWrite, + final @NotNull ParcelFileDescriptor messageRead) { + final Parcel data = Parcel.obtain(); + final Parcel reply = Parcel.obtain(); + try { + data.writeInterfaceToken(BINDER_DESCRIPTOR); + data.writeString(nativeDatabasePath); + data.writeString(nativeLibraryDir); + data.writeInt(appPid); + data.writeLong(appTid); + data.writeInt(tombstoneEnabled ? 1 : 0); + data.writeInt(debug ? 1 : 0); + data.writeLong(shutdownTimeoutMillis); + data.writeStringList(includes); + data.writeStringList(excludes); + data.writeFileDescriptor(notifyRead.getFileDescriptor()); + data.writeFileDescriptor(readyWrite.getFileDescriptor()); + data.writeFileDescriptor(messageRead.getFileDescriptor()); + data.writeFileDescriptor(shm.getFileDescriptor()); + if (!service.transact(TRANSACTION_CONFIGURE, data, reply, 0)) { + return false; + } + reply.readException(); + return reply.readInt() == 1; + } catch (RemoteException | RuntimeException ignored) { + // readException() rethrows whatever the service process threw, the NDK integration then + // doesn't start + return false; + } finally { + data.recycle(); + reply.recycle(); + } + } + + @VisibleForTesting + boolean configureDaemon( + final @Nullable String nativeDatabasePath, + final @Nullable String nativeLibraryDir, + final @Nullable ParcelFileDescriptor shm, + final int appPid, + final long appTid, + final boolean tombstoneEnabled, + final boolean debug, + final long shutdownTimeoutMillis, + final @Nullable ArrayList includes, + final @Nullable ArrayList excludes, + final @Nullable ParcelFileDescriptor notifyRead, + final @Nullable ParcelFileDescriptor readyWrite, + final @Nullable ParcelFileDescriptor messageRead) { + if (nativeDatabasePath == null + || shm == null + || notifyRead == null + || readyWrite == null + || messageRead == null + || appPid < 0) { + closeQuietly(shm); + closeQuietly(notifyRead); + closeQuietly(readyWrite); + closeQuietly(messageRead); + return false; + } + + final DaemonConfig config = + new DaemonConfig( + nativeLibraryDir, + shm.detachFd(), + notifyRead.detachFd(), + readyWrite.detachFd(), + messageRead.detachFd(), + appPid, + appTid, + shutdownTimeoutMillis, + includes != null ? includes : new ArrayList<>(), + excludes != null ? excludes : new ArrayList<>(), + tombstoneEnabled, + debug); + // a relaunched app configures while the previous daemon may still be finishing + new Thread(() -> runDaemonWorker(config), "SentryNdkCrashService").start(); + return true; + } + + private void runDaemonWorker(final @NotNull DaemonConfig config) { + final SentryAndroidOptions options = new SentryAndroidOptions(); + options.setLogger(new AndroidLogger("SentryNdkCrash")); + options.setDebug(config.debug); + + try { + if (config.notifyReadFd < 0 || config.readyWriteFd < 0 || config.messageReadFd < 0) { + return; + } + + // keeps going after onDestroy, a crashed app's binding goes away mid-crash + try (final @Nullable CrashDaemon daemon = + io.sentry.ndk.SentryNdk.runCrashDaemon( + config.appPid, + config.appTid, + config.notifyReadFd, + config.readyWriteFd, + config.messageReadFd, + config.shmFd)) { + if (daemon == null) { + return; + } + final @Nullable String envelopePath = daemon.getEnvelopePath(); + if (envelopePath == null) { + return; + } + + final File envelope = new File(envelopePath); + final @Nullable MergedEnvelope mergedEnvelope = + config.tombstoneEnabled ? waitForMergedEnvelope(options, envelope, config) : null; + if (mergedEnvelope != null) { + // native keeps the envelope for the next launch until it is sent + try { + writeLastTombstoneMarker(envelope, mergedEnvelope.tombstoneTimestamp); + } catch (IOException e) { + options.getLogger().log(SentryLevel.DEBUG, e, "Failed to write the tombstone marker."); + } + } + final @Nullable File mergedFile = mergedEnvelope != null ? mergedEnvelope.file : null; + if (mergedFile == null && config.tombstoneEnabled) { + options + .getLogger() + .log(SentryLevel.DEBUG, "Sending NDK crash without tombstone enrichment."); + } + + final CrashDaemon.SendResult result = + daemon.sendEnvelope( + mergedFile != null ? mergedFile.getPath() : envelope.getPath(), + config.shutdownTimeoutMillis); + if (result == CrashDaemon.SendResult.FAILED) { + options.getLogger().log(SentryLevel.DEBUG, "Failed to send NDK crash envelope."); + } + } + } catch (InterruptedException e) { + options.getLogger().log(SentryLevel.DEBUG, e, "Error running NDK crash service."); + } + } + + @SuppressLint("NewApi") + private @Nullable MergedEnvelope waitForMergedEnvelope( + final @NotNull SentryAndroidOptions options, + final @NotNull File envelope, + final @NotNull DaemonConfig config) + throws InterruptedException { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { + return null; + } + + final @Nullable NativeEnvelope nativeEnvelope = readNativeEnvelope(options, envelope); + final @Nullable Date nativeTimestamp = + nativeEnvelope != null ? nativeEnvelope.event.getTimestamp() : null; + if (nativeTimestamp == null) { + return null; + } + + // the app exits once its tombstone is written, a later exit would not match + final @NotNull Deadline deadline = + Deadline.after(options.getMonotonicTicker(), MATCH_TOLERANCE_MILLIS, TimeUnit.MILLISECONDS); + while (true) { + final @Nullable ApplicationExitInfo exitInfo = + findMatchingExitInfo(options, nativeTimestamp, config.appPid); + if (exitInfo != null) { + if (exitInfo.getReason() != ApplicationExitInfo.REASON_CRASH_NATIVE) { + return null; + } + try { + final @Nullable MergedEnvelope mergedEnvelope = + processEnvelope(options, envelope, nativeEnvelope, exitInfo, config); + if (mergedEnvelope != null) { + return mergedEnvelope; + } + } catch (Exception e) { + // the tombstone comes from the system and parsing it can throw anything, the crash is + // then sent without it + ExceptionUtils.rethrowIfFatal(e); + options.getLogger().log(SentryLevel.DEBUG, e, "Failed to merge NDK tombstone envelope."); + return new MergedEnvelope(null, exitInfo.getTimestamp()); + } + } + + final long remainingMillis = deadline.remaining(TimeUnit.MILLISECONDS); + if (remainingMillis <= 0) { + return exitInfo != null ? new MergedEnvelope(null, exitInfo.getTimestamp()) : null; + } + Thread.sleep(Math.min(POLL_INTERVAL_MILLIS, remainingMillis)); + } + } + + @SuppressLint("NewApi") + private @Nullable MergedEnvelope processEnvelope( + final @NotNull SentryAndroidOptions options, + final @NotNull File file, + final @NotNull NativeEnvelope nativeEnvelope, + final @NotNull ApplicationExitInfo exitInfo, + final @NotNull DaemonConfig config) + throws Exception { + try (final @Nullable InputStream tombstoneInputStream = exitInfo.getTraceInputStream()) { + if (tombstoneInputStream == null) { + return null; + } + + final SentryEvent tombstoneEvent; + try (final TombstoneParser parser = + new TombstoneParser( + tombstoneInputStream, + config.inAppIncludes, + config.inAppExcludes, + config.nativeLibraryDir)) { + tombstoneEvent = parser.parse(); + } + tombstoneEvent.setTimestamp(DateUtils.getDateTime(exitInfo.getTimestamp())); + + TombstoneIntegration.TombstonePolicy.mergeNativeCrashes(nativeEnvelope.event, tombstoneEvent); + final File mergedEnvelope = writeMergedEnvelope(options, file, nativeEnvelope); + return new MergedEnvelope(mergedEnvelope, exitInfo.getTimestamp()); + } + } + + @VisibleForTesting + @SuppressLint("NewApi") + @Nullable + ApplicationExitInfo findMatchingExitInfo( + final @NotNull SentryAndroidOptions options, + final @NotNull Date nativeTimestamp, + final int pid) { + final @Nullable ActivityManager activityManager = + (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + if (activityManager == null) { + return null; + } + + final List exitInfos = + activityManager.getHistoricalProcessExitReasons(null, 0, 10); + ApplicationExitInfo bestMatch = null; + long bestDiff = Long.MAX_VALUE; + for (ApplicationExitInfo exitInfo : exitInfos) { + if (exitInfo.getPid() != pid) { + continue; + } + final long diff = Math.abs(exitInfo.getTimestamp() - nativeTimestamp.getTime()); + if (diff < bestDiff) { + bestDiff = diff; + bestMatch = exitInfo; + } + } + + if (bestMatch != null && bestDiff <= MATCH_TOLERANCE_MILLIS) { + options + .getLogger() + .log(SentryLevel.DEBUG, "Matched NDK tombstone with diff %d ms.", bestDiff); + return bestMatch; + } + return null; + } + + private @Nullable NativeEnvelope readNativeEnvelope( + final @NotNull SentryAndroidOptions options, final @NotNull File file) { + try (final InputStream stream = new BufferedInputStream(new FileInputStream(file))) { + final @Nullable SentryEnvelope envelope = options.getEnvelopeReader().read(stream); + if (envelope == null) { + return null; + } + for (SentryEnvelopeItem item : envelope.getItems()) { + if (item.getHeader().getType() != SentryItemType.Event) { + continue; + } + final @Nullable SentryEvent event = item.getEvent(options.getSerializer()); + if (event != null && "native".equals(event.getPlatform())) { + return new NativeEnvelope(envelope, event); + } + } + } catch (Exception e) { + // getEvent() throws Exception, the crash is then sent without tombstone enrichment + ExceptionUtils.rethrowIfFatal(e); + options.getLogger().log(SentryLevel.DEBUG, e, "Failed to read NDK envelope."); + } + return null; + } + + private @NotNull File writeMergedEnvelope( + final @NotNull SentryAndroidOptions options, + final @NotNull File sourceFile, + final @NotNull NativeEnvelope nativeEnvelope) + throws Exception { + final List items = new ArrayList<>(); + items.add(SentryEnvelopeItem.fromEvent(options.getSerializer(), nativeEnvelope.event)); + for (SentryEnvelopeItem item : nativeEnvelope.envelope.getItems()) { + if (item.getHeader().getType() != SentryItemType.Event) { + items.add(item); + } + } + + final SentryEnvelope mergedEnvelope = + new SentryEnvelope(nativeEnvelope.envelope.getHeader(), items); + final File mergedFile = new File(sourceFile.getPath() + MERGED_SUFFIX); + final File tmpFile = new File(mergedFile.getPath() + ".tmp"); + try (final OutputStream outputStream = new FileOutputStream(tmpFile)) { + options.getSerializer().serialize(mergedEnvelope, outputStream); + } + if (!tmpFile.renameTo(mergedFile)) { + throw new IllegalStateException("Failed to publish merged envelope"); + } + options.getLogger().log(SentryLevel.DEBUG, "Wrote merged NDK tombstone envelope."); + return mergedFile; + } + + // workers for concurrent crashes must not move the marker back + private static synchronized void writeLastTombstoneMarker( + final @NotNull File envelopeFile, final long timestamp) throws IOException { + final @Nullable File runDir = envelopeFile.getParentFile(); + final @Nullable File nativeDir = runDir != null ? runDir.getParentFile() : null; + final @Nullable File cacheDir = nativeDir != null ? nativeDir.getParentFile() : null; + if (cacheDir == null) { + return; + } + final File marker = new File(cacheDir, AndroidEnvelopeCache.LAST_TOMBSTONE_REPORT); + final @Nullable String lastTimestamp = FileUtils.readText(marker); + try { + if (lastTimestamp != null && Long.parseLong(lastTimestamp.trim()) >= timestamp) { + return; + } + } catch (NumberFormatException ignored) { + // overwrite an invalid marker + } + try (final OutputStream outputStream = new FileOutputStream(marker)) { + outputStream.write(String.valueOf(timestamp).getBytes("UTF-8")); + } + } + + private static final class NativeEnvelope { + private final @NotNull SentryEnvelope envelope; + private final @NotNull SentryEvent event; + + private NativeEnvelope( + final @NotNull SentryEnvelope envelope, final @NotNull SentryEvent event) { + this.envelope = envelope; + this.event = event; + } + } + + private static final class MergedEnvelope { + // null when the matched tombstone did not merge, the native event still reports its crash + private final @Nullable File file; + private final long tombstoneTimestamp; + + private MergedEnvelope(final @Nullable File file, final long tombstoneTimestamp) { + this.file = file; + this.tombstoneTimestamp = tombstoneTimestamp; + } + } + + private static final class DaemonConfig { + private final @Nullable String nativeLibraryDir; + private final int shmFd; + private final int notifyReadFd; + private final int readyWriteFd; + private final int messageReadFd; + private final int appPid; + private final long appTid; + private final long shutdownTimeoutMillis; + private final @NotNull List inAppIncludes; + private final @NotNull List inAppExcludes; + private final boolean tombstoneEnabled; + private final boolean debug; + + private DaemonConfig( + final @Nullable String nativeLibraryDir, + final int shmFd, + final int notifyReadFd, + final int readyWriteFd, + final int messageReadFd, + final int appPid, + final long appTid, + final long shutdownTimeoutMillis, + final @NotNull List inAppIncludes, + final @NotNull List inAppExcludes, + final boolean tombstoneEnabled, + final boolean debug) { + this.nativeLibraryDir = nativeLibraryDir; + this.shmFd = shmFd; + this.notifyReadFd = notifyReadFd; + this.readyWriteFd = readyWriteFd; + this.messageReadFd = messageReadFd; + this.appPid = appPid; + this.appTid = appTid; + this.shutdownTimeoutMillis = shutdownTimeoutMillis; + this.inAppIncludes = inAppIncludes; + this.inAppExcludes = inAppExcludes; + this.tombstoneEnabled = tombstoneEnabled; + this.debug = debug; + } + } +} 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 new file mode 100644 index 00000000000..0a18bf19660 --- /dev/null +++ b/sentry-android-ndk-outproc/src/main/java/io/sentry/android/ndk/outproc/SentryNdkOutproc.java @@ -0,0 +1,178 @@ +package io.sentry.android.ndk.outproc; + +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; +import io.sentry.android.ndk.DebugImagesLoader; +import io.sentry.android.ndk.NdkScopeObserver; +import io.sentry.ndk.NativeModuleListLoader; +import io.sentry.ndk.NdkOptions; +import io.sentry.protocol.SdkVersion; +import io.sentry.util.Objects; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +@ApiStatus.Internal +public final class SentryNdkOutproc { + + private static final @NotNull String PACKAGE_NAME = "maven:io.sentry:sentry-android-ndk-outproc"; + + private static final @NotNull CountDownLatch loadLibraryLatch = new CountDownLatch(1); + + @SuppressLint("StaticFieldLeak") // the application context from NdkIntegration + private static @Nullable Context serviceContext; + + private static @Nullable ServiceConnection serviceConnection; + + private SentryNdkOutproc() {} + + static { + new Thread( + () -> { + try { + //noinspection UnstableApiUsage + io.sentry.ndk.SentryNdk.loadNativeLibraries(); + } catch (UnsatisfiedLinkError e) { + // ignored + // if loadLibrary() fails, the later init() will throw an exception anyway + } finally { + loadLibraryLatch.countDown(); + } + }, + "SentryNdkLoadLibs") + .start(); + } + + /** + * Init the NDK integration + * + * @param options the SentryAndroidOptions + */ + public static void init(@NotNull final SentryAndroidOptions options) { + init(null, options); + } + + /** + * Init the NDK integration + * + * @param context the Android context + * @param options the SentryAndroidOptions + */ + 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+"); + } + + addPackage(options.getSdkVersion()); + try { + if (loadLibraryLatch.await(2000, TimeUnit.MILLISECONDS)) { + final @NotNull NdkOptions ndkOptions = + new NdkOptions( + Objects.requireNonNull(options.getDsn(), "DSN is required for sentry-ndk"), + options.isDebug(), + Objects.requireNonNull( + options.getOutboxPath(), "outbox path is required for sentry-ndk"), + options.getRelease(), + options.getEnvironment(), + options.getDist(), + options.getMaxBreadcrumbs(), + options.getNativeSdkName()); + + final int handlerStrategy = options.getNdkHandlerStrategy(); + if (handlerStrategy == NdkHandlerStrategy.SENTRY_HANDLER_STRATEGY_DEFAULT.getValue()) { + ndkOptions.setNdkHandlerStrategy( + io.sentry.ndk.NdkHandlerStrategy.SENTRY_HANDLER_STRATEGY_DEFAULT); + } else if (handlerStrategy + == NdkHandlerStrategy.SENTRY_HANDLER_STRATEGY_CHAIN_AT_START.getValue()) { + ndkOptions.setNdkHandlerStrategy( + io.sentry.ndk.NdkHandlerStrategy.SENTRY_HANDLER_STRATEGY_CHAIN_AT_START); + } + + final @Nullable Double tracesSampleRate = options.getTracesSampleRate(); + if (tracesSampleRate == null) { + ndkOptions.setTracesSampleRate(0.0f); + } else { + ndkOptions.setTracesSampleRate(tracesSampleRate.floatValue()); + } + + ndkOptions.setEnableAppHangTracking(options.isEnableNdkAppHangTracking()); + ndkOptions.setAppHangTimeoutMillis(options.getNdkAppHangTimeoutIntervalMillis()); + + final @Nullable ServiceConnection connection = + SentryNdkCrashService.start(context, options); + if (connection == null) { + throw new IllegalStateException("Failed to start the NDK crash service"); + } + serviceContext = context; + serviceConnection = connection; + + boolean initialized = false; + try { + //noinspection UnstableApiUsage + io.sentry.ndk.SentryNdk.init(ndkOptions); + initialized = true; + } finally { + if (!initialized) { + unbindCrashService(); + } + } + + // only add scope sync observer if the scope sync is enabled. + if (options.isEnableScopeSync()) { + options.addScopeObserver(new NdkScopeObserver(options)); + } + + options.setDebugImagesLoader(new DebugImagesLoader(options, new NativeModuleListLoader())); + } else { + throw new IllegalStateException("Timeout waiting for Sentry NDK library to load"); + } + } catch (InterruptedException e) { + throw new IllegalStateException( + "Thread interrupted while waiting for NDK libs to be loaded", e); + } + } + + /** Closes the NDK integration */ + public static void close() { + try { + if (loadLibraryLatch.await(2000, TimeUnit.MILLISECONDS)) { + //noinspection UnstableApiUsage + io.sentry.ndk.SentryNdk.close(); + } else { + throw new IllegalStateException("Timeout waiting for Sentry NDK library to load"); + } + } catch (InterruptedException e) { + throw new IllegalStateException( + "Thread interrupted while waiting for NDK libs to be loaded", e); + } finally { + unbindCrashService(); + } + } + + private static void addPackage(final @Nullable SdkVersion sdkVersion) { + SentryIntegrationPackageStorage.getInstance() + .addPackage(PACKAGE_NAME, BuildConfig.VERSION_NAME); + if (sdkVersion != null) { + sdkVersion.addPackage(PACKAGE_NAME, BuildConfig.VERSION_NAME); + } + } + + private static void unbindCrashService() { + final @Nullable Context context = serviceContext; + final @Nullable ServiceConnection connection = serviceConnection; + serviceContext = null; + serviceConnection = null; + if (context != null && connection != null) { + context.unbindService(connection); + } + } +} 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 new file mode 100644 index 00000000000..61d56f4236b --- /dev/null +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/NativeBackendTest.kt @@ -0,0 +1,93 @@ +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 +import kotlin.test.assertFailsWith +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mockito +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.mock +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [31]) +class NativeBackendTest { + @Test + fun `defaults missing traces sample rate to zero`() { + initialize({ tracesSampleRate = null }) { assertThat(it.tracesSampleRate).isEqualTo(0.0f) } + } + + @Test + fun `propagates traces sample rate`() { + initialize({ tracesSampleRate = 0.75 }) { assertThat(it.tracesSampleRate).isEqualTo(0.75f) } + } + + @Test + fun `does not enable app hang tracking by default`() { + initialize { + assertThat(it.isEnableAppHangTracking).isFalse() + assertThat(it.appHangTimeoutMillis).isEqualTo(5000L) + } + } + + @Test + fun `propagates app hang tracking options`() { + initialize( + { + isEnableNdkAppHangTracking = true + ndkAppHangTimeoutIntervalMillis = 2000 + }, + ) { + assertThat(it.isEnableAppHangTracking).isTrue() + assertThat(it.appHangTimeoutMillis).isEqualTo(2000L) + } + } + + @Test + fun `fails without a context`() { + 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" + cacheDirPath = "/cache" + } + + private fun initialize( + configure: SentryAndroidOptions.() -> Unit = {}, + verify: (NdkOptions) -> Unit, + ) { + val context = mock() + val options = options().apply(configure) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + Mockito.mockStatic(SentryNdkCrashService::class.java).use { service -> + var captured: NdkOptions? = null + native + .`when` { io.sentry.ndk.SentryNdk.init(any()) } + .doAnswer { captured = it.arguments[0] as NdkOptions } + service + .`when` { SentryNdkCrashService.start(context, options) } + .thenReturn(mock()) + + SentryNdkOutproc.init(context, options) + + service.verify { SentryNdkCrashService.start(context, options) } + assertThat(captured).isNotNull() + verify(captured!!) + } + } + } +} 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 new file mode 100644 index 00000000000..15f47d70780 --- /dev/null +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryNdkCrashServiceTest.kt @@ -0,0 +1,514 @@ +package io.sentry.android.ndk.outproc + +import android.app.ActivityManager +import android.app.ApplicationExitInfo +import android.content.ComponentName +import android.content.Context +import android.os.Binder +import android.os.Parcel +import android.os.ParcelFileDescriptor +import com.google.common.truth.Truth.assertThat +import io.sentry.DateUtils +import io.sentry.SentryEnvelope +import io.sentry.SentryEvent +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 java.io.File +import java.io.InputStream +import java.util.Date +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.zip.GZIPInputStream +import kotlin.test.assertFailsWith +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.Mockito +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.shadows.ShadowActivityManager.ApplicationExitInfoBuilder +import org.robolectric.shadows.ShadowSystemClock + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [31], shadows = [SentryShadowParcelFileDescriptor::class]) +class SentryNdkCrashServiceTest { + private val app = RuntimeEnvironment.getApplication() + private val component = ComponentName(app, SentryNdkCrashService::class.java) + private val options = + SentryAndroidOptions().apply { + dsn = "https://key@sentry.io/proj" + cacheDirPath = app.cacheDir.absolutePath + } + + @Test + fun `binds without starting the service`() { + configure(true) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { + val connection = SentryNdkCrashService.start(app, options) + + assertThat(connection).isNotNull() + assertThat(shadowOf(app).boundServiceConnections).containsExactly(connection) + assertThat(shadowOf(app).unboundServiceConnections).isEmpty() + // robolectric records the bind intent as started, a startService call would add another + assertThat(shadowOf(app).allStartedServices).hasSize(1) + } + } + + @Test + fun `unbinds when the service does not configure`() { + configure(false) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { + assertThat(SentryNdkCrashService.start(app, options)).isNull() + + assertThat(shadowOf(app).boundServiceConnections).isEmpty() + assertThat(shadowOf(app).unboundServiceConnections).hasSize(1) + } + } + + @Test + fun `does not bind without the native libraries`() { + configure(true) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native + .`when` { io.sentry.ndk.SentryNdk.loadNativeLibraries() } + .thenThrow(UnsatisfiedLinkError()) + + assertFailsWith { SentryNdkCrashService.start(app, options) } + + assertThat(shadowOf(app).boundServiceConnections).isEmpty() + assertThat(shadowOf(app).unboundServiceConnections).isEmpty() + } + } + + @Test + fun `close unbinds the service`() { + configure(true) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { + SentryNdkOutproc.init(app, options) + val connection = shadowOf(app).boundServiceConnections.single() + + SentryNdkOutproc.close() + + assertThat(shadowOf(app).boundServiceConnections).isEmpty() + assertThat(shadowOf(app).unboundServiceConnections).containsExactly(connection) + } + } + + @Test + fun `init unbinds when native init fails`() { + configure(true) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native + .`when` { io.sentry.ndk.SentryNdk.init(any()) } + .thenThrow(UnsatisfiedLinkError()) + + assertFailsWith { SentryNdkOutproc.init(app, options) } + + assertThat(shadowOf(app).boundServiceConnections).isEmpty() + assertThat(shadowOf(app).unboundServiceConnections).hasSize(1) + } + } + + @Test + fun `init fails when the service does not bind`() { + shadowOf(app).declareComponentUnbindable(component) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + assertFailsWith { SentryNdkOutproc.init(app, options) } + + native.verify({ io.sentry.ndk.SentryNdk.init(any()) }, never()) + } + } + + @Test + fun `reattaches when the restarted service connects again`() { + val binder = configure(true) + 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(app, options)!! + + connection.onServiceDisconnected(component) + connection.onServiceConnected(component, binder) + + assertThat(binder.transactions).isEqualTo(2) + native.verify { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) } + } + } + + @Test + fun `does not reattach without a crash IPC`() { + val binder = configure(true) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { native -> + native.`when` { io.sentry.ndk.SentryNdk.dupCrashShmFd() }.thenReturn(-1) + val connection = SentryNdkCrashService.start(app, options)!! + + connection.onServiceConnected(component, binder) + + assertThat(binder.transactions).isEqualTo(1) + native.verify( + { io.sentry.ndk.SentryNdk.reattachCrashDaemon(any(), any(), any()) }, + never(), + ) + } + } + + @Test + fun `binds again when the binding died`() { + configure(true) + Mockito.mockStatic(io.sentry.ndk.SentryNdk::class.java).use { + val connection = SentryNdkCrashService.start(app, options)!! + + connection.onBindingDied(component) + + assertThat(shadowOf(app).boundServiceConnections).containsExactly(connection) + // robolectric records each bind intent as started + assertThat(shadowOf(app).allStartedServices).hasSize(2) + } + } + + @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) + + assertFailsWith { SentryNdkOutproc.init(app, options) } + + assertThat(shadowOf(app).boundServiceConnections).isEmpty() + native.verify({ io.sentry.ndk.SentryNdk.init(any()) }, never()) + } + } + + @Test + fun `matches the exit info of the app pid`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + addExitInfo(service, pid = 1, timestamp = 2000) + addExitInfo(service, pid = 2, timestamp = 1000) + + assertThat(service.findMatchingExitInfo(options, Date(2000), 2)?.pid).isEqualTo(2) + } + + @Test + fun `ignores exit infos of other pids`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + addExitInfo(service, pid = 1, timestamp = 1000) + + assertThat(service.findMatchingExitInfo(options, Date(1000), 2)).isNull() + } + + @Test + @Config(instrumentedPackages = ["io.sentry.ndk"], shadows = [BlockingCrashDaemonShadow::class]) + fun `starts a daemon for a relaunched app while the previous one finishes`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + try { + configureDaemon(service, pid = 1, fd = 10) + assertThat(BlockingCrashDaemonShadow.daemons.poll(5, TimeUnit.SECONDS)) + .isEqualTo(listOf(1, 10, 11, 12, 13)) + + configureDaemon(service, pid = 2, fd = 20) + assertThat(BlockingCrashDaemonShadow.daemons.poll(5, TimeUnit.SECONDS)) + .isEqualTo(listOf(2, 20, 21, 22, 23)) + } finally { + BlockingCrashDaemonShadow.release.countDown() + } + } + + @Test + @Config(instrumentedPackages = ["io.sentry.ndk"], shadows = [CrashDaemonShadow::class]) + fun `sends the merged envelope and writes the marker`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + val envelope = writeNativeEnvelope(timestamp = 1000) + addExitInfo(service, pid = 1, timestamp = 2000, trace = tombstone()) + crashDaemon(envelope, CrashDaemon.SendResult.SENT) + + configureDaemon(service, pid = 1, fd = 10, tombstoneEnabled = true) + awaitWorker() + + assertThat(CrashDaemonShadow.sends).containsExactly(listOf("${envelope.path}.merged", 2000L)) + assertThat(marker().readText()).isEqualTo("2000") + } + + @Test + @Config(instrumentedPackages = ["io.sentry.ndk"], shadows = [CrashDaemonShadow::class]) + fun `writes the marker when the merged envelope is kept`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + val envelope = writeNativeEnvelope(timestamp = 1000) + addExitInfo(service, pid = 1, timestamp = 2000, trace = tombstone()) + crashDaemon(envelope, CrashDaemon.SendResult.KEPT) + + configureDaemon(service, pid = 1, fd = 10, tombstoneEnabled = true) + awaitWorker() + + assertThat(marker().readText()).isEqualTo("2000") + } + + @Test + @Config(instrumentedPackages = ["io.sentry.ndk"], shadows = [CrashDaemonShadow::class]) + fun `keeps a newer marker`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + val envelope = writeNativeEnvelope(timestamp = 1000) + addExitInfo(service, pid = 1, timestamp = 2000, trace = tombstone()) + crashDaemon(envelope, CrashDaemon.SendResult.SENT) + marker().writeText("3000") + + configureDaemon(service, pid = 1, fd = 10, tombstoneEnabled = true) + awaitWorker() + + assertThat(CrashDaemonShadow.sends).containsExactly(listOf("${envelope.path}.merged", 2000L)) + assertThat(marker().readText()).isEqualTo("3000") + } + + @Test + @Config(instrumentedPackages = ["io.sentry.ndk"], shadows = [CrashDaemonShadow::class]) + fun `writes the marker when the send fails`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + val envelope = writeNativeEnvelope(timestamp = 1000) + addExitInfo(service, pid = 1, timestamp = 2000, trace = tombstone()) + crashDaemon(envelope, CrashDaemon.SendResult.FAILED) + + configureDaemon(service, pid = 1, fd = 10, tombstoneEnabled = true) + awaitWorker() + + assertThat(CrashDaemonShadow.sends).containsExactly(listOf("${envelope.path}.merged", 2000L)) + assertThat(marker().readText()).isEqualTo("2000") + } + + @Test + @Config(instrumentedPackages = ["io.sentry.ndk"], shadows = [CrashDaemonShadow::class]) + fun `sends without a tombstone when the app did not crash natively`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + val envelope = writeNativeEnvelope(timestamp = 1000) + addExitInfo(service, pid = 1, timestamp = 2000, reason = ApplicationExitInfo.REASON_SIGNALED) + crashDaemon(envelope, CrashDaemon.SendResult.SENT) + + configureDaemon(service, pid = 1, fd = 10, tombstoneEnabled = true) + awaitWorker() + + assertThat(CrashDaemonShadow.sends).containsExactly(listOf(envelope.path, 2000L)) + assertThat(marker().exists()).isFalse() + } + + @Test + @Config(instrumentedPackages = ["io.sentry.ndk"], shadows = [CrashDaemonShadow::class]) + fun `sends without a tombstone when it does not parse`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + val envelope = writeNativeEnvelope(timestamp = 1000) + addExitInfo(service, pid = 1, timestamp = 2000, trace = "invalid".byteInputStream()) + crashDaemon(envelope, CrashDaemon.SendResult.SENT) + + configureDaemon(service, pid = 1, fd = 10, tombstoneEnabled = true) + awaitWorker() + + assertThat(CrashDaemonShadow.sends).containsExactly(listOf(envelope.path, 2000L)) + assertThat(marker().readText()).isEqualTo("2000") + } + + @Test + @Config(instrumentedPackages = ["io.sentry.ndk"], shadows = [CrashDaemonShadow::class]) + fun `writes the marker when the tombstone stays unavailable`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + val envelope = writeNativeEnvelope(timestamp = 1000) + addExitInfo(service, pid = 1, timestamp = 2000) + crashDaemon(envelope, CrashDaemon.SendResult.SENT) + + val threads = Thread.getAllStackTraces().keys + configureDaemon(service, pid = 1, fd = 10, tombstoneEnabled = true) + val worker = + (Thread.getAllStackTraces().keys - threads).single { it.name == "SentryNdkCrashService" } + // pass the deadline once the worker polls for the tombstone + while (worker.isAlive && worker.state != Thread.State.TIMED_WAITING) { + Thread.yield() + } + ShadowSystemClock.advanceBy(30, TimeUnit.SECONDS) + worker.join(5000) + + assertThat(CrashDaemonShadow.sends).containsExactly(listOf(envelope.path, 2000L)) + assertThat(marker().readText()).isEqualTo("2000") + } + + @Test + fun `closes the fds when it does not configure`() { + val service = Robolectric.setupService(SentryNdkCrashService::class.java) + val fds = listOf(descriptor(10), descriptor(11), descriptor(12), descriptor(13)) + + val configured = + service.configureDaemon( + "db", + null, + fds[0], + -1, + 0L, + false, + false, + 2000L, + null, + null, + fds[1], + fds[2], + fds[3], + ) + + assertThat(configured).isFalse() + fds.forEach { Mockito.verify(it).close() } + } + + private fun addExitInfo( + context: Context, + pid: Int, + timestamp: Long, + reason: Int = ApplicationExitInfo.REASON_CRASH_NATIVE, + trace: InputStream? = null, + ) { + val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + shadowOf(activityManager) + .addApplicationExitInfo( + ApplicationExitInfoBuilder.newBuilder() + .setPid(pid) + .setReason(reason) + .setTimestamp(timestamp) + .setTraceInputStream(trace) + .build(), + ) + } + + private fun configureDaemon( + service: SentryNdkCrashService, + pid: Int, + fd: Int, + tombstoneEnabled: Boolean = false, + ) { + val configured = + service.configureDaemon( + "db", + null, + descriptor(fd + 3), + pid, + 0L, + tombstoneEnabled, + false, + 2000L, + null, + null, + descriptor(fd), + descriptor(fd + 1), + descriptor(fd + 2), + ) + assertThat(configured).isTrue() + } + + private fun writeNativeEnvelope(timestamp: Long): File { + val event = SentryEvent(DateUtils.getDateTime(timestamp)).apply { platform = "native" } + val file = File(app.cacheDir, ".sentry-native/test.run/${event.eventId}.envelope") + file.parentFile!!.mkdirs() + file.outputStream().use { + options.serializer.serialize(SentryEnvelope.from(options.serializer, event, null), it) + } + return file + } + + private fun tombstone(): InputStream = + GZIPInputStream(File("../sentry-android-core/src/test/resources/tombstone.pb.gz").inputStream()) + + private fun crashDaemon(envelope: File, result: CrashDaemon.SendResult) { + CrashDaemonShadow.envelopePath = envelope.path + CrashDaemonShadow.result = result + CrashDaemonShadow.sends.clear() + } + + private fun awaitWorker() { + Thread.getAllStackTraces() + .keys + .filter { it.name == "SentryNdkCrashService" } + .forEach { it.join(5000) } + } + + private fun marker(): File = File(app.cacheDir, AndroidEnvelopeCache.LAST_TOMBSTONE_REPORT) + + private fun descriptor(fd: Int): ParcelFileDescriptor = mock { on { detachFd() } doReturn fd } + + private fun configure(configured: Boolean) = + object : Binder() { + var transactions = 0 + + override fun onTransact(code: Int, data: Parcel, reply: Parcel?, flags: Int): Boolean { + transactions++ + reply?.writeNoException() + reply?.writeInt(if (configured) 1 else 0) + return true + } + } + .also { shadowOf(app).setComponentNameAndServiceForBindService(component, it) } +} + +@Implements(io.sentry.ndk.SentryNdk::class) +class BlockingCrashDaemonShadow { + companion object { + val daemons = LinkedBlockingQueue>() + val release = CountDownLatch(1) + + @Suppress("unused") + @Implementation + @JvmStatic + fun runCrashDaemon( + appPid: Int, + appTid: Long, + notifyFd: Int, + readyFd: Int, + messageFd: Int, + shmFd: Int, + ): CrashDaemon? { + daemons.add(listOf(appPid, notifyFd, readyFd, messageFd, shmFd)) + release.await(10, TimeUnit.SECONDS) + return null + } + } +} + +@Implements(io.sentry.ndk.SentryNdk::class) +class CrashDaemonShadow { + companion object { + var envelopePath = "" + var result = CrashDaemon.SendResult.SENT + val sends = mutableListOf>() + + @Suppress("unused") @Implementation @JvmStatic fun loadNativeLibraries() {} + + @Suppress("unused", "UNUSED_PARAMETER") + @Implementation + @JvmStatic + fun nativeRunCrashDaemon( + appPid: Int, + appTid: Long, + notifyFd: Int, + readyFd: Int, + messageFd: Int, + shmFd: Int, + ): Long = 1L + + @Suppress("unused", "UNUSED_PARAMETER") + @Implementation + @JvmStatic + fun nativeGetCrashEnvelopePath(handle: Long): String = envelopePath + + @Suppress("unused", "UNUSED_PARAMETER") + @Implementation + @JvmStatic + fun nativeSendEnvelope(handle: Long, path: String, timeout: Long): Int { + sends.add(listOf(path, timeout)) + return result.ordinal + } + } +} diff --git a/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryShadowParcelFileDescriptor.kt b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryShadowParcelFileDescriptor.kt new file mode 100644 index 00000000000..0035c13a2ed --- /dev/null +++ b/sentry-android-ndk-outproc/src/test/java/io/sentry/android/ndk/outproc/SentryShadowParcelFileDescriptor.kt @@ -0,0 +1,22 @@ +package io.sentry.android.ndk.outproc + +import android.os.ParcelFileDescriptor +import java.io.File +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.shadows.ShadowParcelFileDescriptor + +// the real detachFd needs Android's FileDescriptor ownership API, missing on the JVM +@Implements(ParcelFileDescriptor::class) +class SentryShadowParcelFileDescriptor : ShadowParcelFileDescriptor() { + @Suppress("unused") @Implementation fun detachFd(): Int = -1 + + companion object { + // the real adoptFd needs the same API + @Suppress("unused", "UNUSED_PARAMETER") + @Implementation + @JvmStatic + fun adoptFd(fd: Int): ParcelFileDescriptor = + ParcelFileDescriptor.open(File("/dev/null"), ParcelFileDescriptor.MODE_READ_ONLY) + } +} diff --git a/sentry-android-ndk/api/sentry-android-ndk.api b/sentry-android-ndk/api/sentry-android-ndk.api index 0c2ae5c90f8..397e4b2bfd4 100644 --- a/sentry-android-ndk/api/sentry-android-ndk.api +++ b/sentry-android-ndk/api/sentry-android-ndk.api @@ -29,6 +29,7 @@ public final class io/sentry/android/ndk/NdkScopeObserver : io/sentry/ScopeObser public final class io/sentry/android/ndk/SentryNdk { public static fun close ()V + public static fun init (Landroid/content/Context;Lio/sentry/android/core/SentryAndroidOptions;)V public static fun init (Lio/sentry/android/core/SentryAndroidOptions;)V } diff --git a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/NdkScopeObserver.java b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/NdkScopeObserver.java index c35a294c828..0ec3446aa83 100644 --- a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/NdkScopeObserver.java +++ b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/NdkScopeObserver.java @@ -39,16 +39,15 @@ public void setUser(final @Nullable User user) { try { options .getExecutorService() - .submit( - () -> { - if (user == null) { - // remove user if its null - nativeScope.removeUser(); - } else { - nativeScope.setUser( - user.getId(), user.getEmail(), user.getIpAddress(), user.getUsername()); - } - }); + .submit(() -> { + if (user == null) { + // remove user if its null + nativeScope.removeUser(); + } else { + nativeScope.setUser( + user.getId(), user.getEmail(), user.getIpAddress(), user.getUsername()); + } + }); } catch (Throwable e) { options.getLogger().log(SentryLevel.ERROR, e, "Scope sync setUser has an error."); } @@ -68,34 +67,26 @@ public void addBreadcrumb(final @NotNull Breadcrumb crumb) { try { options .getExecutorService() - .submit( - () -> { - String level = null; - if (crumb.getLevel() != null) { - level = crumb.getLevel().name().toLowerCase(Locale.ROOT); - } - final String timestamp = DateUtils.getTimestamp(crumb.getTimestamp()); - - String data = null; - try { - final Map dataRef = crumb.getData(); - if (!dataRef.isEmpty()) { - data = options.getSerializer().serialize(dataRef); - } - } catch (Throwable e) { - options - .getLogger() - .log(SentryLevel.ERROR, e, "Breadcrumb data is not serializable."); - } - - nativeScope.addBreadcrumb( - level, - crumb.getMessage(), - crumb.getCategory(), - crumb.getType(), - timestamp, - data); - }); + .submit(() -> { + String level = null; + if (crumb.getLevel() != null) { + level = crumb.getLevel().name().toLowerCase(Locale.ROOT); + } + final String timestamp = DateUtils.getTimestamp(crumb.getTimestamp()); + + String data = null; + try { + final Map dataRef = crumb.getData(); + if (!dataRef.isEmpty()) { + data = options.getSerializer().serialize(dataRef); + } + } catch (Throwable e) { + options.getLogger().log(SentryLevel.ERROR, e, "Breadcrumb data is not serializable."); + } + + nativeScope.addBreadcrumb( + level, crumb.getMessage(), crumb.getCategory(), crumb.getType(), timestamp, data); + }); } catch (Throwable e) { options.getLogger().log(SentryLevel.ERROR, e, "Scope sync addBreadcrumb has an error."); } @@ -148,10 +139,9 @@ public void setTrace(@Nullable SpanContext spanContext, @NotNull IScope scope) { try { options .getExecutorService() - .submit( - () -> - nativeScope.setTrace( - spanContext.getTraceId().toString(), spanContext.getSpanId().toString())); + .submit(() -> + nativeScope.setTrace( + spanContext.getTraceId().toString(), spanContext.getSpanId().toString())); } catch (Throwable e) { options.getLogger().log(SentryLevel.ERROR, e, "Scope sync setTrace failed."); } diff --git a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java index fae652f7a64..e2339ca911d 100644 --- a/sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java +++ b/sentry-android-ndk/src/main/java/io/sentry/android/ndk/SentryNdk.java @@ -1,5 +1,6 @@ package io.sentry.android.ndk; +import android.content.Context; import io.sentry.android.core.NdkHandlerStrategy; import io.sentry.android.core.SentryAndroidOptions; import io.sentry.ndk.NativeModuleListLoader; @@ -41,6 +42,17 @@ private SentryNdk() {} * @param options the SentryAndroidOptions */ public static void init(@NotNull final SentryAndroidOptions options) { + init(null, options); + } + + /** + * Init the NDK integration + * + * @param context the Android context + * @param options the SentryAndroidOptions + */ + public static void init( + @Nullable final Context context, @NotNull final SentryAndroidOptions options) { SentryNdkUtil.addPackage(options.getSdkVersion()); try { if (loadLibraryLatch.await(2000, TimeUnit.MILLISECONDS)) { diff --git a/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkTest.kt b/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkTest.kt index d9b332ac185..afa3d7061c6 100644 --- a/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkTest.kt +++ b/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkTest.kt @@ -49,7 +49,7 @@ class SentryNdkTest { dsn = "https://key@sentry.io/proj" cacheDirPath = "/cache" tracesSampleRate = null - } + }, ) { assertNotNull(fixture.capturedOptions) assertEquals(0.0f, fixture.capturedOptions!!.tracesSampleRate, 0.0001f) @@ -64,7 +64,7 @@ class SentryNdkTest { dsn = "https://key@sentry.io/proj" cacheDirPath = "/cache" tracesSampleRate = 0.75 - } + }, ) { assertNotNull(fixture.capturedOptions) assertEquals(0.75f, fixture.capturedOptions!!.tracesSampleRate, 0.0001f) @@ -89,7 +89,7 @@ class SentryNdkTest { cacheDirPath = "/cache" isEnableNdkAppHangTracking = true ndkAppHangTimeoutIntervalMillis = 2000 - } + }, ) { assertNotNull(fixture.capturedOptions) assertTrue(fixture.capturedOptions!!.isEnableAppHangTracking) diff --git a/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkUtilTest.kt b/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkUtilTest.kt index a3f5e9a8f93..ee29d4a5118 100644 --- a/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkUtilTest.kt +++ b/sentry-android-ndk/src/test/java/io/sentry/android/ndk/SentryNdkUtilTest.kt @@ -12,9 +12,8 @@ class SentryNdkUtilTest { SentryNdkUtil.addPackage(options.sdkVersion) assertTrue( options.sdkVersion!!.packageSet.any { - it.name == "maven:io.sentry:sentry-android-ndk" - it.version == BuildConfig.VERSION_NAME - } + it.name == "maven:io.sentry:sentry-android-ndk" && it.version == BuildConfig.VERSION_NAME + }, ) } diff --git a/sentry-android-replay/api/sentry-android-replay.api b/sentry-android-replay/api/sentry-android-replay.api index 91c91778f05..1abe170ef99 100644 --- a/sentry-android-replay/api/sentry-android-replay.api +++ b/sentry-android-replay/api/sentry-android-replay.api @@ -79,10 +79,12 @@ public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConne public fun onTouchEvent (Landroid/view/MotionEvent;)V public fun onWindowSizeChanged (II)V public fun pause ()V + public fun pauseTouchTracking ()V public fun register (Lio/sentry/IScopes;Lio/sentry/SentryOptions;)V public fun registerSegmentName (Ljava/lang/String;)V public fun registerTraceId (Lio/sentry/protocol/SentryId;)V public fun resume ()V + public fun resumeTouchTracking ()V public fun setBreadcrumbConverter (Lio/sentry/ReplayBreadcrumbConverter;)V public fun start ()V public fun startBuffering ()V diff --git a/sentry-android-replay/build.gradle.kts b/sentry-android-replay/build.gradle.kts index 1b51f29cea3..912e85075a6 100644 --- a/sentry-android-replay/build.gradle.kts +++ b/sentry-android-replay/build.gradle.kts @@ -13,6 +13,7 @@ plugins { id("io.sentry.jdk-target") id("io.sentry.publish") id("io.sentry.api-validation") + id("io.sentry.robolectric") } android { @@ -62,6 +63,10 @@ android { // We run a full lint analysis as build part in CI, so skip vital checks for assemble tasks. checkReleaseBuilds = false + + // Lint 9.5 can't load the custom checks bundled with older androidx.lifecycle releases and + // reports that it skips them. They only cover lifecycle APIs this module doesn't call. + disable += "ObsoleteLintCustomCheck" } buildFeatures { buildConfig = true } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/DefaultReplayBreadcrumbConverter.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/DefaultReplayBreadcrumbConverter.kt index bf8a7667a27..2788b39084d 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/DefaultReplayBreadcrumbConverter.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/DefaultReplayBreadcrumbConverter.kt @@ -44,7 +44,7 @@ public open class DefaultReplayBreadcrumbConverter() : ReplayBreadcrumbConverter * user-provided callback to provide the actual breadcrumb to process. */ private inner class ReplayBeforeBreadcrumbCallback( - private val delegate: BeforeBreadcrumbCallback? + private val delegate: BeforeBreadcrumbCallback?, ) : BeforeBreadcrumbCallback { override fun execute(breadcrumb: Breadcrumb, hint: Hint): Breadcrumb? { val resultBreadcrumb = @@ -81,11 +81,11 @@ public open class DefaultReplayBreadcrumbConverter() : ReplayBreadcrumbConverter Collections.synchronizedMap( object : LinkedHashMap() { override fun removeEldestEntry( - eldest: MutableMap.MutableEntry? + eldest: MutableMap.MutableEntry?, ): Boolean { return size > MAX_HTTP_NETWORK_DETAILS } - } + }, ) override fun convert(breadcrumb: Breadcrumb): RRWebEvent? { diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 4d6614a7832..6bdca6f748f 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -114,7 +114,7 @@ public class ReplayIntegration( } private var lastKnownConnectionStatus: ConnectionStatus = ConnectionStatus.UNKNOWN - private var debugMaskingEnabled: Boolean = false + @Volatile private var debugMaskingEnabled: Boolean = false private lateinit var options: SentryOptions private var scopes: IScopes? = null private var recorder: Recorder? = null @@ -135,6 +135,11 @@ public class ReplayIntegration( internal val isEnabled = AtomicBoolean(false) internal var isManualPause = false + // Not reset by start()/stop(), only resumeTouchTracking() clears it, so touches cannot leak + // by accident. Set directly instead of enqueueOnMainThread like lifecycle commands: it does not + // touch ReplayState, so ordering does not matter, and a queued set could let already-pending + // touch events through. + @Volatile private var isTouchTrackingPaused = false public val replayCacheDir: File? get() = state.get().captureStrategy?.replayCacheDir @@ -262,7 +267,7 @@ public class ReplayIntegration( lifecycleState = STARTED, replayId = replayId ?: SentryId.EMPTY_ID, captureStrategy = strategy, - ) + ), ) registerRootViewListeners() @@ -365,7 +370,7 @@ public class ReplayIntegration( current.copy( replayId = replayId ?: SentryId.EMPTY_ID, captureStrategy = activeStrategy, - ) + ), ) } @@ -397,6 +402,14 @@ public class ReplayIntegration( } } + override fun pauseTouchTracking() { + isTouchTrackingPaused = true + } + + override fun resumeTouchTracking() { + isTouchTrackingPaused = false + } + override fun enableDebugMaskingOverlay() { debugMaskingEnabled = true } @@ -457,7 +470,7 @@ public class ReplayIntegration( lifecycleState = STOPPED, replayId = SentryId.EMPTY_ID, captureStrategy = null, - ) + ), ) } @@ -606,7 +619,7 @@ public class ReplayIntegration( override fun onTouchEvent(event: MotionEvent) { val current = state.get() - if (!isEnabled.get() || !current.isTouchRecordingAllowed) { + if (!isEnabled.get() || isTouchTrackingPaused || !current.isTouchRecordingAllowed) { return } current.captureStrategy?.onTouchEvent(event) @@ -715,7 +728,7 @@ public class ReplayIntegration( segment.capture(scopes, hint) } cleanupReplays( - unfinishedReplayId = previousReplayIdString + unfinishedReplayId = previousReplayIdString, ) // will be cleaned up after the envelope is assembled } } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/WindowRecorder.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/WindowRecorder.kt index 19c61900889..8ee0041f8b1 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/WindowRecorder.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/WindowRecorder.kt @@ -205,7 +205,7 @@ internal class WindowRecorder( } return true } - } + }, ) } } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BaseCaptureStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BaseCaptureStrategy.kt index b6b8981f8ce..6b55cab0bb1 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BaseCaptureStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BaseCaptureStrategy.kt @@ -165,7 +165,7 @@ constructor( replayDeadline = null segmentTimestamp = null currentReplayId = SentryId.EMPTY_ID - } + }, ) } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BufferCaptureStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BufferCaptureStrategy.kt index 071acc19cae..988a62e6411 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BufferCaptureStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BufferCaptureStrategy.kt @@ -86,7 +86,7 @@ constructor( ReplayRunnable("$TAG.stop") { ReplayCache.deleteExceptSegmentVideos(replayCacheDir) currentSegment = -1 - } + }, ) super.stop() } @@ -144,7 +144,7 @@ constructor( val bufferLimit = now - options.sessionReplay.errorReplayDuration screenAtStart = cache?.rotate(bufferLimit) bufferedSegments.rotate(bufferLimit) - } + }, ) } @@ -283,7 +283,7 @@ constructor( currentConfig.bitRate, ) onSegmentCreated(segment) - } + }, ) } } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt index 8e6ae9fc4a4..58bbf887084 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt @@ -167,7 +167,7 @@ constructor( options.replayController.stop() options.logger.log(INFO, "Session replay deadline exceeded (1h), stopping recording") } - } + }, ) } @@ -217,7 +217,7 @@ constructor( currentConfig.bitRate, ) onSegmentCreated(segment) - } + }, ) } } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/ReplayGestureConverter.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/ReplayGestureConverter.kt index c348178e9d2..55d90e0d622 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/ReplayGestureConverter.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/ReplayGestureConverter.kt @@ -9,6 +9,7 @@ import io.sentry.rrweb.RRWebInteractionMoveEvent import io.sentry.rrweb.RRWebInteractionMoveEvent.Position import io.sentry.time.Deadline import io.sentry.time.MonotonicTicker +import io.sentry.time.Stopwatch import io.sentry.transport.ICurrentDateProvider import java.util.concurrent.TimeUnit.MILLISECONDS @@ -24,7 +25,9 @@ internal class ReplayGestureConverter( } private val currentPositions = LinkedHashMap>(10) - private var touchMoveBaseline = 0L + + /** Started with the first position in [currentPositions], or `null` while none is batched. */ + private var moveBatch: Stopwatch? = null /** When the next move event may be captured, or `null` before the first one. */ private var moveDebounce: Deadline? = null @@ -42,6 +45,9 @@ internal class ReplayGestureConverter( } moveDebounce = Deadline.after(ticker, TOUCH_MOVE_DEBOUNCE_THRESHOLD, MILLISECONDS) + // read once, so all pointers of this event share one offset + val totalOffset = moveBatch?.elapsed(MILLISECONDS) ?: 0L + currentPositions.keys.forEach { pId -> val pIndex = event.findPointerIndex(pId) @@ -51,8 +57,8 @@ internal class ReplayGestureConverter( } // idk why but rrweb does it like dis - if (touchMoveBaseline == 0L) { - touchMoveBaseline = now + if (moveBatch == null) { + moveBatch = Stopwatch.started(ticker) } currentPositions[pId]!! += @@ -60,12 +66,12 @@ internal class ReplayGestureConverter( x = event.getX(pIndex) * recorderConfig.scaleFactorX y = event.getY(pIndex) * recorderConfig.scaleFactorY id = 0 // html node id, but we don't have it, so hardcode to 0 to align with FE - timeOffset = now - touchMoveBaseline + timeOffset = totalOffset } } - val totalOffset = now - touchMoveBaseline - return if (totalOffset > CAPTURE_MOVE_EVENT_THRESHOLD) { + // with nothing batched there is nothing to wait for + return if (moveBatch == null || totalOffset > CAPTURE_MOVE_EVENT_THRESHOLD) { val moveEvents = ArrayList(currentPositions.size) for ((pointerId, positions) in currentPositions) { if (positions.isNotEmpty()) { @@ -81,7 +87,7 @@ internal class ReplayGestureConverter( currentPositions[pointerId]!!.clear() } } - touchMoveBaseline = 0L + moveBatch = null moveEvents } else { null @@ -108,7 +114,7 @@ internal class ReplayGestureConverter( id = 0 // html node id, but we don't have it, so hardcode to 0 to align with FE pointerId = pId interactionType = InteractionType.TouchStart - } + }, ) } MotionEvent.ACTION_UP, @@ -131,7 +137,7 @@ internal class ReplayGestureConverter( id = 0 // html node id, but we don't have it, so hardcode to 0 to align with FE pointerId = pId interactionType = InteractionType.TouchEnd - } + }, ) } MotionEvent.ACTION_CANCEL -> { @@ -145,7 +151,7 @@ internal class ReplayGestureConverter( id = 0 // html node id, but we don't have it, so hardcode to 0 to align with FE pointerId = 0 // the pointerId is not used for TouchCancel, so just set it to 0 interactionType = InteractionType.TouchCancel - } + }, ) } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt index f40d8c8cc5f..dfb8ec0f268 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/CanvasStrategy.kt @@ -186,7 +186,7 @@ internal class CanvasStrategy( if (!pixelCopyInFlight) { releaseResources() } - } + }, ) unprocessedPictureRef.getAndSet(null) } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/PixelCopyStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/PixelCopyStrategy.kt index 4672e7dbfbc..72c355a5a70 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/PixelCopyStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/screenshot/PixelCopyStrategy.kt @@ -150,7 +150,7 @@ internal class PixelCopyStrategy( } finally { finishFrame() } - } + }, ) if (submitted == null) { finishFrame() @@ -343,7 +343,7 @@ internal class PixelCopyStrategy( } finally { finishFrame() } - } + }, ) if (submitted == null) { recycleCaptures(captures) @@ -385,7 +385,7 @@ internal class PixelCopyStrategy( } finally { finishFrame() } - } + }, ) if (submitted == null) { finishFrame() diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/AnrWithReplayIntegrationTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/AnrWithReplayIntegrationTest.kt index 3df08b2af24..9a48f226819 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/AnrWithReplayIntegrationTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/AnrWithReplayIntegrationTest.kt @@ -110,7 +110,7 @@ class AnrWithReplayIntegrationTest { (no managed stack frames) """ .trimIndent() - .byteInputStream() + .byteInputStream(), ) } shadowActivityManager.addApplicationExitInfo(exitInfo) @@ -180,7 +180,7 @@ class AnrWithReplayIntegrationTest { asserted.set(true) return event } - } + }, ) // have to do it after the cacheDir is set to options, because it adds a dsn hash after @@ -200,7 +200,7 @@ class AnrWithReplayIntegrationTest { $SEGMENT_KEY_TIMESTAMP=2024-07-11T10:25:21.454Z $SEGMENT_KEY_REPLAY_TYPE=BUFFER """ - .trimIndent() + .trimIndent(), ) } @@ -216,7 +216,7 @@ class AnrWithReplayIntegrationTest { await .withAlias( - "Failed because of BeforeSend callback above, but we swallow BeforeSend exceptions, hence the timeout" + "Failed because of BeforeSend callback above, but we swallow BeforeSend exceptions, hence the timeout", ) .untilTrue(asserted) } diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/DefaultReplayBreadcrumbConverterTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/DefaultReplayBreadcrumbConverterTest.kt index 9d9d5b72823..a6759419b29 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/DefaultReplayBreadcrumbConverterTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/DefaultReplayBreadcrumbConverterTest.kt @@ -426,7 +426,7 @@ class DefaultReplayBreadcrumbConverterTest { 100L, NetworkBody("request body content"), mapOf("Content-Type" to "application/json"), - ) + ), ) fakeOkHttpNetworkDetails.setResponseDetails( ReplayNetworkRequestOrResponse( @@ -434,7 +434,7 @@ class DefaultReplayBreadcrumbConverterTest { 500L, NetworkBody(mapOf("status" to "success", "message" to "OK")), mapOf("Content-Type" to "text/plain"), - ) + ), ) val hintWithFakeOKHttpNetworkDetails = Hint() hintWithFakeOKHttpNetworkDetails.set(SENTRY_REPLAY_NETWORK_DETAILS, fakeOkHttpNetworkDetails) @@ -488,7 +488,7 @@ class DefaultReplayBreadcrumbConverterTest { 150L, NetworkBody(listOf("item1", "item2", "item3")), mapOf("Content-Type" to "application/json"), - ) + ), ) fakeOkHttpNetworkDetails.setResponseDetails( ReplayNetworkRequestOrResponse( @@ -496,7 +496,7 @@ class DefaultReplayBreadcrumbConverterTest { 550L, NetworkBody(mapOf("status" to "success", "message" to "OK")), mapOf("Content-Type" to "text/plain"), - ) + ), ) val hintWithFakeOKHttpNetworkDetails = Hint() hintWithFakeOKHttpNetworkDetails.set(SENTRY_REPLAY_NETWORK_DETAILS, fakeOkHttpNetworkDetails) @@ -543,7 +543,7 @@ class DefaultReplayBreadcrumbConverterTest { } val networkRequestData = NetworkRequestData("GET") networkRequestData.setResponseDetails( - ReplayNetworkRequestOrResponse(200, null, null, mapOf("Content-Type" to "application/json")) + ReplayNetworkRequestOrResponse(200, null, null, mapOf("Content-Type" to "application/json")), ) // Simulates Scopes.addBreadcrumb, which hands the network details to the converter options.beforeBreadcrumb?.execute( @@ -558,7 +558,7 @@ class DefaultReplayBreadcrumbConverterTest { 21L, NetworkBody("response body content"), mapOf("Content-Type" to "application/json"), - ) + ), ) check(rrwebEvent is RRWebSpanEvent) @@ -584,7 +584,7 @@ class DefaultReplayBreadcrumbConverterTest { 100L, NetworkBody("request body content"), mapOf("Content-Type" to "application/json"), - ) + ), ) networkRequestData.setResponseDetails( ReplayNetworkRequestOrResponse( @@ -592,7 +592,7 @@ class DefaultReplayBreadcrumbConverterTest { 100L, NetworkBody("response body content"), mapOf("Content-Type" to "application/json"), - ) + ), ) hint.set(SENTRY_REPLAY_NETWORK_DETAILS, networkRequestData) diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/PreviousReplayIntegrationTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/PreviousReplayIntegrationTest.kt index 5999ac9826b..dc42b30e04a 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/PreviousReplayIntegrationTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/PreviousReplayIntegrationTest.kt @@ -73,7 +73,7 @@ class PreviousReplayIntegrationTest { capturedReplay.set(event) return event } - } + }, ) // have to do it after the cacheDir is set to options, because it adds a dsn hash after @@ -96,7 +96,7 @@ class PreviousReplayIntegrationTest { $SEGMENT_KEY_TIMESTAMP=2024-07-11T10:25:21.454Z $SEGMENT_KEY_REPLAY_TYPE=BUFFER """ - .trimIndent() + .trimIndent(), ) File(replayFolder, "1720693523997.jpg").outputStream().use { os -> Bitmap.createBitmap(1, 1, ARGB_8888).compress(JPEG, 80, os) diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayCacheTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayCacheTest.kt index aeca0c868d1..5a447904829 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayCacheTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayCacheTest.kt @@ -49,7 +49,7 @@ import org.robolectric.shadows.ShadowBitmapFactory import org.robolectric.shadows.ShadowCloseGuard @RunWith(AndroidJUnit4::class) -@Config(sdk = [26], shadows = [ReplayShadowMediaCodec::class]) +@Config(sdk = [30], shadows = [ReplayShadowMediaCodec::class]) class ReplayCacheTest { @get:Rule val tmpDir = TemporaryFolder() @@ -271,7 +271,7 @@ class ReplayCacheTest { assertTrue( replayCache.replayCacheDir!!.listFiles()!!.none { it.name == "1.jpg" || it.name == "1001.jpg" - } + }, ) } @@ -367,7 +367,7 @@ class ReplayCacheTest { $SEGMENT_KEY_ID=0 $SEGMENT_KEY_TIMESTAMP=2024-07-11T10:25:21.454Z """ - .trimIndent() + .trimIndent(), ) // omitting replay type, which is required, for the test } @@ -396,7 +396,7 @@ class ReplayCacheTest { $SEGMENT_KEY_REPLAY_TYPE=SESSION $SEGMENT_KEY_REPLAY_RECORDING={}[{"type":3,"timestamp":1720693523997,"data":{"source":2,"type":7,"id":0,"x":314.2979431152344,"y":625.44140625,"pointerType":2,"pointerId":0}},{"type":3,"timestamp":1720693524774,"data":{"source":2,"type":9,"id":0,"x":322.00390625,"y":424.4384765625,"pointerType":2,"pointerId":0}}] """ - .trimIndent() + .trimIndent(), ) } @@ -449,7 +449,7 @@ class ReplayCacheTest { $SEGMENT_KEY_TIMESTAMP=2024-07-11T10:25:21.454Z $SEGMENT_KEY_REPLAY_TYPE=SESSION """ - .trimIndent() + .trimIndent(), ) } @@ -506,7 +506,7 @@ class ReplayCacheTest { $SEGMENT_KEY_TIMESTAMP=2024-07-11T10:25:21.454Z $SEGMENT_KEY_REPLAY_TYPE=BUFFER """ - .trimIndent() + .trimIndent(), ) } @@ -543,7 +543,7 @@ class ReplayCacheTest { $SEGMENT_KEY_SDK_NAME=sentry.java.android $SEGMENT_KEY_SDK_VERSION=8.0.0 """ - .trimIndent() + .trimIndent(), ) } File(replayCacheFolder, "1720693523997.jpg").outputStream().use { @@ -578,7 +578,7 @@ class ReplayCacheTest { $SEGMENT_KEY_TIMESTAMP=2024-07-11T10:25:21.454Z $SEGMENT_KEY_REPLAY_TYPE=BUFFER """ - .trimIndent() + .trimIndent(), ) } File(replayCacheFolder, "1720693523997.jpg").outputStream().use { @@ -609,7 +609,7 @@ class ReplayCacheTest { $SEGMENT_KEY_REPLAY_TYPE=BUFFER $SEGMENT_KEY_FLUSHED=true """ - .trimIndent() + .trimIndent(), ) } diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt index 70e8426d124..d66584f1085 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt @@ -90,7 +90,7 @@ import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) -@Config(sdk = [26], shadows = [ReplayShadowMediaCodec::class]) +@Config(sdk = [30], shadows = [ReplayShadowMediaCodec::class]) class ReplayIntegrationTest { @get:Rule val tmpDir = TemporaryFolder() @@ -102,7 +102,7 @@ class ReplayIntegrationTest { on { isMainThread }.thenAnswer { Looper.myLooper() == Looper.getMainLooper() } } setReplayController( - mock { on { breadcrumbConverter }.thenReturn(DefaultReplayBreadcrumbConverter()) } + mock { on { breadcrumbConverter }.thenReturn(DefaultReplayBreadcrumbConverter()) }, ) executorService = mock { doAnswer { (it.arguments[0] as Runnable).run() }.whenever(mock).submit(any()) @@ -1082,7 +1082,7 @@ class ReplayIntegrationTest { $SEGMENT_KEY_REPLAY_TYPE=SESSION $SEGMENT_KEY_REPLAY_RECORDING={}[{"type":3,"timestamp":1720693523997,"data":{"source":2,"type":7,"id":0,"x":314.2979431152344,"y":625.44140625,"pointerType":2,"pointerId":0}},{"type":3,"timestamp":1720693524774,"data":{"source":2,"type":9,"id":0,"x":322.00390625,"y":424.4384765625,"pointerType":2,"pointerId":0}}] """ - .trimIndent() + .trimIndent(), ) } @@ -1598,6 +1598,93 @@ class ReplayIntegrationTest { verify(captureStrategy, never()).onTouchEvent(any()) } + @Test + fun `pauseTouchTracking drops touches but keeps recording screenshots`() { + val captureStrategy = mock() + val recorder = mock() + val replay = + fixture.getSut( + context, + recorderProvider = { recorder }, + replayCaptureStrategyProvider = { captureStrategy }, + ) + + replay.register(fixture.scopes, fixture.options) + replay.start() + replay.pauseTouchTracking() + replay.onTouchEvent(mock()) + + verify(captureStrategy, never()).onTouchEvent(any()) + verify(recorder, never()).pause() + verify(captureStrategy, never()).pause() + assertTrue(replay.isRecording) + + replay.resumeTouchTracking() + replay.onTouchEvent(mock()) + + verify(captureStrategy).onTouchEvent(any()) + } + + @Test + fun `resume does not resume paused touch tracking`() { + val captureStrategy = mock() + val replay = fixture.getSut(context, replayCaptureStrategyProvider = { captureStrategy }) + + replay.register(fixture.scopes, fixture.options) + replay.start() + replay.pauseTouchTracking() + replay.pause() + replay.resume() + replay.onTouchEvent(mock()) + + verify(captureStrategy, never()).onTouchEvent(any()) + } + + @Test + fun `resumeTouchTracking does not record touches while replay is paused`() { + val captureStrategy = mock() + val replay = fixture.getSut(context, replayCaptureStrategyProvider = { captureStrategy }) + + replay.register(fixture.scopes, fixture.options) + replay.start() + replay.pauseTouchTracking() + replay.pause() + replay.resumeTouchTracking() + replay.onTouchEvent(mock()) + + verify(captureStrategy, never()).onTouchEvent(any()) + + replay.resume() + replay.onTouchEvent(mock()) + + verify(captureStrategy).onTouchEvent(any()) + } + + @Test + fun `paused touch tracking stays paused for new replays`() { + val firstStrategy = mock() + val secondStrategy = mock() + val thirdStrategy = mock() + val strategies = ArrayDeque(listOf(firstStrategy, secondStrategy, thirdStrategy)) + val replay = + fixture.getSut(context, replayCaptureStrategyProvider = { strategies.removeFirst() }) + + replay.register(fixture.scopes, fixture.options) + // called before any replay is started + replay.pauseTouchTracking() + replay.onAppForegrounded(true) + replay.onTouchEvent(mock()) + replay.onAppForegrounded(true) + replay.onTouchEvent(mock()) + replay.stop() + replay.start() + replay.onTouchEvent(mock()) + + verify(firstStrategy, never()).onTouchEvent(any()) + verify(secondStrategy, never()).onTouchEvent(any()) + verify(thirdStrategy, never()).onTouchEvent(any()) + } + @Test fun `when paused manually onConnectionStatusChanged does not resume`() { val captureStrategy = getSessionCaptureStrategy(fixture.options) diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationWithRecorderTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationWithRecorderTest.kt index 44f1551ede2..873dec18f66 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationWithRecorderTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationWithRecorderTest.kt @@ -40,7 +40,7 @@ import org.mockito.kotlin.whenever import org.robolectric.annotation.Config @RunWith(AndroidJUnit4::class) -@Config(sdk = [26], shadows = [ReplayShadowMediaCodec::class]) +@Config(sdk = [30], shadows = [ReplayShadowMediaCodec::class]) class ReplayIntegrationWithRecorderTest { @get:Rule val tmpDir = TemporaryFolder() diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplaySmokeTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplaySmokeTest.kt index d35ef4e8e0f..c7a368b06cb 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplaySmokeTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplaySmokeTest.kt @@ -85,7 +85,7 @@ class ReplaySmokeTest { Callback { it.callback?.run() true - } + }, ) private val recordingThread = Executors.newSingleThreadScheduledExecutor() diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/BufferCaptureStrategyTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/BufferCaptureStrategyTest.kt index f3830bc1ed5..a926eb00358 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/BufferCaptureStrategyTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/BufferCaptureStrategyTest.kt @@ -59,7 +59,7 @@ class BufferCaptureStrategyTest { val options = SentryOptions().apply { setReplayController( - mock { on { breadcrumbConverter }.thenReturn(DefaultReplayBreadcrumbConverter()) } + mock { on { breadcrumbConverter }.thenReturn(DefaultReplayBreadcrumbConverter()) }, ) } val scope = Scope(options) @@ -329,7 +329,7 @@ class BufferCaptureStrategyTest { anyInt(), anyInt(), any(), - ) + ), ) .thenAnswer { invocation -> capturedFrom = invocation.arguments[1] as Long @@ -363,7 +363,7 @@ class BufferCaptureStrategyTest { anyInt(), anyInt(), any(), - ) + ), ) .thenAnswer { invocation -> capturedFrom = invocation.arguments[1] as Long diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/SessionCaptureStrategyTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/SessionCaptureStrategyTest.kt index 4c31090cee9..68f7bb0cb0f 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/SessionCaptureStrategyTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/SessionCaptureStrategyTest.kt @@ -77,7 +77,7 @@ class SessionCaptureStrategyTest { val options = SentryOptions().apply { setReplayController( - mock { on { breadcrumbConverter }.thenReturn(DefaultReplayBreadcrumbConverter()) } + mock { on { breadcrumbConverter }.thenReturn(DefaultReplayBreadcrumbConverter()) }, ) } val scope = Scope(options) diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/gestures/GestureRecorderTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/gestures/GestureRecorderTest.kt index 6f5a02b54c7..fe72df2562d 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/gestures/GestureRecorderTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/gestures/GestureRecorderTest.kt @@ -28,7 +28,7 @@ class GestureRecorderTest { val options = SentryOptions() fun getSut( - touchRecorderCallback: TouchRecorderCallback = NoOpTouchRecorderCallback() + touchRecorderCallback: TouchRecorderCallback = NoOpTouchRecorderCallback(), ): GestureRecorder = GestureRecorder(options, touchRecorderCallback) } @@ -65,7 +65,7 @@ class GestureRecorderTest { override fun onTouchEvent(event: MotionEvent) { called = true } - } + }, ) gestureRecorder.onRootViewsChanged(activity.root, true) @@ -92,7 +92,7 @@ class GestureRecorderTest { assertEquals(MotionEvent.ACTION_DOWN, event.action) called = true } - } + }, ) gestureRecorder.onRootViewsChanged(activity.root, true) diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/gestures/ReplayGestureConverterTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/gestures/ReplayGestureConverterTest.kt index a396a62f93a..b06f85253d2 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/gestures/ReplayGestureConverterTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/gestures/ReplayGestureConverterTest.kt @@ -2,6 +2,7 @@ package io.sentry.android.replay.gestures import android.view.MotionEvent import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat import io.sentry.android.replay.ScreenshotRecorderConfig import io.sentry.rrweb.RRWebInteractionEvent import io.sentry.rrweb.RRWebInteractionMoveEvent @@ -30,7 +31,7 @@ class ReplayGestureConverterTest { } fun getSut( - dateProvider: ICurrentDateProvider = ICurrentDateProvider { now } + dateProvider: ICurrentDateProvider = ICurrentDateProvider { now }, ): ReplayGestureConverter = ReplayGestureConverter(dateProvider, ticker) } @@ -141,6 +142,55 @@ class ReplayGestureConverterTest { moveEvent.recycle() } + @Test + fun `wall clock stepping backwards during a swipe does not hold back the batch`() { + val sut = fixture.getSut() + val recorderConfig = ScreenshotRecorderConfig(scaleFactorX = 1f, scaleFactorY = 1f) + val downEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 100f, 200f, 0) + val moveEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 110f, 210f, 0) + sut.convert(downEvent, recorderConfig) + assertThat(sut.convert(moveEvent, recorderConfig)).isNull() + + // an NTP correction drags the wall clock back mid-swipe + fixture.now -= 1_000 + fixture.advance(300) + assertThat(sut.convert(moveEvent, recorderConfig)).isNull() + + fixture.advance(300) + val result = sut.convert(moveEvent, recorderConfig) + + assertThat(result).hasSize(1) + val batch = result!!.single() as RRWebInteractionMoveEvent + assertThat(batch.positions!!.map { it.timeOffset }).containsExactly(-600L, -300L, 0L).inOrder() + + downEvent.recycle() + moveEvent.recycle() + } + + @Test + fun `wall clock stepping forwards during a swipe does not send the batch early`() { + val sut = fixture.getSut() + val recorderConfig = ScreenshotRecorderConfig(scaleFactorX = 1f, scaleFactorY = 1f) + val downEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 100f, 200f, 0) + val moveEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 110f, 210f, 0) + sut.convert(downEvent, recorderConfig) + assertThat(sut.convert(moveEvent, recorderConfig)).isNull() + + fixture.now += 60_000 + fixture.advance(300) + assertThat(sut.convert(moveEvent, recorderConfig)).isNull() + + fixture.advance(300) + val result = sut.convert(moveEvent, recorderConfig) + + assertThat(result).hasSize(1) + val batch = result!!.single() as RRWebInteractionMoveEvent + assertThat(batch.positions!!.map { it.timeOffset }).containsExactly(-600L, -300L, 0L).inOrder() + + downEvent.recycle() + moveEvent.recycle() + } + @Test fun `convert ACTION_UP event`() { val sut = fixture.getSut() diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/screenshot/PixelCopyStrategyTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/screenshot/PixelCopyStrategyTest.kt index 587927e9793..1bf2fa89a10 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/screenshot/PixelCopyStrategyTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/screenshot/PixelCopyStrategyTest.kt @@ -664,7 +664,7 @@ private class ActivityWithSurfaceView : Activity() { TextView(this).apply { text = "Overlay" layoutParams = FrameLayout.LayoutParams(200, 50) - } + }, ) root.addView(SurfaceView(this).apply { layoutParams = FrameLayout.LayoutParams(200, 200) }) setContentView(root) 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 0accb9ed16d..607b81d888d 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 @@ -221,7 +221,7 @@ class ComposeMaskingOptionsTest { @Test @Ignore( - "Flaky: Robolectric intermittently reports zero bounds for nodes, causing isVisible=false and making the assertion non-deterministic" + "Flaky: Robolectric intermittently reports zero bounds for nodes, causing isVisible=false and making the assertion non-deterministic", ) fun `when sentry-unmask modifier is set unmasks the node`() { ComposeMaskingOptionsActivity.textModifierApplier = { Modifier.sentryReplayUnmask() } diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/viewhierarchy/ContainerMaskingOptionsTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/viewhierarchy/ContainerMaskingOptionsTest.kt index 5d5304555ce..d23a64926d1 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/viewhierarchy/ContainerMaskingOptionsTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/viewhierarchy/ContainerMaskingOptionsTest.kt @@ -217,9 +217,9 @@ class ContainerMaskingOptionsTest { textViewInUnmask = this text = "Hello, World!" layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) - } + }, ) - } + }, ) linearLayout.addView( @@ -231,9 +231,9 @@ class ContainerMaskingOptionsTest { val image = this::class.java.classLoader.getResource("Tongariro.jpg")!! setImageDrawable(Drawable.createFromPath(image.path)) layoutParams = LayoutParams(50, 50).apply { setMargins(0, 16, 0, 0) } - } + }, ) - } + }, ) linearLayout.addView( @@ -243,23 +243,23 @@ class ContainerMaskingOptionsTest { CustomGroup(context).apply { customViewInUnmask = this this.addView(CustomView(context).apply { secondLayerChildInUnmask = this }) - } + }, ) - } + }, ) linearLayout.addView( CustomMask(context).apply { maskWithChildren = this this.addView(CustomGroup(context).apply { this.addView(CustomView(context)) }) - } + }, ) linearLayout.addView( CustomUnmask(context).apply { unmaskWithMaskChild = this this.addView(CustomMask(context).apply { maskAsDirectChildOfUnmask = this }) - } + }, ) setContentView(linearLayout) diff --git a/sentry-android-timber/src/main/java/io/sentry/android/timber/SentryTimberIntegration.kt b/sentry-android-timber/src/main/java/io/sentry/android/timber/SentryTimberIntegration.kt index f9ef0c308ef..acdde6bbf71 100644 --- a/sentry-android-timber/src/main/java/io/sentry/android/timber/SentryTimberIntegration.kt +++ b/sentry-android-timber/src/main/java/io/sentry/android/timber/SentryTimberIntegration.kt @@ -34,7 +34,7 @@ private constructor( ) public constructor( - logsEnabled: Boolean + logsEnabled: Boolean, ) : this( SentryLevel.ERROR, SentryLevel.INFO, @@ -43,7 +43,7 @@ private constructor( ) internal constructor( - logsEnabledProvider: Evaluator + logsEnabledProvider: Evaluator, ) : this( SentryLevel.ERROR, SentryLevel.INFO, diff --git a/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberIntegrationTest.kt b/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberIntegrationTest.kt index e569b7a2936..a224f2f8b86 100644 --- a/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberIntegrationTest.kt +++ b/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberIntegrationTest.kt @@ -155,7 +155,7 @@ class SentryTimberIntegrationTest { assertTrue( fixture.options.sdkVersion!!.packageSet.any { it.name == "maven:io.sentry:sentry-android-timber" && it.version == BuildConfig.VERSION_NAME - } + }, ) } @@ -192,7 +192,7 @@ class SentryTimberIntegrationTest { SentryLevel.ERROR, SentryLevel.INFO, SentryLogLevel.INFO, - ) + ), ) try { diff --git a/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberTreeTest.kt b/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberTreeTest.kt index ff90a420701..fbdc815cdd1 100644 --- a/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberTreeTest.kt +++ b/sentry-android-timber/src/test/java/io/sentry/android/timber/SentryTimberTreeTest.kt @@ -192,7 +192,7 @@ class SentryTimberTreeTest { check { assertEquals("tag", it.getTag("TimberTag")) assertEquals(sentryLevel, it.level) - } + }, ) } } @@ -211,7 +211,7 @@ class SentryTimberTreeTest { sut.e("message") verify(fixture.scopes) .captureEvent( - check { assertNotNull(it.message) { message -> assertEquals("message", message.message) } } + check { assertNotNull(it.message) { message -> assertEquals("message", message.message) } }, ) } @@ -227,7 +227,7 @@ class SentryTimberTreeTest { assertEquals("test count: 32", message.formatted) assertEquals("32", message.params!!.first()) } - } + }, ) } @@ -271,7 +271,7 @@ class SentryTimberTreeTest { assertEquals("Timber", it.category) assertEquals(SentryLevel.INFO, it.level) assertEquals("message", it.message) - } + }, ) } @@ -285,7 +285,7 @@ class SentryTimberTreeTest { assertEquals("exception", it.category) assertEquals(SentryLevel.ERROR, it.level) assertEquals("test", it.message) - } + }, ) } diff --git a/sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApolloBuilderExtensions.kt b/sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApolloBuilderExtensions.kt index 076cfea521d..79f7059124b 100644 --- a/sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApolloBuilderExtensions.kt +++ b/sentry-apollo-3/src/main/java/io/sentry/apollo3/SentryApolloBuilderExtensions.kt @@ -20,7 +20,7 @@ fun ApolloClient.Builder.sentryTracing( captureFailedRequests = captureFailedRequests, failedRequestTargets = failedRequestTargets, beforeSpan = beforeSpan, - ) + ), ) return this } diff --git a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorClientErrors.kt b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorClientErrors.kt index 315f15a97b3..a450acbb96e 100644 --- a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorClientErrors.kt +++ b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorClientErrors.kt @@ -88,7 +88,7 @@ class SentryApollo3InterceptorClientErrors { sdkVersion = SdkVersion("test", "1.2.3") isSendDefaultPii = sendDefaultPii configureOptions() - } + }, ) } whenever(scopes.captureEvent(any(), any())).thenReturn(SentryId.EMPTY_ID) @@ -151,7 +151,7 @@ class SentryApollo3InterceptorClientErrors { fixture.getSut(captureFailedRequests = false) assertFalse( - SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo3ClientError") + SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo3ClientError"), ) } @@ -160,7 +160,7 @@ class SentryApollo3InterceptorClientErrors { fixture.getSut() assertTrue( - SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo3ClientError") + SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo3ClientError"), ) } diff --git a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt index c26a41a4af1..7b9454f394a 100644 --- a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt +++ b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorTest.kt @@ -114,7 +114,7 @@ class SentryApollo3InterceptorTest { MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) if (beforeSpan != null) { @@ -294,8 +294,8 @@ class SentryApollo3InterceptorTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=op")) @@ -386,8 +386,8 @@ class SentryApollo3InterceptorTest { beforeSpan = { span, request, response -> span.description = "overwritten description" span - } - ) + }, + ), ) verify(fixture.scopes) @@ -432,7 +432,7 @@ class SentryApollo3InterceptorTest { beforeSpan = { span, _, _ -> span.spanContext.sampled = false error("callback failed") - } + }, ) assertThat(sut.query(LaunchDetailsQuery("83")).execute().data).isNotNull() @@ -459,7 +459,7 @@ class SentryApollo3InterceptorTest { beforeSpan = { span, _, _ -> span.description = "partially modified" throw failure - } + }, ) val response = sut.query(LaunchDetailsQuery("83")).execute() diff --git a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorWithVariablesTest.kt b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorWithVariablesTest.kt index a77c3b6ecd4..297be0093dc 100644 --- a/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorWithVariablesTest.kt +++ b/sentry-apollo-3/src/test/java/io/sentry/apollo3/SentryApollo3InterceptorWithVariablesTest.kt @@ -63,7 +63,7 @@ class SentryApollo3InterceptorWithVariablesTest { MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) return ApolloClient.Builder() diff --git a/sentry-apollo-3/src/test/java/io/sentry/apollo3/selections/LaunchDetailsQuerySelections.kt b/sentry-apollo-3/src/test/java/io/sentry/apollo3/selections/LaunchDetailsQuerySelections.kt index 19d38491023..4f166f19871 100644 --- a/sentry-apollo-3/src/test/java/io/sentry/apollo3/selections/LaunchDetailsQuerySelections.kt +++ b/sentry-apollo-3/src/test/java/io/sentry/apollo3/selections/LaunchDetailsQuerySelections.kt @@ -46,6 +46,6 @@ public object LaunchDetailsQuerySelections { CompiledField.Builder(name = "launch", type = Launch.type) .arguments(listOf(CompiledArgument("id", CompiledVariable("id")))) .selections(launch) - .build() + .build(), ) } diff --git a/sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApolloBuilderExtensions.kt b/sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApolloBuilderExtensions.kt index 51383d33ed7..da8cd7f5c1e 100644 --- a/sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApolloBuilderExtensions.kt +++ b/sentry-apollo-4/src/main/java/io/sentry/apollo4/SentryApolloBuilderExtensions.kt @@ -20,7 +20,7 @@ fun ApolloClient.Builder.sentryTracing( captureFailedRequests = captureFailedRequests, failedRequestTargets = failedRequestTargets, beforeSpan = beforeSpan, - ) + ), ) return this } diff --git a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4BuilderExtensionsClientErrorsTest.kt b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4BuilderExtensionsClientErrorsTest.kt index 4c13e35a83e..dfdf728708d 100644 --- a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4BuilderExtensionsClientErrorsTest.kt +++ b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4BuilderExtensionsClientErrorsTest.kt @@ -47,7 +47,7 @@ class SentryApollo4BuilderExtensionsClientErrorsTestWithV3Implementation : abstract class SentryApollo4BuilderExtensionsClientErrorsTest( private val executeQueryImplementation: - KSuspendFunction1, ApolloResponse> + KSuspendFunction1, ApolloResponse>, ) { class Fixture { val server = MockWebServer() @@ -102,7 +102,7 @@ abstract class SentryApollo4BuilderExtensionsClientErrorsTest( sdkVersion = SdkVersion("test", "1.2.3") isSendDefaultPii = sendDefaultPii configureOptions() - } + }, ) } whenever(scopes.captureEvent(any(), any())).thenReturn(SentryId.EMPTY_ID) @@ -165,7 +165,7 @@ abstract class SentryApollo4BuilderExtensionsClientErrorsTest( fixture.getSut(captureFailedRequests = false) assertFalse( - SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo4ClientError") + SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo4ClientError"), ) } @@ -174,7 +174,7 @@ abstract class SentryApollo4BuilderExtensionsClientErrorsTest( fixture.getSut() assertTrue( - SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo4ClientError") + SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo4ClientError"), ) } diff --git a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4BuilderExtensionsTest.kt b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4BuilderExtensionsTest.kt index 654ff307eba..6b28d145b25 100644 --- a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4BuilderExtensionsTest.kt +++ b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4BuilderExtensionsTest.kt @@ -44,7 +44,7 @@ class SentryApollo4BuilderExtensionsTestWithV3Implementation : abstract class SentryApollo4BuilderExtensionsTest( private val executeQueryImplementation: - KSuspendFunction1, ApolloResponse> + KSuspendFunction1, ApolloResponse>, ) { class Fixture { val server = MockWebServer() @@ -78,7 +78,7 @@ abstract class SentryApollo4BuilderExtensionsTest( MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) return ApolloClient.Builder() diff --git a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt index 665a4a299c9..cb78ddcbd05 100644 --- a/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt +++ b/sentry-apollo-4/src/test/java/io/sentry/apollo4/SentryApollo4HttpInterceptorTest.kt @@ -77,7 +77,7 @@ class SentryApollo4HttpInterceptorTestWithV3Implementation : abstract class SentryApollo4HttpInterceptorTest( private val executeQueryImplementation: - KSuspendFunction1, ApolloResponse> + KSuspendFunction1, ApolloResponse>, ) { class Fixture { val server = MockWebServer() @@ -128,7 +128,7 @@ abstract class SentryApollo4HttpInterceptorTest( MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) if (beforeSpan != null) { @@ -308,8 +308,8 @@ abstract class SentryApollo4HttpInterceptorTest( assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=op")) @@ -400,8 +400,8 @@ abstract class SentryApollo4HttpInterceptorTest( beforeSpan = { span, request, response -> span.description = "overwritten description" span - } - ) + }, + ), ) verify(fixture.scopes) @@ -446,7 +446,7 @@ abstract class SentryApollo4HttpInterceptorTest( beforeSpan = { span, _, _ -> span.spanContext.sampled = false error("callback failed") - } + }, ) assertThat(executeQueryImplementation(sut.query(LaunchDetailsQuery("83"))).data).isNotNull() @@ -473,7 +473,7 @@ abstract class SentryApollo4HttpInterceptorTest( beforeSpan = { span, _, _ -> span.description = "partially modified" throw failure - } + }, ) val response = executeQueryImplementation(sut.query(LaunchDetailsQuery("83"))) diff --git a/sentry-apollo-5/src/main/java/io/sentry/apollo5/SentryApollo5HttpInterceptor.kt b/sentry-apollo-5/src/main/java/io/sentry/apollo5/SentryApollo5HttpInterceptor.kt index 8bcf97ae162..f273d438f34 100644 --- a/sentry-apollo-5/src/main/java/io/sentry/apollo5/SentryApollo5HttpInterceptor.kt +++ b/sentry-apollo-5/src/main/java/io/sentry/apollo5/SentryApollo5HttpInterceptor.kt @@ -138,7 +138,7 @@ constructor( var headers = request.headers.toMutableList() headers.add( - HttpHeader(tracingHeaders.sentryTraceHeader.name, tracingHeaders.sentryTraceHeader.value) + HttpHeader(tracingHeaders.sentryTraceHeader.name, tracingHeaders.sentryTraceHeader.value), ) tracingHeaders.baggageHeader?.let { baggageHeader -> headers = diff --git a/sentry-apollo-5/src/main/java/io/sentry/apollo5/SentryApolloBuilderExtensions.kt b/sentry-apollo-5/src/main/java/io/sentry/apollo5/SentryApolloBuilderExtensions.kt index aed866942b6..780cd4fc125 100644 --- a/sentry-apollo-5/src/main/java/io/sentry/apollo5/SentryApolloBuilderExtensions.kt +++ b/sentry-apollo-5/src/main/java/io/sentry/apollo5/SentryApolloBuilderExtensions.kt @@ -21,7 +21,7 @@ fun ApolloClient.Builder.sentryTracing( captureFailedRequests = captureFailedRequests, failedRequestTargets = failedRequestTargets, beforeSpan = beforeSpan, - ) + ), ) return this } diff --git a/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5BuilderExtensionsClientErrorsTest.kt b/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5BuilderExtensionsClientErrorsTest.kt index 1307544eb89..82f8471d9e4 100644 --- a/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5BuilderExtensionsClientErrorsTest.kt +++ b/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5BuilderExtensionsClientErrorsTest.kt @@ -44,7 +44,7 @@ class SentryApollo5BuilderExtensionsClientErrorsTestWithV5Implementation : abstract class SentryApollo5BuilderExtensionsClientErrorsTest( private val executeQueryImplementation: - KSuspendFunction1, ApolloResponse> + KSuspendFunction1, ApolloResponse>, ) { class Fixture { val server = MockWebServer() @@ -99,7 +99,7 @@ abstract class SentryApollo5BuilderExtensionsClientErrorsTest( sdkVersion = SdkVersion("test", "1.2.3") isSendDefaultPii = sendDefaultPii configureOptions() - } + }, ) } whenever(scopes.captureEvent(any(), any())).thenReturn(SentryId.EMPTY_ID) @@ -164,7 +164,7 @@ abstract class SentryApollo5BuilderExtensionsClientErrorsTest( fixture.getSut(captureFailedRequests = false) assertFalse( - SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo5ClientError") + SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo5ClientError"), ) } @@ -173,7 +173,7 @@ abstract class SentryApollo5BuilderExtensionsClientErrorsTest( fixture.getSut() assertTrue( - SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo5ClientError") + SentryIntegrationPackageStorage.getInstance().integrations.contains("Apollo5ClientError"), ) } diff --git a/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5BuilderExtensionsTest.kt b/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5BuilderExtensionsTest.kt index 4050fc2b607..465f5a97c31 100644 --- a/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5BuilderExtensionsTest.kt +++ b/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5BuilderExtensionsTest.kt @@ -55,7 +55,7 @@ class SentryApollo5BuilderExtensionsTestWithV5Implementation : abstract class SentryApollo5BuilderExtensionsTest( private val executeQueryImplementation: - KSuspendFunction1, ApolloResponse> + KSuspendFunction1, ApolloResponse>, ) { class Fixture { val server = MockWebServer() @@ -90,7 +90,7 @@ abstract class SentryApollo5BuilderExtensionsTest( MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) val builder = @@ -120,7 +120,7 @@ abstract class SentryApollo5BuilderExtensionsTest( transportBuilder.httpRequestComposer( object : HttpRequestComposer { override fun compose( - apolloRequest: ApolloRequest + apolloRequest: ApolloRequest, ): HttpRequest { val request = defaultComposer.compose(apolloRequest) return HttpRequest.Builder(request.method, request.url) @@ -129,14 +129,14 @@ abstract class SentryApollo5BuilderExtensionsTest( .addExecutionContext(apolloRequest.executionContext) .build() } - } + }, ) } else { transportBuilder.serverUrl(serverUrl) } if (manuallyInstallHttpInterceptor) { transportBuilder.addInterceptor( - SentryApollo5HttpInterceptor(scopes = scopes, captureFailedRequests = false) + SentryApollo5HttpInterceptor(scopes = scopes, captureFailedRequests = false), ) } @@ -261,7 +261,7 @@ abstract class SentryApollo5BuilderExtensionsTest( fixture.getSutWithCustomNetworkTransport( manuallyInstallHttpInterceptor = true, useCustomRequestComposer = true, - ) + ), ) verify(fixture.scopes) @@ -305,7 +305,7 @@ abstract class SentryApollo5BuilderExtensionsTest( operationName = LaunchDetailsQuery.OPERATION_NAME, operationType = "query", variables = "{id=83}", - ) + ), ) } @@ -371,7 +371,7 @@ abstract class SentryApollo5BuilderExtensionsTest( assertThat( recordedRequest.headers.names().none { it.startsWith("SENTRY-APOLLO-5-", ignoreCase = true) - } + }, ) .isTrue() } diff --git a/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5HttpInterceptorTest.kt b/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5HttpInterceptorTest.kt index f0f68e1bb33..3c5d6b5144f 100644 --- a/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5HttpInterceptorTest.kt +++ b/sentry-apollo-5/src/test/java/io/sentry/apollo5/SentryApollo5HttpInterceptorTest.kt @@ -73,7 +73,7 @@ class SentryApollo5HttpInterceptorTestWithV5Implementation : abstract class SentryApollo5HttpInterceptorTest( private val executeQueryImplementation: - KSuspendFunction1, ApolloResponse> + KSuspendFunction1, ApolloResponse>, ) { class Fixture { val server = MockWebServer() @@ -124,7 +124,7 @@ abstract class SentryApollo5HttpInterceptorTest( MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) if (beforeSpan != null) { @@ -403,8 +403,8 @@ abstract class SentryApollo5HttpInterceptorTest( assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=op")) @@ -418,8 +418,8 @@ abstract class SentryApollo5HttpInterceptorTest( beforeSpan = { span, request, response -> span.description = "overwritten description" span - } - ) + }, + ), ) verify(fixture.scopes) @@ -461,7 +461,7 @@ abstract class SentryApollo5HttpInterceptorTest( beforeSpan = { span, _, _ -> span.spanContext.sampled = false throw IllegalStateException("callback failed") - } + }, ) assertThat(executeQueryImplementation(sut.query(LaunchDetailsQuery("83"))).data).isNotNull() @@ -485,7 +485,7 @@ abstract class SentryApollo5HttpInterceptorTest( beforeSpan = { span, _, _ -> span.description = "partially modified" throw failure - } + }, ) val response = executeQueryImplementation(sut.query(LaunchDetailsQuery("83"))) diff --git a/sentry-apollo-5/src/test/java/io/sentry/apollo5/generated/selections/LaunchDetailsQuerySelections.kt b/sentry-apollo-5/src/test/java/io/sentry/apollo5/generated/selections/LaunchDetailsQuerySelections.kt index a36f4f962e8..43b07d3b1ae 100644 --- a/sentry-apollo-5/src/test/java/io/sentry/apollo5/generated/selections/LaunchDetailsQuerySelections.kt +++ b/sentry-apollo-5/src/test/java/io/sentry/apollo5/generated/selections/LaunchDetailsQuerySelections.kt @@ -34,8 +34,8 @@ public object LaunchDetailsQuerySelections { listOf( CompiledArgument.Builder(CompiledArgumentDefinition.Builder("size").build()) .value("LARGE") - .build() - ) + .build(), + ), ) .build(), ) @@ -90,10 +90,10 @@ public object LaunchDetailsQuerySelections { listOf( CompiledArgument.Builder(CompiledArgumentDefinition.Builder("id").build()) .value("id") - .build() - ) + .build(), + ), ) .selections(launch) - .build() + .build(), ) } diff --git a/sentry-apollo/src/test/java/io/sentry/apollo/SentryApolloInterceptorTest.kt b/sentry-apollo/src/test/java/io/sentry/apollo/SentryApolloInterceptorTest.kt index b212e2212c8..c31ccee0e7f 100644 --- a/sentry-apollo/src/test/java/io/sentry/apollo/SentryApolloInterceptorTest.kt +++ b/sentry-apollo/src/test/java/io/sentry/apollo/SentryApolloInterceptorTest.kt @@ -95,7 +95,7 @@ class SentryApolloInterceptorTest { MockResponse() .setBody(responseBody) .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) if (beforeSpan != null || !attachTracingHeaders) { @@ -232,7 +232,7 @@ class SentryApolloInterceptorTest { fixture.getSut { span, _, _ -> span.description = "overwritten description" span - } + }, ) verify(fixture.scopes) diff --git a/sentry-async-profiler/src/main/java/io/sentry/asyncprofiler/profiling/JavaContinuousProfiler.java b/sentry-async-profiler/src/main/java/io/sentry/asyncprofiler/profiling/JavaContinuousProfiler.java index ced363d4a58..c7e2bcdd9b2 100644 --- a/sentry-async-profiler/src/main/java/io/sentry/asyncprofiler/profiling/JavaContinuousProfiler.java +++ b/sentry-async-profiler/src/main/java/io/sentry/asyncprofiler/profiling/JavaContinuousProfiler.java @@ -400,23 +400,22 @@ private void sendChunks(final @NotNull IScopes scopes, final @NotNull SentryOpti try { options .getExecutorService() - .submit( - () -> { - // SDK is closed, we don't send the chunks - if (isClosed.get()) { - return; - } - final ArrayList payloads = new ArrayList<>(payloadBuilders.size()); - try (final @NotNull ISentryLifecycleToken ignored = payloadLock.acquire()) { - for (ProfileChunk.Builder builder : payloadBuilders) { - payloads.add(builder.build(options)); - } - payloadBuilders.clear(); - } - for (ProfileChunk payload : payloads) { - scopes.captureProfileChunk(payload); - } - }); + .submit(() -> { + // SDK is closed, we don't send the chunks + if (isClosed.get()) { + return; + } + final ArrayList payloads = new ArrayList<>(payloadBuilders.size()); + try (final @NotNull ISentryLifecycleToken ignored = payloadLock.acquire()) { + for (ProfileChunk.Builder builder : payloadBuilders) { + payloads.add(builder.build(options)); + } + payloadBuilders.clear(); + } + for (ProfileChunk payload : payloads) { + scopes.captureProfileChunk(payload); + } + }); } catch (Throwable e) { options.getLogger().log(SentryLevel.DEBUG, "Failed to send profile chunks.", e); } diff --git a/sentry-async-profiler/src/test/java/io/sentry/asyncprofiler/profiling/JavaContinuousProfilerTest.kt b/sentry-async-profiler/src/test/java/io/sentry/asyncprofiler/profiling/JavaContinuousProfilerTest.kt index 745139a20a6..3ffc4ef6bae 100644 --- a/sentry-async-profiler/src/test/java/io/sentry/asyncprofiler/profiling/JavaContinuousProfilerTest.kt +++ b/sentry-async-profiler/src/test/java/io/sentry/asyncprofiler/profiling/JavaContinuousProfilerTest.kt @@ -277,7 +277,7 @@ class JavaContinuousProfilerTest { .log( eq(SentryLevel.WARNING), eq( - "Disabling profiling because traces directory is not writable or does not exist: %s (writable=%b, exists=%b)" + "Disabling profiling because traces directory is not writable or does not exist: %s (writable=%b, exists=%b)", ), eq(expectedPath), eq(false), diff --git a/sentry-compose/build.gradle.kts b/sentry-compose/build.gradle.kts index 158058507f8..0c5d585989a 100644 --- a/sentry-compose/build.gradle.kts +++ b/sentry-compose/build.gradle.kts @@ -16,6 +16,7 @@ plugins { id("io.sentry.jdk-target") id("io.sentry.publish.multiplatform") id("io.sentry.api-validation") + id("io.sentry.robolectric") } kotlin { @@ -116,6 +117,10 @@ android { // We run a full lint analysis as build part in CI, so skip vital checks for assemble tasks. checkReleaseBuilds = false + + // Lint 9.5 can't load the custom checks bundled with older androidx.lifecycle releases and + // reports that it skips them. They only cover lifecycle APIs this module doesn't call. + disable += "ObsoleteLintCustomCheck" } buildFeatures { buildConfig = true } @@ -137,9 +142,9 @@ tasks.withType().configureEach { // suppress unattached source sets for docs dokkaSourceSets { matching { - it.name.contains("androidandroid", ignoreCase = true) || - it.name.contains("testfixtures", ignoreCase = true) - } + it.name.contains("androidandroid", ignoreCase = true) || + it.name.contains("testfixtures", ignoreCase = true) + } .configureEach { suppress.set(true) } } } diff --git a/sentry-compose/proguard-rules.pro b/sentry-compose/proguard-rules.pro index ea5984aa88e..30473497a5f 100644 --- a/sentry-compose/proguard-rules.pro +++ b/sentry-compose/proguard-rules.pro @@ -13,6 +13,7 @@ -keepnames class androidx.compose.foundation.CombinedClickableElement -keepnames class androidx.compose.foundation.ScrollingLayoutElement -keepnames class androidx.compose.foundation.ScrollingContainerElement +-keepnames class androidx.compose.foundation.ScrollableAreaElement -keepnames class androidx.compose.ui.platform.TestTagElement { *; } -keepnames class io.sentry.compose.SentryModifier$SentryTagModifierNodeElement { *; } diff --git a/sentry-compose/src/androidMain/kotlin/io/sentry/compose/SentryNavigationIntegration.kt b/sentry-compose/src/androidMain/kotlin/io/sentry/compose/SentryNavigationIntegration.kt index b95f65393d3..07dd300075f 100644 --- a/sentry-compose/src/androidMain/kotlin/io/sentry/compose/SentryNavigationIntegration.kt +++ b/sentry-compose/src/androidMain/kotlin/io/sentry/compose/SentryNavigationIntegration.kt @@ -59,7 +59,7 @@ internal class SentryLifecycleObserver( @Composable @NonRestartableComposable public fun NavHostController.withSentryObservableEffect( - navListener: SentryNavigationListener + navListener: SentryNavigationListener, ): NavHostController { val navListenerSnapshot by rememberUpdatedState(navListener) @@ -105,7 +105,7 @@ public fun NavHostController.withSentryObservableEffect( enableNavigationBreadcrumbs = enableBreadcrumbsSnapshot, enableNavigationTracing = enableTracingSnapshot, traceOriginAppendix = TRACE_ORIGIN_APPENDIX, - ) + ), ) } diff --git a/sentry-compose/src/androidMain/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocator.kt b/sentry-compose/src/androidMain/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocator.kt index 47dda6eda9c..ba011e455ab 100644 --- a/sentry-compose/src/androidMain/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocator.kt +++ b/sentry-compose/src/androidMain/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocator.kt @@ -83,9 +83,7 @@ public class ComposeGestureTargetLocator(private val logger: ILogger) : GestureT ) { targetTag = tag } else if ( - targetType == UiElement.Type.SCROLLABLE && - ("androidx.compose.foundation.ScrollingLayoutElement" == type || - "androidx.compose.foundation.ScrollingContainerElement" == type) + targetType == UiElement.Type.SCROLLABLE && type in SCROLLABLE_ELEMENT_TYPES ) { return UiElement(null, null, null, tag, ORIGIN) } @@ -130,5 +128,14 @@ public class ComposeGestureTargetLocator(private val logger: ILogger) : GestureT public companion object { private const val ORIGIN = "jetpack_compose" + + private val SCROLLABLE_ELEMENT_TYPES = + setOf( + "androidx.compose.foundation.ScrollingLayoutElement", + "androidx.compose.foundation.ScrollingContainerElement", + // Compose foundation 1.10+: lazy layouts and pagers use ScrollableAreaElement + // in place of ScrollingContainerElement + "androidx.compose.foundation.ScrollableAreaElement", + ) } } diff --git a/sentry-compose/src/androidUnitTest/kotlin/androidx/compose/foundation/GestureModifierStubs.kt b/sentry-compose/src/androidUnitTest/kotlin/androidx/compose/foundation/GestureModifierStubs.kt index 43b3e53bc67..052158c1243 100644 --- a/sentry-compose/src/androidUnitTest/kotlin/androidx/compose/foundation/GestureModifierStubs.kt +++ b/sentry-compose/src/androidUnitTest/kotlin/androidx/compose/foundation/GestureModifierStubs.kt @@ -13,3 +13,5 @@ internal open class CombinedClickableElement : Modifier.Element internal open class ScrollingLayoutElement : Modifier.Element internal open class ScrollingContainerElement : Modifier.Element + +internal open class ScrollableAreaElement : Modifier.Element diff --git a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/ComposeIntegrationTests.kt b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/ComposeIntegrationTests.kt index f4195b1d6f3..c7be12652ab 100644 --- a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/ComposeIntegrationTests.kt +++ b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/ComposeIntegrationTests.kt @@ -39,7 +39,7 @@ class ComposeIntegrationTests { val appContext: Application = ApplicationProvider.getApplicationContext() Shadows.shadowOf(appContext.packageManager) .addActivityIfNotPresent( - ComponentName(appContext.packageName, ComponentActivity::class.java.name) + ComponentName(appContext.packageName, ComponentActivity::class.java.name), ) } } diff --git a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/SentryModifierComposeTest.kt b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/SentryModifierComposeTest.kt index 7e80f10a5e7..42728885d5e 100644 --- a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/SentryModifierComposeTest.kt +++ b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/SentryModifierComposeTest.kt @@ -35,7 +35,7 @@ class SentryModifierComposeTest { val appContext: Application = ApplicationProvider.getApplicationContext() Shadows.shadowOf(appContext.packageManager) .addActivityIfNotPresent( - ComponentName(appContext.packageName, ComponentActivity::class.java.name) + ComponentName(appContext.packageName, ComponentActivity::class.java.name), ) } } @@ -49,7 +49,7 @@ class SentryModifierComposeTest { .onNode( SemanticsMatcher(TAG_VALUE) { it.config.find { (key, _) -> key.name == SentryModifier.TAG }?.value == TAG_VALUE - } + }, ) .assertExists() } diff --git a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/SentryTracedTest.kt b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/SentryTracedTest.kt index 935fb6933d5..73b2ebc8201 100644 --- a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/SentryTracedTest.kt +++ b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/SentryTracedTest.kt @@ -60,7 +60,7 @@ class SentryTracedTest { val appContext: Application = ApplicationProvider.getApplicationContext() Shadows.shadowOf(appContext.packageManager) .addActivityIfNotPresent( - ComponentName(appContext.packageName, ComponentActivity::class.java.name) + ComponentName(appContext.packageName, ComponentActivity::class.java.name), ) } } @@ -86,7 +86,7 @@ class SentryTracedTest { assertThat(tx.countSpans(OP_COMPOSE)).isEqualTo(1) assertThat(tx.countSpans(OP_PARENT_RENDER)).isEqualTo(0) assertThat( - tx.singleSpan(OP_PARENT_COMPOSITION).startDate.isAfter(tx.singleSpan(OP_COMPOSE).startDate) + tx.singleSpan(OP_PARENT_COMPOSITION).startDate.isAfter(tx.singleSpan(OP_COMPOSE).startDate), ) .isFalse() } @@ -415,7 +415,7 @@ class SentryTracedTest { modifier = Modifier.fillMaxSize(), enableUserInteractionTracing = false, ) {} - } + }, ) { measurables, constraints -> val placeable = measurables.single().measure(constraints) layout(placeable.width, placeable.height) { diff --git a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocatorTest.kt b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocatorTest.kt index 8efdf3ebe30..ae51ee4bd23 100644 --- a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocatorTest.kt +++ b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/gestures/ComposeGestureTargetLocatorTest.kt @@ -217,6 +217,31 @@ class ComposeGestureTargetLocatorTest { assertEquals("scroll", result!!.tag) } + @Test + fun `detects scrollable via ScrollableAreaElement modifier`() { + val scrollableChild = + mockLayoutNode( + isPlaced = true, + tag = "scroll", + width = 50, + height = 50, + nodeModifierClassName = "androidx.compose.foundation.ScrollableAreaElement", + ) + val root = + mockLayoutNode( + isPlaced = true, + tag = null, + width = 100, + height = 100, + children = listOf(scrollableChild), + ) + val owner = mockOwner(root) + + val result = locator.locate(owner, 5f, 5f, UiElement.Type.SCROLLABLE) + assertNotNull(result) + assertEquals("scroll", result!!.tag) + } + @Test fun `ignores clickable when looking for scrollable`() { val clickableChild = @@ -663,7 +688,7 @@ class ComposeGestureTargetLocatorTest { config.set(SemanticsPropertyKey("TestTag") { s: String?, _: String? -> s }, tag) return config } - } + }, ) return modifierInfo } @@ -681,7 +706,7 @@ class ComposeGestureTargetLocatorTest { } return config } - } + }, ) return modifierInfo } @@ -693,7 +718,7 @@ class ComposeGestureTargetLocatorTest { Class.forName(className) } catch (_: ClassNotFoundException) { Modifier::class.java - } + }, ) as Modifier val modifierInfo = Mockito.mock(ModifierInfo::class.java) whenever(modifierInfo.modifier).thenReturn(modifierWithClassName) diff --git a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/viewhierarchy/ComposeViewHierarchyExporterTest.kt b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/viewhierarchy/ComposeViewHierarchyExporterTest.kt index 7113db59d6c..7679ce05bee 100644 --- a/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/viewhierarchy/ComposeViewHierarchyExporterTest.kt +++ b/sentry-compose/src/androidUnitTest/kotlin/io/sentry/compose/viewhierarchy/ComposeViewHierarchyExporterTest.kt @@ -78,7 +78,7 @@ class ComposeViewHierarchyExporterTest { config.set(SemanticsPropertyKey("SentryTag") { s: String?, s2: String? -> s }, tag) return config } - } + }, ) val modifierInfoList: MutableList = ArrayList() modifierInfoList.add(modifierInfo) diff --git a/sentry-graphql-22/src/main/java/io/sentry/graphql22/SentryInstrumentation.java b/sentry-graphql-22/src/main/java/io/sentry/graphql22/SentryInstrumentation.java index d4833cafee3..e4f08e6fbbd 100644 --- a/sentry-graphql-22/src/main/java/io/sentry/graphql22/SentryInstrumentation.java +++ b/sentry-graphql-22/src/main/java/io/sentry/graphql22/SentryInstrumentation.java @@ -170,10 +170,9 @@ public SentryInstrumentation( final @NotNull InstrumentationExecutionParameters parameters, final @NotNull InstrumentationState state) { return super.instrumentExecutionResult(executionResult, parameters, state) - .whenComplete( - (result, exception) -> { - instrumentation.instrumentExecutionResultComplete(parameters, result, exception); - }); + .whenComplete((result, exception) -> { + instrumentation.instrumentExecutionResultComplete(parameters, result, exception); + }); } @Override diff --git a/sentry-graphql-22/src/test/kotlin/io/sentry/graphql22/SentryInstrumentationAnotherTest.kt b/sentry-graphql-22/src/test/kotlin/io/sentry/graphql22/SentryInstrumentationAnotherTest.kt index 238b420bc16..574883936d7 100644 --- a/sentry-graphql-22/src/test/kotlin/io/sentry/graphql22/SentryInstrumentationAnotherTest.kt +++ b/sentry-graphql-22/src/test/kotlin/io/sentry/graphql22/SentryInstrumentationAnotherTest.kt @@ -316,7 +316,7 @@ class SentryInstrumentationAnotherTest { fixture.executionContext.executionId.toString(), breadcrumb.data["operation_id"], ) - } + }, ) } @@ -368,7 +368,7 @@ class SentryInstrumentationAnotherTest { assertSame( fixture.scopes, fixture.instrumentationExecutionParameters.graphQLContext.get( - SentryGraphqlInstrumentation.SENTRY_SCOPES_CONTEXT_KEY + SentryGraphqlInstrumentation.SENTRY_SCOPES_CONTEXT_KEY, ), ) assertNotNull(fixture.instrumentationState.transaction) @@ -385,7 +385,7 @@ class SentryInstrumentationAnotherTest { GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(ErrorType.ValidationError) - .build() + .build(), ) .build() val resultFuture = @@ -418,7 +418,7 @@ class SentryInstrumentationAnotherTest { mapOf( SentryGraphqlInstrumentation.SENTRY_EXCEPTIONS_CONTEXT_KEY to listOf(exception), SentryGraphqlInstrumentation.SENTRY_SCOPES_CONTEXT_KEY to fixture.scopes, - ) + ), ) val executionResult = ExecutionResult.newExecutionResult().data("raw result").build() val resultFuture = @@ -452,19 +452,19 @@ class SentryInstrumentationAnotherTest { GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(ErrorType.DataFetchingException) - .build() + .build(), ) .addError( GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(org.springframework.graphql.execution.ErrorType.INTERNAL_ERROR) - .build() + .build(), ) .addError( GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(com.netflix.graphql.types.errors.ErrorType.INTERNAL) - .build() + .build(), ) .build() val resultFuture = @@ -488,7 +488,7 @@ class SentryInstrumentationAnotherTest { GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(SomeErrorClassification.SOME_ERROR) - .build() + .build(), ) .build() val resultFuture = @@ -526,6 +526,6 @@ class SentryInstrumentationAnotherTest { data class Show(val id: Int) enum class SomeErrorClassification : ErrorClassification { - SOME_ERROR + SOME_ERROR, } } diff --git a/sentry-graphql-22/src/test/kotlin/io/sentry/graphql22/SentryInstrumentationTest.kt b/sentry-graphql-22/src/test/kotlin/io/sentry/graphql22/SentryInstrumentationTest.kt index a28ff2af582..6d37b68a191 100644 --- a/sentry-graphql-22/src/test/kotlin/io/sentry/graphql22/SentryInstrumentationTest.kt +++ b/sentry-graphql-22/src/test/kotlin/io/sentry/graphql22/SentryInstrumentationTest.kt @@ -85,7 +85,7 @@ class SentryInstrumentationTest { val graphQL = GraphQL.newGraphQL(graphQLSchema) .instrumentation( - SentryInstrumentation(beforeSpan, NoOpSubscriptionHandler.getInstance(), true) + SentryInstrumentation(beforeSpan, NoOpSubscriptionHandler.getInstance(), true), ) .build() @@ -166,7 +166,7 @@ class SentryInstrumentationTest { fun `beforeSpan can drop spans`() { val sut = fixture.getSut( - beforeSpan = SentryGraphqlInstrumentation.BeforeSpanCallback { _, _, _ -> null } + beforeSpan = SentryGraphqlInstrumentation.BeforeSpanCallback { _, _, _ -> null }, ) val onDiscard = mock() fixture.scopes.options.onDiscard = onDiscard @@ -194,7 +194,7 @@ class SentryInstrumentationTest { beforeSpan = { span, _, _ -> span.spanContext.sampled = false throw IllegalStateException("callback failed") - } + }, ) fixture.activeSpan.spanContext.sampled = sampled fixture.scopes.options.onDiscard = onDiscard @@ -220,7 +220,7 @@ class SentryInstrumentationTest { beforeSpan = { span, _, _ -> span.description = "partially modified" throw failure - } + }, ) fixture.scopes.options.isDebug = true fixture.scopes.options.setLogger(logger) @@ -300,7 +300,7 @@ class SentryInstrumentationTest { beforeSpan = SentryGraphqlInstrumentation.BeforeSpanCallback { span, _, _ -> span.apply { description = "changed" } - } + }, ) withMockScopes { @@ -333,7 +333,7 @@ class SentryInstrumentationTest { GraphQLScalarType.newScalar() .name("MyResponseType") .coercing(GraphqlStringCoercing()) - .build() + .build(), ) .build() val environment = @@ -341,7 +341,7 @@ class SentryInstrumentationTest { .graphQLContext(graphQLContext) .executionStepInfo(executionStepInfo) .operationDefinition( - OperationDefinition.newOperationDefinition().operation(operation).build() + OperationDefinition.newOperationDefinition().operation(operation).build(), ) .build() val executionContext = diff --git a/sentry-graphql-core/src/main/java/io/sentry/graphql/ExceptionReporter.java b/sentry-graphql-core/src/main/java/io/sentry/graphql/ExceptionReporter.java index 86eac63fc43..cae1eade220 100644 --- a/sentry-graphql-core/src/main/java/io/sentry/graphql/ExceptionReporter.java +++ b/sentry-graphql-core/src/main/java/io/sentry/graphql/ExceptionReporter.java @@ -72,13 +72,12 @@ private void setRequestDetailsOnEvent( final @NotNull IScopes scopes, final @NotNull ExceptionDetails exceptionDetails, final @NotNull SentryEvent event) { - scopes.configureScope( - (scope) -> { - final @Nullable Request scopeRequest = scope.getRequest(); - final @NotNull Request request = scopeRequest == null ? new Request() : scopeRequest; - setDetailsOnRequest(scopes, exceptionDetails, request); - event.setRequest(request); - }); + scopes.configureScope(scope -> { + final @Nullable Request scopeRequest = scope.getRequest(); + final @NotNull Request request = scopeRequest == null ? new Request() : scopeRequest; + setDetailsOnRequest(scopes, exceptionDetails, request); + event.setRequest(request); + }); } private void setDetailsOnRequest( diff --git a/sentry-graphql-core/src/main/java/io/sentry/graphql/SentryGraphqlInstrumentation.java b/sentry-graphql-core/src/main/java/io/sentry/graphql/SentryGraphqlInstrumentation.java index cb1757e30d4..3d1a53f2b6d 100644 --- a/sentry-graphql-core/src/main/java/io/sentry/graphql/SentryGraphqlInstrumentation.java +++ b/sentry-graphql-core/src/main/java/io/sentry/graphql/SentryGraphqlInstrumentation.java @@ -292,16 +292,15 @@ public void beginExecuteOperation( maybeCallSubscriptionHandler(parameters, environment, tmpResult); if (result instanceof CompletableFuture) { ((CompletableFuture) result) - .whenComplete( - (r, ex) -> { - if (ex != null) { - span.setThrowable(ex); - span.setStatus(SpanStatus.INTERNAL_ERROR); - } else { - span.setStatus(SpanStatus.OK); - } - finish(span, environment, r); - }); + .whenComplete((r, ex) -> { + if (ex != null) { + span.setThrowable(ex); + span.setStatus(SpanStatus.INTERNAL_ERROR); + } else { + span.setStatus(SpanStatus.OK); + } + finish(span, environment, r); + }); } else { span.setStatus(SpanStatus.OK); finish(span, environment, result); diff --git a/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/ExceptionReporterTest.kt b/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/ExceptionReporterTest.kt index c054911396d..0124c603834 100644 --- a/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/ExceptionReporterTest.kt +++ b/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/ExceptionReporterTest.kt @@ -64,7 +64,7 @@ class ExceptionReporterTest { GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(ErrorType.ValidationError) - .build() + .build(), ) .build() val executionInput = diff --git a/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/SentryGenericDataFetcherExceptionHandlerTest.kt b/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/SentryGenericDataFetcherExceptionHandlerTest.kt index 927829632b6..07324a2a3f0 100644 --- a/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/SentryGenericDataFetcherExceptionHandlerTest.kt +++ b/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/SentryGenericDataFetcherExceptionHandlerTest.kt @@ -26,7 +26,7 @@ class SentryGenericDataFetcherExceptionHandlerTest { .dataFetchingEnvironment( DataFetchingEnvironmentImpl.newDataFetchingEnvironment() .graphQLContext(GraphQLContext.of(emptyMap())) - .build() + .build(), ) .build() handler.onException(parameters) diff --git a/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/SentryGraphqlInstrumentationTest.kt b/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/SentryGraphqlInstrumentationTest.kt index 09843710bea..b5789c7e9da 100644 --- a/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/SentryGraphqlInstrumentationTest.kt +++ b/sentry-graphql-core/src/test/kotlin/io/sentry/graphql/SentryGraphqlInstrumentationTest.kt @@ -24,7 +24,7 @@ class SentryGraphqlInstrumentationTest { .thenReturn( GraphQLContext.newContext() .of(SentryGraphqlInstrumentation.SENTRY_SCOPES_CONTEXT_KEY, scopes) - .build() + .build(), ) } @@ -45,7 +45,7 @@ class SentryGraphqlInstrumentationTest { CustomErrorClassification( "graphql.validation.interpolation.ResourceBundleMessageInterpolator\$ValidationErrorType@1", mapOf("type" to "ExtendedValidationError"), - ) + ), ), ignoredErrorTypes = listOf("ExtendedValidationError"), ) @@ -73,7 +73,7 @@ class SentryGraphqlInstrumentationTest { CustomErrorClassification( "graphql.validation.interpolation.ResourceBundleMessageInterpolator\$ValidationErrorType@1", mapOf("type" to "ExtendedValidationError"), - ) + ), ), ignoredErrorTypes = listOf("ExtendedValidationError"), enableSpecificationErrorTypeFiltering = true, diff --git a/sentry-graphql/src/main/java/io/sentry/graphql/SentryInstrumentation.java b/sentry-graphql/src/main/java/io/sentry/graphql/SentryInstrumentation.java index 0d0736f8b70..456bd96d6e2 100644 --- a/sentry-graphql/src/main/java/io/sentry/graphql/SentryInstrumentation.java +++ b/sentry-graphql/src/main/java/io/sentry/graphql/SentryInstrumentation.java @@ -163,10 +163,9 @@ public SentryInstrumentation( public CompletableFuture instrumentExecutionResult( ExecutionResult executionResult, InstrumentationExecutionParameters parameters) { return super.instrumentExecutionResult(executionResult, parameters) - .whenComplete( - (result, exception) -> { - instrumentation.instrumentExecutionResultComplete(parameters, result, exception); - }); + .whenComplete((result, exception) -> { + instrumentation.instrumentExecutionResultComplete(parameters, result, exception); + }); } @Override diff --git a/sentry-graphql/src/test/kotlin/io/sentry/graphql/SentryInstrumentationAnotherTest.kt b/sentry-graphql/src/test/kotlin/io/sentry/graphql/SentryInstrumentationAnotherTest.kt index 9d77da698ac..d1742bc45dc 100644 --- a/sentry-graphql/src/test/kotlin/io/sentry/graphql/SentryInstrumentationAnotherTest.kt +++ b/sentry-graphql/src/test/kotlin/io/sentry/graphql/SentryInstrumentationAnotherTest.kt @@ -287,7 +287,7 @@ class SentryInstrumentationAnotherTest { fixture.executionContext.executionId.toString(), breadcrumb.data["operation_id"], ) - } + }, ) } @@ -332,7 +332,7 @@ class SentryInstrumentationAnotherTest { assertSame( fixture.scopes, fixture.instrumentationExecutionParameters.graphQLContext.get( - SentryGraphqlInstrumentation.SENTRY_SCOPES_CONTEXT_KEY + SentryGraphqlInstrumentation.SENTRY_SCOPES_CONTEXT_KEY, ), ) assertNotNull(fixture.instrumentationState.transaction) @@ -349,7 +349,7 @@ class SentryInstrumentationAnotherTest { GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(ErrorType.ValidationError) - .build() + .build(), ) .build() val resultFuture = @@ -381,7 +381,7 @@ class SentryInstrumentationAnotherTest { mapOf( SentryGraphqlInstrumentation.SENTRY_EXCEPTIONS_CONTEXT_KEY to listOf(exception), SentryGraphqlInstrumentation.SENTRY_SCOPES_CONTEXT_KEY to fixture.scopes, - ) + ), ) val executionResult = ExecutionResultImpl.newExecutionResult().data("raw result").build() val resultFuture = @@ -414,19 +414,19 @@ class SentryInstrumentationAnotherTest { GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(ErrorType.DataFetchingException) - .build() + .build(), ) .addError( GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(org.springframework.graphql.execution.ErrorType.INTERNAL_ERROR) - .build() + .build(), ) .addError( GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(com.netflix.graphql.types.errors.ErrorType.INTERNAL) - .build() + .build(), ) .build() val resultFuture = @@ -449,7 +449,7 @@ class SentryInstrumentationAnotherTest { GraphqlErrorException.newErrorException() .message("exception message") .errorClassification(SomeErrorClassification.SOME_ERROR) - .build() + .build(), ) .build() val resultFuture = @@ -485,6 +485,6 @@ class SentryInstrumentationAnotherTest { data class Show(val id: Int) enum class SomeErrorClassification : ErrorClassification { - SOME_ERROR + SOME_ERROR, } } diff --git a/sentry-graphql/src/test/kotlin/io/sentry/graphql/SentryInstrumentationTest.kt b/sentry-graphql/src/test/kotlin/io/sentry/graphql/SentryInstrumentationTest.kt index 5f61ccfe912..117ba8314d3 100644 --- a/sentry-graphql/src/test/kotlin/io/sentry/graphql/SentryInstrumentationTest.kt +++ b/sentry-graphql/src/test/kotlin/io/sentry/graphql/SentryInstrumentationTest.kt @@ -81,7 +81,7 @@ class SentryInstrumentationTest { val graphQL = GraphQL.newGraphQL(graphQLSchema) .instrumentation( - SentryInstrumentation(beforeSpan, NoOpSubscriptionHandler.getInstance(), true) + SentryInstrumentation(beforeSpan, NoOpSubscriptionHandler.getInstance(), true), ) .build() @@ -162,7 +162,7 @@ class SentryInstrumentationTest { fun `beforeSpan can drop spans`() { val sut = fixture.getSut( - beforeSpan = SentryGraphqlInstrumentation.BeforeSpanCallback { _, _, _ -> null } + beforeSpan = SentryGraphqlInstrumentation.BeforeSpanCallback { _, _, _ -> null }, ) val onDiscard = mock() fixture.scopes.options.onDiscard = onDiscard @@ -190,7 +190,7 @@ class SentryInstrumentationTest { beforeSpan = { span, _, _ -> span.spanContext.sampled = false throw IllegalStateException("callback failed") - } + }, ) fixture.activeSpan.spanContext.sampled = sampled fixture.scopes.options.onDiscard = onDiscard @@ -216,7 +216,7 @@ class SentryInstrumentationTest { beforeSpan = { span, _, _ -> span.description = "partially modified" throw failure - } + }, ) fixture.scopes.options.isDebug = true fixture.scopes.options.setLogger(logger) @@ -296,7 +296,7 @@ class SentryInstrumentationTest { beforeSpan = SentryGraphqlInstrumentation.BeforeSpanCallback { span, _, _ -> span.apply { description = "changed" } - } + }, ) withMockScopes { @@ -329,7 +329,7 @@ class SentryInstrumentationTest { GraphQLScalarType.newScalar() .name("MyResponseType") .coercing(GraphqlStringCoercing()) - .build() + .build(), ) .build() val environment = @@ -337,7 +337,7 @@ class SentryInstrumentationTest { .graphQLContext(graphQLContext) .executionStepInfo(executionStepInfo) .operationDefinition( - OperationDefinition.newOperationDefinition().operation(operation).build() + OperationDefinition.newOperationDefinition().operation(operation).build(), ) .build() val executionContext = diff --git a/sentry-jcache/src/test/kotlin/io/sentry/jcache/SentryJCacheWrapperTest.kt b/sentry-jcache/src/test/kotlin/io/sentry/jcache/SentryJCacheWrapperTest.kt index 9e523d3df21..bde3860d7fe 100644 --- a/sentry-jcache/src/test/kotlin/io/sentry/jcache/SentryJCacheWrapperTest.kt +++ b/sentry-jcache/src/test/kotlin/io/sentry/jcache/SentryJCacheWrapperTest.kt @@ -470,7 +470,9 @@ class SentryJCacheWrapperTest { fun `getConfiguration delegates to underlying cache`() { val config = mock>() whenever( - delegate.getConfiguration(Configuration::class.java as Class>) + delegate.getConfiguration( + Configuration::class.java as Class>, + ), ) .thenReturn(config) val wrapper = SentryJCacheWrapper(delegate, scopes) diff --git a/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/DatabaseUtilsTest.kt b/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/DatabaseUtilsTest.kt index 8f8b25007b7..27a6ac69708 100644 --- a/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/DatabaseUtilsTest.kt +++ b/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/DatabaseUtilsTest.kt @@ -123,7 +123,7 @@ class DatabaseUtilsTest { fun `detects db system for dynamodb`() { val details = DatabaseUtils.parse( - "jdbc:amazondynamodb:Access Key=xxx;Secret Key=xxx;Domain=amazonaws.com;Region=OREGON;" + "jdbc:amazondynamodb:Access Key=xxx;Secret Key=xxx;Domain=amazonaws.com;Region=OREGON;", ) assertEquals("amazondynamodb", details.dbSystem) assertNull(details.dbName) @@ -140,7 +140,7 @@ class DatabaseUtilsTest { fun `detects db system for oracle2`() { val details = DatabaseUtils.parse( - "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myoracle.db.server)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=my_servicename)))" + "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myoracle.db.server)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=my_servicename)))", ) assertEquals("oracle", details.dbSystem) assertEquals("my_servicename", details.dbName) @@ -150,7 +150,7 @@ class DatabaseUtilsTest { fun `detects db system for mariadb`() { val details = DatabaseUtils.parse( - "jdbc:mariadb://example.skysql.net:5001/jdbc_demo?useSsl=true&serverSslCert=/path/to/skysql_chain.pem" + "jdbc:mariadb://example.skysql.net:5001/jdbc_demo?useSsl=true&serverSslCert=/path/to/skysql_chain.pem", ) assertEquals("mariadb", details.dbSystem) assertEquals("jdbc_demo", details.dbName) @@ -167,7 +167,7 @@ class DatabaseUtilsTest { fun `detects db system for mysql`() { val details = DatabaseUtils.parse( - "jdbc:mysql://mysql.db.server:3306/my_database?useSSL=false&serverTimezone=UTC" + "jdbc:mysql://mysql.db.server:3306/my_database?useSSL=false&serverTimezone=UTC", ) assertEquals("mysql", details.dbSystem) assertEquals("my_database", details.dbName) @@ -184,7 +184,7 @@ class DatabaseUtilsTest { fun `detects db system for mssql`() { val details = DatabaseUtils.parse( - "jdbc:sqlserver://mssql.db.server\\\\mssql_instance;databaseName=my_database" + "jdbc:sqlserver://mssql.db.server\\\\mssql_instance;databaseName=my_database", ) assertEquals("sqlserver", details.dbSystem) assertEquals("my_database", details.dbName) @@ -194,7 +194,7 @@ class DatabaseUtilsTest { fun `detects db system for mssql2`() { val details = DatabaseUtils.parse( - "jdbc:sqlserver://mssql.db.server\\\\mssql_instance;databaseName=my_database;otherProperty=value" + "jdbc:sqlserver://mssql.db.server\\\\mssql_instance;databaseName=my_database;otherProperty=value", ) assertEquals("sqlserver", details.dbSystem) assertEquals("my_database", details.dbName) @@ -212,7 +212,7 @@ class DatabaseUtilsTest { fun `detects db system for postgres`() { val details = DatabaseUtils.parse( - "jdbc:postgresql://postgresql.db.server:5430/my_database?ssl=true&loglevel=2" + "jdbc:postgresql://postgresql.db.server:5430/my_database?ssl=true&loglevel=2", ) assertEquals("postgresql", details.dbSystem) assertEquals("my_database", details.dbName) @@ -229,7 +229,7 @@ class DatabaseUtilsTest { fun `detects db system for datadirect postgres`() { val details = DatabaseUtils.parse( - "jdbc:datadirect:postgresql://postgresql.db.server:5430/my_database?ssl=true&loglevel=2" + "jdbc:datadirect:postgresql://postgresql.db.server:5430/my_database?ssl=true&loglevel=2", ) assertEquals("postgresql", details.dbSystem) assertEquals("my_database", details.dbName) @@ -239,7 +239,7 @@ class DatabaseUtilsTest { fun `detects db system for tibcosoftware postgres`() { val details = DatabaseUtils.parse( - "jdbc:tibcosoftware:postgresql://postgresql.db.server:5430/my_database?ssl=true&loglevel=2" + "jdbc:tibcosoftware:postgresql://postgresql.db.server:5430/my_database?ssl=true&loglevel=2", ) assertEquals("postgresql", details.dbSystem) assertEquals("my_database", details.dbName) @@ -249,7 +249,7 @@ class DatabaseUtilsTest { fun `detects db system for jtds postgres`() { val details = DatabaseUtils.parse( - "jdbc:jtds:postgresql://postgresql.db.server:5430/my_database?ssl=true&loglevel=2" + "jdbc:jtds:postgresql://postgresql.db.server:5430/my_database?ssl=true&loglevel=2", ) assertEquals("postgresql", details.dbSystem) assertEquals("my_database", details.dbName) @@ -259,7 +259,7 @@ class DatabaseUtilsTest { fun `detects db system for microsoft sqlserver`() { val details = DatabaseUtils.parse( - "jdbc:microsoft:sqlserver://mssql.db.server\\\\mssql_instance;databaseName=my_database" + "jdbc:microsoft:sqlserver://mssql.db.server\\\\mssql_instance;databaseName=my_database", ) assertEquals("sqlserver", details.dbSystem) assertEquals("my_database", details.dbName) diff --git a/sentry-jul/src/test/kotlin/io/sentry/jul/SentryHandlerTest.kt b/sentry-jul/src/test/kotlin/io/sentry/jul/SentryHandlerTest.kt index 9ab96f451e9..647b043eb55 100644 --- a/sentry-jul/src/test/kotlin/io/sentry/jul/SentryHandlerTest.kt +++ b/sentry-jul/src/test/kotlin/io/sentry/jul/SentryHandlerTest.kt @@ -289,7 +289,7 @@ class SentryHandlerTest { fixture = Fixture() fixture.logger.config( - "this should not be a breadcrumb as the level is lower than the minimum INFO" + "this should not be a breadcrumb as the level is lower than the minimum INFO", ) fixture.logger.info("this should be a breadcrumb") fixture.logger.warning("this should not be sent as the event but be a breadcrumb") @@ -339,7 +339,7 @@ class SentryHandlerTest { .send( checkLogs { logs -> assertEquals("this should be captured as a log", logs.items.first().body) - } + }, ) } @@ -427,7 +427,7 @@ class SentryHandlerTest { assertTrue( it.packageSet.any { pkg -> "maven:io.sentry:sentry-jul" == pkg.name && BuildConfig.VERSION_NAME == pkg.version - } + }, ) assertTrue(it.integrationSet.contains("Jul")) } @@ -459,7 +459,7 @@ class SentryHandlerTest { .send( checkLogs { logs -> assertEquals("this should be captured as a log", logs.items.first().body) - } + }, ) } @@ -527,10 +527,10 @@ class SentryHandlerTest { } fixture.handler.publish( - LogRecord(Level.INFO, null).apply { this.resourceBundle = resourceBundle } + LogRecord(Level.INFO, null).apply { this.resourceBundle = resourceBundle }, ) fixture.handler.publish( - LogRecord(Level.SEVERE, null).apply { this.resourceBundle = resourceBundle } + LogRecord(Level.SEVERE, null).apply { this.resourceBundle = resourceBundle }, ) Sentry.flush(10) @@ -558,7 +558,7 @@ class SentryHandlerTest { checkLogs { event -> assertEquals(SentryLogLevel.TRACE, event.items.first().level) assertEquals("auto.log.jul", event.items.first().attributes?.get("sentry.origin")?.value) - } + }, ) } @@ -630,7 +630,7 @@ class SentryHandlerTest { val log = logs.items.first() assertEquals("testing message without parameters", log.body) assertNull(log.attributes?.get("sentry.message.template")) - } + }, ) } @@ -648,7 +648,7 @@ class SentryHandlerTest { assertEquals("testing message param", log.body) assertEquals("testing message {0}", log.attributes?.get("sentry.message.template")?.value) assertEquals("param", log.attributes?.get("sentry.message.parameter.0")?.value) - } + }, ) } @@ -666,7 +666,7 @@ class SentryHandlerTest { assertEquals("testing message param", log.body) assertEquals("testing message %s", log.attributes?.get("sentry.message.template")?.value) assertEquals("param", log.attributes?.get("sentry.message.parameter.0")?.value) - } + }, ) } @@ -688,7 +688,7 @@ class SentryHandlerTest { ) assertEquals(1, log.attributes?.get("sentry.message.parameter.0")?.value) assertNull(log.attributes?.get("sentry.message.parameter.1")) - } + }, ) } @@ -710,7 +710,7 @@ class SentryHandlerTest { val attributes = log.attributes!! assertEquals("someValue", attributes["mdc.someTag"]?.value) assertNull(attributes["otherTag"]) - } + }, ) } } diff --git a/sentry-kotlin-extensions/src/main/java/io/sentry/kotlin/SentryCoroutineExceptionHandler.kt b/sentry-kotlin-extensions/src/main/java/io/sentry/kotlin/SentryCoroutineExceptionHandler.kt index 13145a8345a..e519d73bbff 100644 --- a/sentry-kotlin-extensions/src/main/java/io/sentry/kotlin/SentryCoroutineExceptionHandler.kt +++ b/sentry-kotlin-extensions/src/main/java/io/sentry/kotlin/SentryCoroutineExceptionHandler.kt @@ -17,7 +17,7 @@ import org.jetbrains.annotations.ApiStatus */ @ApiStatus.Experimental public open class SentryCoroutineExceptionHandler( - private val scopes: IScopes = ScopesAdapter.getInstance() + private val scopes: IScopes = ScopesAdapter.getInstance(), ) : AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler { override fun handleException(context: CoroutineContext, exception: Throwable) { val mechanism = diff --git a/sentry-kotlin-extensions/src/test/java/io/sentry/kotlin/SentryContextTest.kt b/sentry-kotlin-extensions/src/test/java/io/sentry/kotlin/SentryContextTest.kt index 55fa4f58d6a..457773550b0 100644 --- a/sentry-kotlin-extensions/src/test/java/io/sentry/kotlin/SentryContextTest.kt +++ b/sentry-kotlin-extensions/src/test/java/io/sentry/kotlin/SentryContextTest.kt @@ -87,10 +87,10 @@ class SentryContextTest { assertEquals("c1value", getTag("c1")) assertNull(getTag("c2")) launch { - Sentry.setTag("c2", "c2value") - assertEquals("c2value", getTag("c2")) - assertEquals("c1value", getTag("c1")) - } + Sentry.setTag("c2", "c2value") + assertEquals("c2value", getTag("c2")) + assertEquals("c1value", getTag("c1")) + } .join() } c1.join() @@ -182,8 +182,8 @@ class SentryContextTest { SentryContext( Sentry.getCurrentScopes().forkedScopes("test").also { it.setTag("cloned", "clonedValue") - } - ) + }, + ), ) { Sentry.setTag("c2", "c2value") assertEquals("c2value", getTag("c2")) @@ -222,8 +222,8 @@ class SentryContextTest { it.configureScope(ScopeType.CURRENT) { scope -> scope.setTag("cloned", "clonedValue") } - } - ) + }, + ), ) { Sentry.configureScope(ScopeType.CURRENT) { scope -> scope.setTag("c2", "c2value") } assertEquals("c2value", getTag("c2", ScopeType.CURRENT)) @@ -247,7 +247,7 @@ class SentryContextTest { fun `mergeForChild returns copy of initial context if Key not present`() { val initialContextElement = SentryContext( - Sentry.getCurrentScopes().forkedScopes("test").also { it.setTag("cloned", "clonedValue") } + Sentry.getCurrentScopes().forkedScopes("test").also { it.setTag("cloned", "clonedValue") }, ) val mergedContextElement = initialContextElement.mergeForChild(CoroutineName("test")) @@ -259,7 +259,7 @@ class SentryContextTest { fun `mergeForChild returns passed context`() { val initialContextElement = SentryContext( - Sentry.getCurrentScopes().forkedScopes("test").also { it.setTag("cloned", "clonedValue") } + Sentry.getCurrentScopes().forkedScopes("test").also { it.setTag("cloned", "clonedValue") }, ) val mergedContextElement = SentryContext().mergeForChild(initialContextElement) diff --git a/sentry-kotlin-extensions/src/test/java/io/sentry/kotlin/SentryCoroutineExceptionHandlerTest.kt b/sentry-kotlin-extensions/src/test/java/io/sentry/kotlin/SentryCoroutineExceptionHandlerTest.kt index 53462602a25..9eccaf9f244 100644 --- a/sentry-kotlin-extensions/src/test/java/io/sentry/kotlin/SentryCoroutineExceptionHandlerTest.kt +++ b/sentry-kotlin-extensions/src/test/java/io/sentry/kotlin/SentryCoroutineExceptionHandlerTest.kt @@ -56,7 +56,7 @@ class SentryCoroutineExceptionHandlerTest { assertTrue { exception.toString().equals(it.throwable.toString()) } // stack trace will differ - } + }, ) } } diff --git a/sentry-ktor-client/build.gradle.kts b/sentry-ktor-client/build.gradle.kts index 6f26d029df8..b18559621b9 100644 --- a/sentry-ktor-client/build.gradle.kts +++ b/sentry-ktor-client/build.gradle.kts @@ -47,6 +47,31 @@ dependencies { testImplementation(libs.okhttp.mockwebserver) } +testing { + suites { + register("testKtor300") { + useJUnit() + dependencies { + implementation(enforcedPlatform("io.ktor:ktor-bom:3.0.0")) + } + sources { + java.setSrcDirs(sourceSets.test.get().java.srcDirs) + resources.setSrcDirs(sourceSets.test.get().resources.srcDirs) + } + } + } +} + +configurations.named("testKtor300Implementation") { + extendsFrom(configurations.testImplementation.get()) +} + +kotlin.target.compilations.named("testKtor300") { + associateWith(kotlin.target.compilations.getByName("main")) +} + +tasks.check { dependsOn(testing.suites.named("testKtor300")) } + buildConfig { useJavaOutput() packageName("io.sentry.ktorClient") diff --git a/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientPlugin.kt b/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientPlugin.kt index ef645364fbd..4552bd02956 100644 --- a/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientPlugin.kt +++ b/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientPlugin.kt @@ -7,6 +7,7 @@ import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.util.* import io.ktor.util.pipeline.* +import io.ktor.util.reflect.TypeInfo import io.sentry.BaggageHeader import io.sentry.BuildConfig import io.sentry.DataCategory @@ -98,9 +99,13 @@ public val SentryKtorClientPlugin: ClientPlugin = // Attributes // Request start time for breadcrumbs - val requestStartTimestampKey = AttributeKey("SentryRequestStartTimestamp") + val requestStartTimestampKey = + AttributeKey( + "SentryRequestStartTimestamp", + TypeInfo(SentryDate::class, null), + ) // Span associated with the request - val requestSpanKey = AttributeKey("SentryRequestSpan") + val requestSpanKey = AttributeKey("SentryRequestSpan", TypeInfo(ISpan::class, null)) onRequest { request, _ -> val effectiveScopes = if (forceScopes) scopes else Sentry.getCurrentScopes() @@ -242,7 +247,7 @@ public open class SentryKtorClientPluginContextHook(protected val scopes: IScope client.requestPipeline.intercept(phase) { val scopes = this@SentryKtorClientPluginContextHook.scopes.forkedCurrentScope( - SENTRY_KTOR_CLIENT_PLUGIN_KEY + SENTRY_KTOR_CLIENT_PLUGIN_KEY, ) withContext(SentryContext(scopes)) { proceed() } } diff --git a/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientUtils.kt b/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientUtils.kt index 6632efce93f..4ab9310d6b1 100644 --- a/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientUtils.kt +++ b/sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientUtils.kt @@ -19,6 +19,7 @@ import io.sentry.protocol.Mechanism import io.sentry.util.CookieUtils import io.sentry.util.HttpUtils import io.sentry.util.UrlUtils +import java.util.concurrent.TimeUnit internal object SentryKtorClientUtils { internal suspend fun captureClientError( @@ -126,16 +127,17 @@ internal object SentryKtorClientUtils { SpanDataConvention.HTTP_RESPONSE_CONTENT_LENGTH_KEY, response.contentLength(), ) + // Session Replay reads these as epoch milliseconds for its rrweb network spans. if (startTimestamp != null) { breadcrumb.setData( SpanDataConvention.HTTP_START_TIMESTAMP, - startTimestamp.nanoTimestamp() / 1000L, + TimeUnit.NANOSECONDS.toMillis(startTimestamp.nanoTimestamp()), ) } if (endTimestamp != null) { breadcrumb.setData( SpanDataConvention.HTTP_END_TIMESTAMP, - endTimestamp.nanoTimestamp() / 1000L, + TimeUnit.NANOSECONDS.toMillis(endTimestamp.nanoTimestamp()), ) } diff --git a/sentry-ktor-client/src/test/java/io/sentry/ktorClient/SentryKtorClientPluginTest.kt b/sentry-ktor-client/src/test/java/io/sentry/ktorClient/SentryKtorClientPluginTest.kt index 17c528ce0fc..c508bc3a43a 100644 --- a/sentry-ktor-client/src/test/java/io/sentry/ktorClient/SentryKtorClientPluginTest.kt +++ b/sentry-ktor-client/src/test/java/io/sentry/ktorClient/SentryKtorClientPluginTest.kt @@ -23,8 +23,10 @@ import io.sentry.Scope import io.sentry.ScopeCallback import io.sentry.ScopeType import io.sentry.Sentry +import io.sentry.SentryDateProvider import io.sentry.SentryEvent import io.sentry.SentryLevel +import io.sentry.SentryNanotimeDate import io.sentry.SentryOptions import io.sentry.SentryTraceHeader import io.sentry.SentryTracer @@ -78,7 +80,7 @@ class SentryKtorClientPluginTest { failedRequestTargets: List = listOf(".*"), failedRequestStatusCodes: List = listOf( - HttpStatusCodeRange(HttpStatusCodeRange.DEFAULT_MIN, HttpStatusCodeRange.DEFAULT_MAX) + HttpStatusCodeRange(HttpStatusCodeRange.DEFAULT_MIN, HttpStatusCodeRange.DEFAULT_MAX), ), sendDefaultPii: Boolean = false, optionsConfiguration: Sentry.OptionsConfiguration? = null, @@ -118,7 +120,7 @@ class SentryKtorClientPluginTest { .addHeader("myResponseHeader", "myValue") .addHeader("Set-Cookie", "theme=dark; Path=/") .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) return HttpClient(httpClientEngine) { @@ -155,6 +157,27 @@ class SentryKtorClientPluginTest { ) } + @Test + fun `breadcrumb timestamps are epoch milliseconds`(): Unit = runBlocking { + val epochMillis = 1_700_000_000_123L + val sut = + fixture.getSut( + optionsConfiguration = { options -> + options.dateProvider = SentryDateProvider { SentryNanotimeDate(epochMillis, 0) } + }, + ) + sut.get(fixture.server.url("/hello").toString()) + + verify(fixture.scopes) + .addBreadcrumb( + check { + assertThat(it.getData(SpanDataConvention.HTTP_START_TIMESTAMP)).isEqualTo(epochMillis) + assertThat(it.getData(SpanDataConvention.HTTP_END_TIMESTAMP)).isEqualTo(epochMillis) + }, + anyOrNull(), + ) + } + @Test fun `adds breadcrumb when http call fails`(): Unit = runBlocking { val sut = fixture.getSut(httpStatusCode = 500, responseBody = "error") @@ -457,7 +480,7 @@ class SentryKtorClientPluginTest { beforeSpan = { span, _ -> span.spanContext.sampled = false error("callback failed") - } + }, ) fixture.sentryTracer.spanContext.sampled = sampled fixture.options.onDiscard = onDiscard @@ -481,7 +504,7 @@ class SentryKtorClientPluginTest { beforeSpan = { span, _ -> span.description = "partially modified" throw failure - } + }, ) fixture.options.isDebug = true fixture.options.setLogger(logger) @@ -536,7 +559,7 @@ class SentryKtorClientPluginTest { beforeSpan = { span, _ -> span.description = "changed" span - } + }, ) sut.use { sut.get(fixture.server.url("/hello").toString()) } val span = fixture.sentryTracer.children.single() @@ -579,7 +602,7 @@ class SentryKtorClientPluginTest { optionsConfiguration = Sentry.OptionsConfiguration { it.dataCollection.urlQueryParams = KeyValueCollectionBehavior.denyList("token") - } + }, ) sut.get(fixture.server.url("/hello?name=value&token=secret").toString()) @@ -595,7 +618,7 @@ class SentryKtorClientPluginTest { optionsConfiguration = Sentry.OptionsConfiguration { it.dataCollection.urlQueryParams = KeyValueCollectionBehavior.off() - } + }, ) sut.get(fixture.server.url("/hello?name=value").toString()) @@ -733,8 +756,8 @@ class SentryKtorClientPluginTest { "thirdPartyBaggage=someValue," + "secondThirdPartyBaggage=secondValue; " + "property;propertyKey=propertyValue," + - "anotherThirdPartyBaggage=anotherValue" - ) + "anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=name")) diff --git a/sentry-log4j2/build.gradle.kts b/sentry-log4j2/build.gradle.kts index 009455c9c1e..7ffd767e953 100644 --- a/sentry-log4j2/build.gradle.kts +++ b/sentry-log4j2/build.gradle.kts @@ -65,7 +65,7 @@ tasks.named("compileJava") { listOf( "-Alog4j.graalvm.groupId=${project.group}", "-Alog4j.graalvm.artifactId=${project.name}", - ) + ), ) } diff --git a/sentry-log4j2/src/test/kotlin/io/sentry/log4j2/SentryAppenderTest.kt b/sentry-log4j2/src/test/kotlin/io/sentry/log4j2/SentryAppenderTest.kt index 21c0a8b90a4..73f6711dcee 100644 --- a/sentry-log4j2/src/test/kotlin/io/sentry/log4j2/SentryAppenderTest.kt +++ b/sentry-log4j2/src/test/kotlin/io/sentry/log4j2/SentryAppenderTest.kt @@ -109,7 +109,7 @@ class SentryAppenderTest { ILoggerBatchProcessorFactory { options, client -> LoggerBatchProcessor(options, client, ImmediateExecutorService()) } - } + }, ) loggerContext.start() @@ -281,7 +281,7 @@ class SentryAppenderTest { .send( checkLogs { logs -> assertEquals("this should be captured as a log", logs.items.first().body) - } + }, ) } @@ -352,8 +352,8 @@ class SentryAppenderTest { null, null, null, - ) - ) + ), + ), ) pluginDefaultAppender.append(event) @@ -381,8 +381,8 @@ class SentryAppenderTest { null, null, null, - ) - ) + ), + ), ) doNothing().whenever(appender).captureLog(event) @@ -406,7 +406,7 @@ class SentryAppenderTest { "auto.log.log4j2", event.items.first().attributes?.get("sentry.origin")?.value, ) - } + }, ) } @@ -579,7 +579,7 @@ class SentryAppenderTest { it.packageSet.any { pkg -> "maven:io.sentry:sentry-log4j2" == pkg.name && BuildConfig.VERSION_NAME == pkg.version - } + }, ) assertTrue(it.integrationSet.contains("Log4j")) } @@ -695,7 +695,7 @@ class SentryAppenderTest { val log = logs.items.first() assertEquals("testing message without parameters", log.body) assertNull(log.attributes?.get("sentry.message.template")) - } + }, ) } @@ -713,7 +713,7 @@ class SentryAppenderTest { assertEquals("testing message param", log.body) assertEquals("testing message {}", log.attributes?.get("sentry.message.template")?.value) assertEquals("param", log.attributes?.get("sentry.message.parameter.0")?.value) - } + }, ) } @@ -736,7 +736,7 @@ class SentryAppenderTest { assertEquals("param1", log.attributes?.get("sentry.message.parameter.0")?.value) assertEquals("param2", log.attributes?.get("sentry.message.parameter.1")?.value) assertNull(log.attributes?.get("sentry.message.parameter.2")) - } + }, ) } @@ -758,7 +758,7 @@ class SentryAppenderTest { val attributes = log.attributes!! assertEquals("someValue", attributes["mdc.someTag"]?.value) assertNull(attributes["otherTag"]) - } + }, ) } } diff --git a/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt b/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt index b3379940195..a5ecb2b30cd 100644 --- a/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt +++ b/sentry-logback/src/test/kotlin/io/sentry/logback/SentryAppenderTest.kt @@ -434,7 +434,7 @@ class SentryAppenderTest { .send( checkLogs { logs -> assertEquals("this should be captured as a log", logs.items.first().body) - } + }, ) } @@ -533,7 +533,7 @@ class SentryAppenderTest { assertEquals("Testing {} level", attributes["sentry.message.template"]?.value) assertEquals("TRACE", attributes["sentry.message.parameter.0"]?.value) assertEquals("auto.log.logback", attributes["sentry.origin"]?.value) - } + }, ) } @@ -554,7 +554,7 @@ class SentryAppenderTest { val attributes = log.attributes!! assertNull(attributes["sentry.message.template"]) assertNull(attributes["sentry.message.parameter.0"]) - } + }, ) } @@ -580,7 +580,7 @@ class SentryAppenderTest { val attributes = log.attributes!! assertEquals("Testing {} level", attributes["sentry.message.template"]?.value) assertEquals("TRACE", attributes["sentry.message.parameter.0"]?.value) - } + }, ) } @@ -607,7 +607,7 @@ class SentryAppenderTest { val attributes = log.attributes!! assertEquals("Testing {} level", attributes["sentry.message.template"]?.value) assertEquals("TRACE", attributes["sentry.message.parameter.0"]?.value) - } + }, ) } @@ -723,7 +723,7 @@ class SentryAppenderTest { it.packageSet.any { pkg -> "maven:io.sentry:sentry-logback" == pkg.name && BuildConfig.VERSION_NAME == pkg.version - } + }, ) assertTrue(it.integrationSet.contains("Logback")) } @@ -787,7 +787,7 @@ class SentryAppenderTest { fixture = Fixture() fixture.logger.debug( - "this should not be a breadcrumb as the level is lower than the minimum INFO" + "this should not be a breadcrumb as the level is lower than the minimum INFO", ) fixture.logger.info("this should be a breadcrumb") fixture.logger.warn("this should not be sent as the event but be a breadcrumb") @@ -828,7 +828,7 @@ class SentryAppenderTest { fixture = Fixture(dsn = "DSN_IS_UNDEFINED", minimumEventLevel = Level.DEBUG) assertTrue( - fixture.loggerContext.statusManager.copyOfStatusList.none { it.level == Status.WARN } + fixture.loggerContext.statusManager.copyOfStatusList.none { it.level == Status.WARN }, ) } @@ -875,7 +875,7 @@ class SentryAppenderTest { val log = logs.items.first() assertEquals("testing message without parameters", log.body) assertNull(log.attributes?.get("sentry.message.template")) - } + }, ) } @@ -893,7 +893,7 @@ class SentryAppenderTest { assertEquals("testing message param", log.body) assertEquals("testing message {}", log.attributes?.get("sentry.message.template")?.value) assertEquals("param", log.attributes?.get("sentry.message.parameter.0")?.value) - } + }, ) } @@ -916,7 +916,7 @@ class SentryAppenderTest { assertEquals("param1", log.attributes?.get("sentry.message.parameter.0")?.value) assertEquals("param2", log.attributes?.get("sentry.message.parameter.1")?.value) assertNull(log.attributes?.get("sentry.message.parameter.2")) - } + }, ) } @@ -942,7 +942,7 @@ class SentryAppenderTest { assertEquals("encoded testing message param", log.body) assertNull(log.attributes?.get("sentry.message.template")) assertNull(log.attributes?.get("sentry.message.parameter.0")) - } + }, ) } @@ -969,7 +969,7 @@ class SentryAppenderTest { assertThat(log.attributes?.get("sentry.message.template")?.value) .isEqualTo("testing message {}") assertThat(log.attributes?.get("sentry.message.parameter.0")?.value).isEqualTo("param") - } + }, ) } @@ -995,7 +995,7 @@ class SentryAppenderTest { assertEquals("encoded testing message param", log.body) assertEquals("testing message {}", log.attributes?.get("sentry.message.template")?.value) assertEquals("param", log.attributes?.get("sentry.message.parameter.0")?.value) - } + }, ) } @@ -1017,7 +1017,7 @@ class SentryAppenderTest { val attributes = log.attributes!! assertEquals("someValue", attributes["mdc.someTag"]?.value) assertNull(attributes["otherTag"]) - } + }, ) } } diff --git a/sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpEventListener.kt b/sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpEventListener.kt index 12836a732b0..c1cbc3d2d8e 100644 --- a/sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpEventListener.kt +++ b/sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpEventListener.kt @@ -96,13 +96,13 @@ public open class SentryOkHttpEventListener( public constructor() : this(ScopesAdapter.getInstance(), originalEventListenerCreator = null) public constructor( - originalEventListener: EventListener + originalEventListener: EventListener, ) : this(ScopesAdapter.getInstance(), originalEventListenerCreator = { originalEventListener }) { fixedOriginalEventListener = originalEventListener } public constructor( - originalEventListenerFactory: Factory + originalEventListenerFactory: Factory, ) : this( ScopesAdapter.getInstance(), originalEventListenerCreator = { originalEventListenerFactory.create(it) }, diff --git a/sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpInterceptor.kt b/sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpInterceptor.kt index 7341cc57a84..5f346aab178 100644 --- a/sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpInterceptor.kt +++ b/sentry-okhttp/src/main/java/io/sentry/okhttp/SentryOkHttpInterceptor.kt @@ -177,7 +177,7 @@ public open class SentryOkHttpInterceptor( }, scopes.options.sessionReplay.networkRequestHeaders, { req: Request -> req.headers.toMap() }, - ) + ), ) request = requestBuilder.build() @@ -381,7 +381,7 @@ public open class SentryOkHttpInterceptor( e, ) } - } + }, ) .build() } @@ -404,7 +404,7 @@ public open class SentryOkHttpInterceptor( { body() }, scopes.options.sessionReplay.networkResponseHeaders, { resp: Response -> resp.headers.toMap() }, - ) + ), ) } diff --git a/sentry-okhttp/src/test/java/io/sentry/okhttp/CapturedResponseBodyTest.kt b/sentry-okhttp/src/test/java/io/sentry/okhttp/CapturedResponseBodyTest.kt index 0a5829d9c5f..719eb4b0e17 100644 --- a/sentry-okhttp/src/test/java/io/sentry/okhttp/CapturedResponseBodyTest.kt +++ b/sentry-okhttp/src/test/java/io/sentry/okhttp/CapturedResponseBodyTest.kt @@ -71,12 +71,16 @@ class CapturedResponseBodyTest { private val closed = CountDownLatch(1) private var sent = false + /** Counts down once a read is blocked waiting for [close]. */ + val parked = CountDownLatch(1) + override fun read(sink: Buffer, byteCount: Long): Long { if (!sent) { sent = true sink.write(chunk) return chunk.size.toLong() } + parked.countDown() closed.await(10, TimeUnit.SECONDS) return -1L } @@ -260,19 +264,19 @@ class CapturedResponseBodyTest { val chunk = "data: event-0\n\n".toByteArray() val source = ParkingSource(chunk) val (wrapper, captured) = capture(source, 1024) - val chunkRead = CountDownLatch(1) val readDone = CountDownLatch(1) val reader = Thread { val bodySource = wrapper.source() bodySource.readByteArray(chunk.size.toLong()) - chunkRead.countDown() bodySource.readByteArray() readDone.countDown() } reader.isDaemon = true reader.start() - assertTrue(chunkRead.await(10, TimeUnit.SECONDS), "the reader must have received the chunk") + // Wait until the reader is blocked inside read(). Closing before that would make the next read + // throw "closed" on the reader thread instead of returning end of stream. + assertTrue(source.parked.await(10, TimeUnit.SECONDS), "the reader must be blocked in read()") wrapper.close() assertTrue( diff --git a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventListenerTest.kt b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventListenerTest.kt index 7f9915f13b1..8ef0443381c 100644 --- a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventListenerTest.kt +++ b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventListenerTest.kt @@ -76,7 +76,7 @@ class SentryOkHttpEventListenerTest { .setBody("responseBody") .addHeader("myResponseHeader", "myValue") .setSocketPolicy(SocketPolicy.KEEP_OPEN) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) val builder = OkHttpClient.Builder() diff --git a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventTest.kt b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventTest.kt index 89d5078c6fd..3017ad3abd7 100644 --- a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventTest.kt +++ b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpEventTest.kt @@ -244,7 +244,7 @@ class SentryOkHttpEventTest { val sut = fixture.getSut() sut.setRequest( - Request.Builder().post("".toRequestBody()).url("https://foo.bar/updated").build() + Request.Builder().post("".toRequestBody()).url("https://foo.bar/updated").build(), ) sut.finish() diff --git a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpInterceptorTest.kt b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpInterceptorTest.kt index baa37a7716a..8e4d492692a 100644 --- a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpInterceptorTest.kt +++ b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpInterceptorTest.kt @@ -86,7 +86,7 @@ class SentryOkHttpInterceptorTest { failedRequestTargets: List = listOf(".*"), failedRequestStatusCodes: List = listOf( - HttpStatusCodeRange(HttpStatusCodeRange.DEFAULT_MIN, HttpStatusCodeRange.DEFAULT_MAX) + HttpStatusCodeRange(HttpStatusCodeRange.DEFAULT_MIN, HttpStatusCodeRange.DEFAULT_MAX), ), sendDefaultPii: Boolean = false, eventListener: EventListener? = null, @@ -120,7 +120,7 @@ class SentryOkHttpInterceptorTest { .setBody(responseBody) .addHeader("myResponseHeader", "myValue") .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) val interceptor = @@ -184,7 +184,7 @@ class SentryOkHttpInterceptorTest { } private fun postRequest( - body: RequestBody = "request-body".toRequestBody("text/plain".toMediaType()) + body: RequestBody = "request-body".toRequestBody("text/plain".toMediaType()), ): Request = Request.Builder().post(body).url(fixture.server.url("/hello")).build() @SuppressWarnings("MaxLineLength") @@ -283,8 +283,8 @@ class SentryOkHttpInterceptorTest { "thirdPartyBaggage=someValue," + "secondThirdPartyBaggage=secondValue; " + "property;propertyKey=propertyValue," + - "anotherThirdPartyBaggage=anotherValue" - ) + "anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=name")) @@ -364,7 +364,7 @@ class SentryOkHttpInterceptorTest { it.dataCollection.httpHeaders.request = KeyValueCollectionBehavior.off() it.dataCollection.httpHeaders.response = KeyValueCollectionBehavior.off() it.sessionReplay.setNetworkDetailAllowUrls(listOf(".*")) - } + }, ) val request = postRequest().newBuilder().addHeader("Accept", "application/json").build() @@ -377,7 +377,7 @@ class SentryOkHttpInterceptorTest { hint.firstValue.getAs( TypeCheckHint.SENTRY_REPLAY_NETWORK_DETAILS, NetworkRequestData::class.java, - ) + ), ) assertEquals("request-body", networkDetails.request?.body?.body) assertEquals("application/json", networkDetails.request?.headers?.get("Accept")) @@ -400,7 +400,7 @@ class SentryOkHttpInterceptorTest { hint.firstValue.getAs( TypeCheckHint.SENTRY_REPLAY_NETWORK_DETAILS, NetworkRequestData::class.java, - ) + ), ) .isNull() } @@ -449,7 +449,7 @@ class SentryOkHttpInterceptorTest { beforeSpan = { span, _, _ -> span.description = "overwritten description" span - } + }, ) val request = getRequest() sut.newCall(request).execute() @@ -468,7 +468,7 @@ class SentryOkHttpInterceptorTest { assertEquals(request.method, request.method) assertNotNull(response) { assertEquals(201, it.code) } span - } + }, ) val request = getRequest() sut.newCall(request).execute() @@ -497,7 +497,7 @@ class SentryOkHttpInterceptorTest { beforeSpan = { span, _, _ -> span.spanContext.sampled = false error("callback failed") - } + }, ) fixture.sentryTracer.spanContext.sampled = sampled fixture.options.onDiscard = onDiscard @@ -521,7 +521,7 @@ class SentryOkHttpInterceptorTest { beforeSpan = { span, _, _ -> span.description = "partially modified" throw failure - } + }, ) fixture.options.isDebug = true fixture.options.setLogger(logger) @@ -578,7 +578,7 @@ class SentryOkHttpInterceptorTest { .getSut( beforeSpan = { _, _, _ -> throw IllegalStateException("callback failed") - } + }, ) .newBuilder() .addInterceptor { throw requestFailure } @@ -850,9 +850,9 @@ class SentryOkHttpInterceptorTest { .request() .newBuilder() .url(chain.request().url.newBuilder().addPathSegment("v1").build()) - .build() + .build(), ) - } + }, ), ) @@ -886,7 +886,7 @@ class SentryOkHttpInterceptorTest { fun `adds W3C traceparent header when propagateTraceparent is enabled`() { val client = fixture.getSut( - optionsConfiguration = Sentry.OptionsConfiguration { it.isPropagateTraceparent = true } + optionsConfiguration = Sentry.OptionsConfiguration { it.isPropagateTraceparent = true }, ) fixture.server.enqueue(MockResponse().setResponseCode(200)) @@ -903,7 +903,7 @@ class SentryOkHttpInterceptorTest { fun `does not add W3C traceparent header when propagateTraceparent is disabled`() { val client = fixture.getSut( - optionsConfiguration = Sentry.OptionsConfiguration { it.isPropagateTraceparent = false } + optionsConfiguration = Sentry.OptionsConfiguration { it.isPropagateTraceparent = false }, ) fixture.server.enqueue(MockResponse().setResponseCode(200)) diff --git a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpInterceptorUnknownContentLengthTest.kt b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpInterceptorUnknownContentLengthTest.kt index b6257bfc50b..5fda8edfaaf 100644 --- a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpInterceptorUnknownContentLengthTest.kt +++ b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpInterceptorUnknownContentLengthTest.kt @@ -78,7 +78,7 @@ class SentryOkHttpInterceptorUnknownContentLengthTest { hint.firstValue.getAs( TypeCheckHint.SENTRY_REPLAY_NETWORK_DETAILS, NetworkRequestData::class.java, - ) + ), ) } @@ -273,7 +273,7 @@ class SentryOkHttpInterceptorUnknownContentLengthTest { thread.set(Thread.currentThread().name) done.countDown() } - } + }, ) assertTrue(done.await(10, TimeUnit.SECONDS), "the callback must be reached") @@ -350,7 +350,7 @@ class SentryOkHttpInterceptorUnknownContentLengthTest { MockResponse() .setBody(payload) .removeHeader("Content-Length") - .setHeader("Content-Type", "text/event-stream") + .setHeader("Content-Type", "text/event-stream"), ) sut = sut.newBuilder().protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE)).build() @@ -381,7 +381,7 @@ class SentryOkHttpInterceptorUnknownContentLengthTest { MockResponse() .setBody(gzipped) .setHeader("Content-Encoding", "gzip") - .setHeader("Content-Type", "application/json") + .setHeader("Content-Type", "application/json"), ) val response = sut.newCall(requestTo(server.url("/json").toString())).execute() diff --git a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpUtilsTest.kt b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpUtilsTest.kt index a11398fed57..b89a1f5bf5c 100644 --- a/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpUtilsTest.kt +++ b/sentry-okhttp/src/test/java/io/sentry/okhttp/SentryOkHttpUtilsTest.kt @@ -58,7 +58,7 @@ class SentryOkHttpUtilsTest { .addHeader("myResponseHeader", "myValue") .addHeader("Set-Cookie", "theme=dark; Path=/") .setSocketPolicy(socketPolicy) - .setResponseCode(httpStatusCode) + .setResponseCode(httpStatusCode), ) return OkHttpClient.Builder().build() } diff --git a/sentry-openfeign/src/test/kotlin/io/sentry/openfeign/SentryFeignClientTest.kt b/sentry-openfeign/src/test/kotlin/io/sentry/openfeign/SentryFeignClientTest.kt index 398640989ce..cbeaebb2eca 100644 --- a/sentry-openfeign/src/test/kotlin/io/sentry/openfeign/SentryFeignClientTest.kt +++ b/sentry-openfeign/src/test/kotlin/io/sentry/openfeign/SentryFeignClientTest.kt @@ -119,8 +119,8 @@ class SentryFeignClientTest { listOf( "thirdPartyBaggage=someValue", "secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", - ) - ) + ), + ), ) val recorderRequest = @@ -132,8 +132,8 @@ class SentryFeignClientTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=name")) @@ -304,7 +304,7 @@ class SentryFeignClientTest { beforeSpan = { span, _, _ -> span.spanContext.sampled = false throw IllegalStateException("callback failed") - } + }, ) fixture.sentryTracer.spanContext.sampled = sampled fixture.sentryOptions.onDiscard = onDiscard @@ -330,7 +330,7 @@ class SentryFeignClientTest { beforeSpan = { span, _, _ -> span.description = "partially modified" throw failure - } + }, ) assertThat(sut.getOk()).isEqualTo("success") diff --git a/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts b/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts index b9ee2400d49..311bae4ce8c 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts +++ b/sentry-opentelemetry/sentry-opentelemetry-agent/build.gradle.kts @@ -107,7 +107,9 @@ fun isolateClasses(jars: Iterable): CopySpec = copySpec { } } -// Don't publish non-shadowed jar (shadowJar is in shadowRuntimeElements) +// Only the agent, the shadow jar in shadowRuntimeElements, is published. The plain jar in +// runtimeElements holds just AgentMarker. A project dependency on this module resolves to it, so +// the Spring Boot modules' unit tests get AgentMarker on their classpath without the agent. with(components["java"] as AdhocComponentWithVariants) { configurations.forEach { withVariantsFromConfiguration(configurations["apiElements"]) { skip() } @@ -215,7 +217,7 @@ tasks { test { jvmArgumentProviders.add( - objects.newInstance().apply { agentJar.from(shadowJar) } + objects.newInstance().apply { agentJar.from(shadowJar) }, ) } } diff --git a/sentry-opentelemetry/sentry-opentelemetry-agentcustomization/src/main/java/io/sentry/opentelemetry/SentryAutoConfigurationCustomizerProvider.java b/sentry-opentelemetry/sentry-opentelemetry-agentcustomization/src/main/java/io/sentry/opentelemetry/SentryAutoConfigurationCustomizerProvider.java index e11ae4c72b3..42277f53c26 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-agentcustomization/src/main/java/io/sentry/opentelemetry/SentryAutoConfigurationCustomizerProvider.java +++ b/sentry-opentelemetry/sentry-opentelemetry-agentcustomization/src/main/java/io/sentry/opentelemetry/SentryAutoConfigurationCustomizerProvider.java @@ -35,15 +35,14 @@ public void customize(AutoConfigurationCustomizer autoConfiguration) { ManifestVersionReader.getInstance().readOpenTelemetryVersion(); if (isSentryAutoInitEnabled()) { - Sentry.init( - options -> { - options.setEnableExternalConfiguration(true); - options.setInitPriority(InitPriority.HIGH); - final @Nullable SdkVersion sdkVersion = createSdkVersion(options, versionInfoHolder); - if (sdkVersion != null) { - options.setSdkVersion(sdkVersion); - } - }); + Sentry.init(options -> { + options.setEnableExternalConfiguration(true); + options.setInitPriority(InitPriority.HIGH); + final @Nullable SdkVersion sdkVersion = createSdkVersion(options, versionInfoHolder); + if (sdkVersion != null) { + options.setSdkVersion(sdkVersion); + } + }); } autoConfiguration diff --git a/sentry-opentelemetry/sentry-opentelemetry-agentless/src/test/kotlin/io/sentry/opentelemetry/agentless/AgentlessEndToEndTest.kt b/sentry-opentelemetry/sentry-opentelemetry-agentless/src/test/kotlin/io/sentry/opentelemetry/agentless/AgentlessEndToEndTest.kt index 6d519ed4174..e4ac7595757 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-agentless/src/test/kotlin/io/sentry/opentelemetry/agentless/AgentlessEndToEndTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-agentless/src/test/kotlin/io/sentry/opentelemetry/agentless/AgentlessEndToEndTest.kt @@ -75,7 +75,7 @@ class AgentlessEndToEndTest { addBreadcrumb(Breadcrumb("Processed by the event processor")) } } - } + }, ) } Sentry.withScope { @@ -95,11 +95,11 @@ class AgentlessEndToEndTest { message = Message().apply { message = "Detailed event" } fingerprints = listOf("NewClientDebug") level = SentryLevel.DEBUG - } + }, ) repeat(10) { i -> Sentry.captureEvent( - SentryEvent().apply { message = Message().apply { message = "event $i" } } + SentryEvent().apply { message = Message().apply { message = "event $i" } }, ) } val transaction = Sentry.startTransaction("transaction name", "op") diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OpenTelemetryAttributesExtractor.java b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OpenTelemetryAttributesExtractor.java index cf0fb06c11a..5ae9de98cc6 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OpenTelemetryAttributesExtractor.java +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OpenTelemetryAttributesExtractor.java @@ -79,30 +79,27 @@ private static Map collectHeaders( final @NotNull Attributes attributes, final @NotNull SentryOptions options) { Map headers = new HashMap<>(); - attributes.forEach( - (key, value) -> { - final @NotNull String attributeKeyAsString = key.getKey(); - if (attributeKeyAsString.startsWith(HTTP_REQUEST_HEADER_PREFIX)) { - final @NotNull String headerName = - StringUtils.removePrefix(attributeKeyAsString, HTTP_REQUEST_HEADER_PREFIX); - if (options.isSendDefaultPii() || !HttpUtils.containsSensitiveHeader(headerName)) { - if (value instanceof List) { - try { - final @NotNull List headerValues = (List) value; - headers.put( - headerName, - toString( - CookieUtils.filterOutSecurityCookiesFromHeader( - headerValues, headerName, null))); - } catch (Throwable t) { - options - .getLogger() - .log(SentryLevel.WARNING, "Expected a List as header", t); - } - } + attributes.forEach((key, value) -> { + final @NotNull String attributeKeyAsString = key.getKey(); + if (attributeKeyAsString.startsWith(HTTP_REQUEST_HEADER_PREFIX)) { + final @NotNull String headerName = + StringUtils.removePrefix(attributeKeyAsString, HTTP_REQUEST_HEADER_PREFIX); + if (options.isSendDefaultPii() || !HttpUtils.containsSensitiveHeader(headerName)) { + if (value instanceof List) { + try { + final @NotNull List headerValues = (List) value; + headers.put( + headerName, + toString( + CookieUtils.filterOutSecurityCookiesFromHeader( + headerValues, headerName, null))); + } catch (Throwable t) { + options.getLogger().log(SentryLevel.WARNING, "Expected a List as header", t); } } - }); + } + } + }); return headers; } diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OtelSentrySpanProcessor.java b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OtelSentrySpanProcessor.java index 1cf6fa5d833..880a2840757 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OtelSentrySpanProcessor.java +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/OtelSentrySpanProcessor.java @@ -156,13 +156,11 @@ private boolean isRootSpan(SpanData otelSpan) { private static void updatePropagationContext( IScopes scopes, PropagationContext propagationContext) { - scopes.configureScope( - scope -> { - scope.withPropagationContext( - oldPropagationContext -> { - scope.setPropagationContext(propagationContext); - }); - }); + scopes.configureScope(scope -> { + scope.withPropagationContext(oldPropagationContext -> { + scope.setPropagationContext(propagationContext); + }); + }); } @Override diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySampler.java b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySampler.java index 1a9e8724ca6..6fd2f037f25 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySampler.java +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/main/java/io/sentry/opentelemetry/SentrySampler.java @@ -148,13 +148,12 @@ public SamplingResult shouldSample( final @NotNull Map mapWithStringKeys = new HashMap<>(attributes.size()); if (attributes != null) { - attributes.forEach( - (key, value) -> { - if (key != null) { - final @NotNull String stringKey = key.getKey(); - mapWithStringKeys.put(stringKey, value); - } - }); + attributes.forEach((key, value) -> { + if (key != null) { + final @NotNull String stringKey = key.getKey(); + mapWithStringKeys.put(stringKey, value); + } + }); } return mapWithStringKeys; 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 3cc492a9e4c..cd5063d1880 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 @@ -119,7 +119,7 @@ public CompletableResultCode export(Collection spans) { final @NotNull SentryInstantDate now = new SentryInstantDate(); final @NotNull List nonExpired = - remaining.stream().filter((span) -> !isSpanTooOld(span, now)).collect(Collectors.toList()); + remaining.stream().filter(span -> !isSpanTooOld(span, now)).collect(Collectors.toList()); this.finishedSpans.addAll(nonExpired); @@ -145,7 +145,7 @@ private boolean isSpanTooOld(final @NotNull SpanData span, final @NotNull Sentry private @NotNull List filterOutSentrySpans(final @NotNull Collection spans) { return spans.stream() - .filter((span) -> !isSentryRequest(scopes, span.getKind(), span.getAttributes())) + .filter(span -> !isSentryRequest(scopes, span.getKind(), span.getAttributes())) .collect(Collectors.toList()); } @@ -176,8 +176,8 @@ private List maybeSend(final @NotNull List spans) { } return remaining.stream() - .map((node) -> node.getSpan()) - .filter((it) -> it != null) + .map(node -> node.getSpan()) + .filter(it -> it != null) .collect(Collectors.toList()); } @@ -381,7 +381,7 @@ private void transferSpanDetails( private List findCompletedRootNodes(final @NotNull List grouped) { final @NotNull Predicate isRootPredicate = - (node) -> { + node -> { return node.getParentNode() == null && node.getSpan() != null; }; return grouped.stream().filter(isRootPredicate).collect(Collectors.toList()); @@ -509,15 +509,14 @@ private SpanStatus mapOtelStatus( final @NotNull Map mapWithStringKeys = new HashMap<>(); if (attributes != null) { - attributes.forEach( - (key, value) -> { - if (key != null) { - final @NotNull String stringKey = key.getKey(); - if (!shouldRemoveAttribute(stringKey)) { - mapWithStringKeys.put(stringKey, value); - } - } - }); + attributes.forEach((key, value) -> { + if (key != null) { + final @NotNull String stringKey = key.getKey(); + if (!shouldRemoveAttribute(stringKey)) { + mapWithStringKeys.put(stringKey, value); + } + } + }); } return mapWithStringKeys; diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OpenTelemetryAttributesExtractorTest.kt b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OpenTelemetryAttributesExtractorTest.kt index 6d37240f0b2..080f69ce442 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OpenTelemetryAttributesExtractorTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OpenTelemetryAttributesExtractorTest.kt @@ -42,7 +42,7 @@ class OpenTelemetryAttributesExtractorTest { UrlAttributes.URL_QUERY to "q=123456&b=X", ServerAttributes.SERVER_ADDRESS to "io.sentry", ServerAttributes.SERVER_PORT to 8081L, - ) + ), ) whenExtractingAttributes() @@ -63,7 +63,7 @@ class OpenTelemetryAttributesExtractorTest { UrlAttributes.URL_QUERY to "q=123456&b=X", ServerAttributes.SERVER_ADDRESS to "io.sentry", ServerAttributes.SERVER_PORT to 8081L, - ) + ), ) whenExtractingAttributes() @@ -89,7 +89,7 @@ class OpenTelemetryAttributesExtractorTest { UrlAttributes.URL_QUERY to "q=123456&b=X", ServerAttributes.SERVER_ADDRESS to "io.sentry", ServerAttributes.SERVER_PORT to 8081L, - ) + ), ) whenExtractingAttributes() @@ -107,7 +107,7 @@ class OpenTelemetryAttributesExtractorTest { it.queryString = "s=abc" } givenAttributes( - mapOf(UrlAttributes.URL_FULL to "https://io.sentry:8081/path/to/123?q=123456&b=X") + mapOf(UrlAttributes.URL_FULL to "https://io.sentry:8081/path/to/123?q=123456&b=X"), ) whenExtractingAttributes() @@ -125,7 +125,7 @@ class OpenTelemetryAttributesExtractorTest { UrlAttributes.URL_SCHEME to "https", UrlAttributes.URL_PATH to "/path/to/123", ServerAttributes.SERVER_ADDRESS to "io.sentry", - ) + ), ) whenExtractingAttributes() @@ -141,7 +141,7 @@ class OpenTelemetryAttributesExtractorTest { HttpAttributes.HTTP_REQUEST_METHOD to "GET", UrlAttributes.URL_SCHEME to "https", ServerAttributes.SERVER_ADDRESS to "io.sentry", - ) + ), ) whenExtractingAttributes() @@ -153,7 +153,7 @@ class OpenTelemetryAttributesExtractorTest { @Test fun `does not set URL if server address is missing`() { givenAttributes( - mapOf(HttpAttributes.HTTP_REQUEST_METHOD to "GET", UrlAttributes.URL_SCHEME to "https") + mapOf(HttpAttributes.HTTP_REQUEST_METHOD to "GET", UrlAttributes.URL_SCHEME to "https"), ) whenExtractingAttributes() @@ -168,7 +168,7 @@ class OpenTelemetryAttributesExtractorTest { mapOf( HttpAttributes.HTTP_REQUEST_METHOD to "GET", ServerAttributes.SERVER_ADDRESS to "io.sentry", - ) + ), ) whenExtractingAttributes() @@ -203,7 +203,7 @@ class OpenTelemetryAttributesExtractorTest { ServerAttributes.SERVER_ADDRESS to "sentry.io", ServerAttributes.SERVER_PORT to 8082L, UrlAttributes.URL_PATH to "/some/path", - ) + ), ) val url = whenExtractingUrl() @@ -218,7 +218,7 @@ class OpenTelemetryAttributesExtractorTest { UrlAttributes.URL_SCHEME to "https", ServerAttributes.SERVER_ADDRESS to "sentry.io", UrlAttributes.URL_PATH to "/some/path", - ) + ), ) val url = whenExtractingUrl() @@ -233,7 +233,7 @@ class OpenTelemetryAttributesExtractorTest { ServerAttributes.SERVER_ADDRESS to "sentry.io", ServerAttributes.SERVER_PORT to 8082L, UrlAttributes.URL_PATH to "/some/path", - ) + ), ) val url = whenExtractingUrl() @@ -248,7 +248,7 @@ class OpenTelemetryAttributesExtractorTest { UrlAttributes.URL_SCHEME to "https", ServerAttributes.SERVER_PORT to 8082L, UrlAttributes.URL_PATH to "/some/path", - ) + ), ) val url = whenExtractingUrl() @@ -259,7 +259,7 @@ class OpenTelemetryAttributesExtractorTest { @Test fun `returns reconstructed URL if attributes present without port and path`() { givenAttributes( - mapOf(UrlAttributes.URL_SCHEME to "https", ServerAttributes.SERVER_ADDRESS to "sentry.io") + mapOf(UrlAttributes.URL_SCHEME to "https", ServerAttributes.SERVER_ADDRESS to "sentry.io"), ) val url = whenExtractingUrl() @@ -274,7 +274,7 @@ class OpenTelemetryAttributesExtractorTest { UrlAttributes.URL_SCHEME to "https", ServerAttributes.SERVER_ADDRESS to "sentry.io", ServerAttributes.SERVER_PORT to 8082L, - ) + ), ) val url = whenExtractingUrl() @@ -304,7 +304,7 @@ class OpenTelemetryAttributesExtractorTest { "__" + UUID.randomUUID().toString() + "__" + - UUID.randomUUID().toString() + UUID.randomUUID().toString(), ), ) givenAttributes(map) @@ -336,7 +336,7 @@ class OpenTelemetryAttributesExtractorTest { @Test fun `if there is no request method attribute does not set request on scope`() { givenAttributes( - mapOf(UrlAttributes.URL_SCHEME to "https", ServerAttributes.SERVER_ADDRESS to "io.sentry") + mapOf(UrlAttributes.URL_SCHEME to "https", ServerAttributes.SERVER_ADDRESS to "io.sentry"), ) whenExtractingAttributes() diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelInternalSpanDetectionUtilTest.kt b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelInternalSpanDetectionUtilTest.kt index 63a6c77c520..2269dde7f7b 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelInternalSpanDetectionUtilTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelInternalSpanDetectionUtilTest.kt @@ -40,7 +40,7 @@ class OtelInternalSpanDetectionUtilTest { UrlAttributes.URL_QUERY to "q=123456&b=X", ServerAttributes.SERVER_ADDRESS to "io.sentry", ServerAttributes.SERVER_PORT to 8081L, - ) + ), ) thenRequestIsConsideredInternal() @@ -67,7 +67,7 @@ class OtelInternalSpanDetectionUtilTest { UrlAttributes.URL_QUERY to "q=123456&b=X", ServerAttributes.SERVER_ADDRESS to "io.sentry", ServerAttributes.SERVER_PORT to 8081L, - ) + ), ) thenRequestIsConsideredInternal() diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelSentryPropagatorTest.kt b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelSentryPropagatorTest.kt index f935d71b329..6ff4ff1eaa8 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelSentryPropagatorTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelSentryPropagatorTest.kt @@ -129,8 +129,8 @@ class OtelSentryPropagatorTest { whenever(sentrySpan.toBaggageHeader(anyOrNull())) .thenReturn( BaggageHeader( - "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" - ) + "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", + ), ) val otelSpanContext = SpanContext.create( @@ -163,8 +163,8 @@ class OtelSentryPropagatorTest { whenever(sentrySpan.toBaggageHeader(anyOrNull())) .thenReturn( BaggageHeader( - "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" - ) + "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", + ), ) whenever(sentrySpan.openTelemetrySpanAttributes).thenReturn(otelAttributes) val otelSpanContext = @@ -202,8 +202,8 @@ class OtelSentryPropagatorTest { whenever(sentrySpan.toBaggageHeader(anyOrNull())) .thenReturn( BaggageHeader( - "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" - ) + "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", + ), ) whenever(sentrySpan.openTelemetrySpanAttributes).thenReturn(otelAttributes) val otelSpanContext = @@ -241,8 +241,8 @@ class OtelSentryPropagatorTest { whenever(sentrySpan.toBaggageHeader(anyOrNull())) .thenReturn( BaggageHeader( - "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" - ) + "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", + ), ) whenever(sentrySpan.openTelemetrySpanAttributes).thenReturn(otelAttributes) val otelSpanContext = diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelSpanWrapperTest.kt b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelSpanWrapperTest.kt index 8432aeff9e5..7fa49dc69d4 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelSpanWrapperTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/OtelSpanWrapperTest.kt @@ -31,7 +31,7 @@ class OtelSpanWrapperTest { "cedf5b7571cb4972", TraceFlags.getSampled(), TraceState.getDefault(), - ) + ), ) whenever(otelSpan.name).thenReturn("parent") diff --git a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySamplerTest.kt b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySamplerTest.kt index 8a8ec0c8e0d..242b1cb35a6 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySamplerTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SentrySamplerTest.kt @@ -9,6 +9,8 @@ import io.opentelemetry.api.trace.TraceFlags import io.opentelemetry.api.trace.TraceState import io.opentelemetry.context.Context import io.opentelemetry.sdk.trace.SdkTracerProvider +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor +import io.opentelemetry.sdk.trace.export.SpanExporter import io.opentelemetry.sdk.trace.samplers.Sampler import io.opentelemetry.sdk.trace.samplers.SamplingDecision import io.sentry.DataCategory @@ -138,18 +140,24 @@ class SentrySamplerTest { verify(onDiscard).execute(DiscardReason.CALLBACK_ERROR, DataCategory.Span, 1) verifyNoMoreInteractions(onDiscard) val recordingSampler = mock(defaultAnswer = delegatesTo(sampler)) - SdkTracerProvider.builder().setSampler(recordingSampler).build().use { provider -> - val openTelemetry = - mock().also { - whenever(it.tracerProvider).thenReturn(provider) - } - OtelSpanFactory(openTelemetry).createTransaction(context, scopes, TransactionOptions(), null) - val attributes = argumentCaptor() - verify(recordingSampler).shouldSample(any(), any(), any(), any(), attributes.capture(), any()) - val restored = OtelSamplingUtil.extractSamplingDecision(attributes.firstValue)!! - assertThat(restored.sampled).isFalse() - assertThat(restored.profileSampled).isFalse() - } + SdkTracerProvider.builder() + .setSampler(recordingSampler) + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.composite())) + .build() + .use { provider -> + val openTelemetry = + mock().also { + whenever(it.tracerProvider).thenReturn(provider) + } + OtelSpanFactory(openTelemetry) + .createTransaction(context, scopes, TransactionOptions(), null) + val attributes = argumentCaptor() + verify(recordingSampler) + .shouldSample(any(), any(), any(), any(), attributes.capture(), any()) + val restored = OtelSamplingUtil.extractSamplingDecision(attributes.firstValue)!! + assertThat(restored.sampled).isFalse() + assertThat(restored.profileSampled).isFalse() + } verifyNoMoreInteractions(onDiscard) } 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 a43afb849e6..4290b0cf7e3 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SpanDescriptionExtractorTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-core/src/test/kotlin/SpanDescriptionExtractorTest.kt @@ -107,7 +107,7 @@ class SpanDescriptionExtractorTest { mapOf( HttpAttributes.HTTP_REQUEST_METHOD to "GET", UrlAttributes.URL_FULL to "https://sentry.io/some/path?q=1#top", - ) + ), ) val info = whenExtractingSpanInfo() @@ -121,7 +121,7 @@ class SpanDescriptionExtractorTest { fun `uses URL_PATH for description`() { givenSpanKind(SpanKind.SERVER) givenAttributes( - mapOf(HttpAttributes.HTTP_REQUEST_METHOD to "GET", UrlAttributes.URL_PATH to "/some/path") + mapOf(HttpAttributes.HTTP_REQUEST_METHOD to "GET", UrlAttributes.URL_PATH to "/some/path"), ) val info = whenExtractingSpanInfo() @@ -140,7 +140,7 @@ class SpanDescriptionExtractorTest { HttpAttributes.HTTP_ROUTE to "/some/{id}", HttpIncubatingAttributes.HTTP_TARGET to "some/path?q=1#top", UrlAttributes.URL_PATH to "/some/path", - ) + ), ) val info = whenExtractingSpanInfo() @@ -181,7 +181,7 @@ class SpanDescriptionExtractorTest { mapOf( DbIncubatingAttributes.DB_SYSTEM to "some", DbIncubatingAttributes.DB_QUERY_TEXT to "SELECT * FROM tbl", - ) + ), ) val info = whenExtractingSpanInfo() @@ -197,7 +197,7 @@ class SpanDescriptionExtractorTest { mapOf( DbIncubatingAttributes.DB_SYSTEM to "some", DbIncubatingAttributes.DB_STATEMENT to "SELECT * FROM tbl", - ) + ), ) val info = whenExtractingSpanInfo() @@ -238,7 +238,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "publish", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = false) @@ -255,7 +255,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "publish", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -272,7 +272,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "send", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -289,7 +289,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "process", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -306,7 +306,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "deliver", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -323,7 +323,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "create", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -340,7 +340,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "receive", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -357,7 +357,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "rabbitmq", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-queue", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "settle", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -375,7 +375,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "rabbitmq", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "queue-name", MessagingIncubatingAttributes.MESSAGING_OPERATION to "publish", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -391,7 +391,7 @@ class SpanDescriptionExtractorTest { mapOf( MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -407,7 +407,7 @@ class SpanDescriptionExtractorTest { mapOf( MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-topic", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -423,7 +423,7 @@ class SpanDescriptionExtractorTest { mapOf( MessagingIncubatingAttributes.MESSAGING_SYSTEM to "kafka", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "publish", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -444,7 +444,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "aws.sqs", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-queue", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "publish", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = true) @@ -464,7 +464,7 @@ class SpanDescriptionExtractorTest { MessagingIncubatingAttributes.MESSAGING_SYSTEM to "aws.sqs", MessagingIncubatingAttributes.MESSAGING_DESTINATION_NAME to "my-queue", MessagingIncubatingAttributes.MESSAGING_OPERATION_TYPE to "publish", - ) + ), ) val info = whenExtractingSpanInfo(queueTracingEnabled = false) diff --git a/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtelSentryPropagatorTest.kt b/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtelSentryPropagatorTest.kt index afa728c7ff0..61a8f20bc5a 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtelSentryPropagatorTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtelSentryPropagatorTest.kt @@ -8,6 +8,8 @@ import io.opentelemetry.context.Context import io.opentelemetry.context.propagation.TextMapGetter import io.opentelemetry.context.propagation.TextMapSetter import io.opentelemetry.sdk.trace.SdkTracerProvider +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor +import io.opentelemetry.sdk.trace.export.SpanExporter import io.sentry.Baggage import io.sentry.Sentry import kotlin.test.AfterTest @@ -158,7 +160,7 @@ class OpenTelemetryOtlpPropagatorTest { val otelSpan = Span.wrap(otelSpanContext) val baggage = Baggage.fromHeader( - "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" + "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", ) val context = Context.root().with(otelSpan).with(OpenTelemetryOtlpPropagator.SENTRY_BAGGAGE_KEY, baggage) @@ -180,7 +182,10 @@ class OpenTelemetryOtlpPropagatorTest { } val propagator = OpenTelemetryOtlpPropagator() val carrier = mutableMapOf() - val tracerProvider = SdkTracerProvider.builder().build() + val tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.composite())) + .build() val otelSpan = tracerProvider .get("test") @@ -189,7 +194,7 @@ class OpenTelemetryOtlpPropagatorTest { .startSpan() val baggage = Baggage.fromHeader( - "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" + "sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", ) try { @@ -220,7 +225,10 @@ class OpenTelemetryOtlpPropagatorTest { } val propagator = OpenTelemetryOtlpPropagator() val carrier = mutableMapOf() - val tracerProvider = SdkTracerProvider.builder().build() + val tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.composite())) + .build() val otelSpan = tracerProvider .get("test") diff --git a/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtlpEndToEndTest.kt b/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtlpEndToEndTest.kt index ce66d5f9dae..8c9672a2012 100644 --- a/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtlpEndToEndTest.kt +++ b/sentry-opentelemetry/sentry-opentelemetry-otlp/src/test/kotlin/OtlpEndToEndTest.kt @@ -3,6 +3,8 @@ package io.sentry.opentelemetry.otlp import com.google.common.truth.Truth.assertThat import io.opentelemetry.sdk.OpenTelemetrySdk import io.opentelemetry.sdk.trace.SdkTracerProvider +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor +import io.opentelemetry.sdk.trace.export.SpanExporter import io.sentry.Sentry import io.sentry.test.MockSentryServer import io.sentry.test.event @@ -20,7 +22,13 @@ import kotlin.test.Test class OtlpEndToEndTest { private val server = MockSentryServer() private val openTelemetry = - OpenTelemetrySdk.builder().setTracerProvider(SdkTracerProvider.builder().build()).build() + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.composite())) + .build(), + ) + .build() @AfterTest fun teardown() { diff --git a/sentry-quartz/src/test/kotlin/io/sentry/quartz/SentryJobListenerTest.kt b/sentry-quartz/src/test/kotlin/io/sentry/quartz/SentryJobListenerTest.kt index 7f6ddd68bab..d447b0c97ca 100644 --- a/sentry-quartz/src/test/kotlin/io/sentry/quartz/SentryJobListenerTest.kt +++ b/sentry-quartz/src/test/kotlin/io/sentry/quartz/SentryJobListenerTest.kt @@ -44,7 +44,7 @@ class SentryJobListenerTest { fun `cron trigger is sent as crontab monitor config with timezone`() { val config = inProgressMonitorConfig( - cronTrigger("0 15 10 ? * MON-FRI", TimeZone.getTimeZone("America/New_York")) + cronTrigger("0 15 10 ? * MON-FRI", TimeZone.getTimeZone("America/New_York")), ) assertThat(config).isNotNull() @@ -161,7 +161,7 @@ class SentryJobListenerTest { val trigger = TriggerBuilder.newTrigger() .withSchedule( - CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInDays(1) + CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInDays(1), ) .build() diff --git a/sentry-samples/sentry-samples-android/build.gradle.kts b/sentry-samples/sentry-samples-android/build.gradle.kts index cf63b11ff68..71c34564edf 100644 --- a/sentry-samples/sentry-samples-android/build.gradle.kts +++ b/sentry-samples/sentry-samples-android/build.gradle.kts @@ -47,7 +47,7 @@ plugins.withId("io.sentry.android.gradle") { InstrumentationFeature.COMPOSE, InstrumentationFeature.DATABASE, InstrumentationFeature.OKHTTP, - ) + ), ) logcat.enabled.set(false) appStart.enabled.set(false) @@ -90,7 +90,7 @@ android { "ContentDescription", "LabelFor", "HardcodedText", - ) + ), ) } @@ -222,6 +222,7 @@ dependencies { implementation(libs.androidx.recyclerview) implementation(libs.androidx.viewpager2) implementation(libs.androidx.browser) + implementation(libs.androidx.webkit) implementation(libs.androidx.room3.runtime) implementation(libs.bundles.androidx.room2) implementation(libs.bundles.androidx.sqlite.drivers) @@ -278,7 +279,7 @@ abstract class ToggleNativeLoggingTask : Exec() { companion object { private val regex = Regex( - """]*android:name="io\.sentry\.session-replay\.debug"[^>]*android:value="([^"]+)"""" + """]*android:name="io\.sentry\.session-replay\.debug"[^>]*android:value="([^"]+)"""", ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml b/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml index d73711b4c9b..ce4e62d7d19 100644 --- a/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml +++ b/sentry-samples/sentry-samples-android/src/main/AndroidManifest.xml @@ -98,6 +98,11 @@ android:name=".CustomTabsActivity" android:exported="false" /> + + @@ -142,6 +147,11 @@ android:exported="false" android:theme="@style/AppTheme.Main.Translucent" /> + + + + + + + + + + + +

WebView page

+

Injected sentry-trace:

+
(none, not injected)
+ + + diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/FrameDataForSpansActivity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/FrameDataForSpansActivity.kt index 2eb995dbcf1..e8acb496816 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/FrameDataForSpansActivity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/FrameDataForSpansActivity.kt @@ -134,7 +134,7 @@ fun JankyButton(name: String, delay: Long, counter: MutableIntState) { counter.intValue += 1 Thread.sleep(delay) } - } + }, ) { Text(color = MaterialTheme.colorScheme.onPrimary, text = "$name: ${counter.intValue}") } @@ -192,9 +192,9 @@ class ViewModel { fun onStopDelayedSpanClicked() { Thread { - Thread.sleep(3000) - onStopSpanClicked() - } + Thread.sleep(3000) + onStopSpanClicked() + } .start() } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/GithubAPI.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/GithubAPI.kt index df3ee7d33fa..2cd26b7405e 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/GithubAPI.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/GithubAPI.kt @@ -15,7 +15,7 @@ object GitHubApi { SentryOkHttpInterceptor( captureFailedRequests = true, failedRequestStatusCodes = listOf(HttpStatusCodeRange(400, 599)), - ) + ), ) .build() diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/MainActivity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/MainActivity.kt index 9cfc5b14a78..ea8c4a5db86 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/MainActivity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/MainActivity.kt @@ -204,9 +204,9 @@ fun MainScreen() { Modifier.fillMaxSize() .windowInsetsPadding( WindowInsets.safeDrawing.only( - WindowInsetsSides.Top + WindowInsetsSides.Bottom + WindowInsetsSides.End - ) - ) + WindowInsetsSides.Top + WindowInsetsSides.Bottom + WindowInsetsSides.End, + ), + ), ) { when (selectedCategory) { Category.ERRORS -> ErrorsScreen() @@ -303,7 +303,7 @@ fun ErrorsScreen() { onClick = { tagSampleAction("crash_from_java") throw RuntimeException("Crash from Java button: uncaught RuntimeException") - } + }, ) { Text("Crash from Java", maxLines = 2, overflow = TextOverflow.Ellipsis) } @@ -315,7 +315,7 @@ fun ErrorsScreen() { onClick = { tagSampleAction("capture_exception") Sentry.captureException( - Exception(Exception(Exception("Capture Exception button: nested exception"))) + Exception(Exception(Exception("Capture Exception button: nested exception"))), ) }, modifier = Modifier, @@ -386,16 +386,16 @@ fun ErrorsScreen() { onClick = { tagSampleAction("anr") Thread { - synchronized(mutex) { - while (true) { - try { - Thread.sleep(10000) - } catch (e: InterruptedException) { - e.printStackTrace() - } + synchronized(mutex) { + while (true) { + try { + Thread.sleep(10000) + } catch (e: InterruptedException) { + e.printStackTrace() } } } + } .start() Handler(Looper.getMainLooper()) @@ -445,16 +445,16 @@ fun ErrorsScreen() { val latch = CountDownLatch(1) for (i in 0 until 20) { Thread { - val data = ArrayList() - try { - latch.await() - for (j in 0 until 1_000_000) { - data.add(String(ByteArray(1024 * 8))) - } - } catch (e: InterruptedException) { - e.printStackTrace() + val data = ArrayList() + try { + latch.await() + for (j in 0 until 1_000_000) { + data.add(String(ByteArray(1024 * 8))) } + } catch (e: InterruptedException) { + e.printStackTrace() } + } .start() } latch.countDown() @@ -559,7 +559,7 @@ fun TracingScreen() { OutlinedButton( onClick = { activity.startActivity( - Intent(activity, io.sentry.samples.android.sqlite.SQLiteActivity::class.java) + Intent(activity, io.sentry.samples.android.sqlite.SQLiteActivity::class.java), ) }, modifier = Modifier, @@ -568,6 +568,16 @@ fun TracingScreen() { } } } + item { + SentryTraced("open_webview_activity") { + OutlinedButton( + onClick = { activity.startActivity(Intent(activity, WebViewActivity::class.java)) }, + modifier = Modifier, + ) { + Text("Open WebView Trace Activity", maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + } } } @@ -686,7 +696,7 @@ fun SessionReplayScreen() { } else { showDialog = false } - } + }, ) { Text("Close") } @@ -884,7 +894,7 @@ fun IntegrationsScreen() { OutlinedButton( onClick = { activity.startActivity( - Intent(activity, io.sentry.samples.android.compose.ComposeActivity::class.java) + Intent(activity, io.sentry.samples.android.compose.ComposeActivity::class.java), ) }, modifier = Modifier, @@ -901,7 +911,7 @@ fun IntegrationsScreen() { Intent( activity, io.sentry.samples.android.navigation.nav2.Nav2SetupActivity::class.java, - ) + ), ) }, modifier = Modifier, @@ -1038,37 +1048,36 @@ fun UpdatesScreen() { val future = Sentry.distribution().checkForUpdate() Thread { - try { - val result = future.get() - activity.runOnUiThread { - val message = - when (result) { - is UpdateStatus.NewRelease -> { - "Update available: ${result.info.buildVersion} " + - "(Build ${result.info.buildNumber})\n" + - "Download URL: ${result.info.downloadUrl}" - } + try { + val result = future.get() + activity.runOnUiThread { + val message = + when (result) { + is UpdateStatus.NewRelease -> { + "Update available: ${result.info.buildVersion} " + + "(Build ${result.info.buildNumber})\n" + + "Download URL: ${result.info.downloadUrl}" + } - is UpdateStatus.UpToDate -> "App is up to date!" - is UpdateStatus.NoNetwork -> "No network connection: ${result.message}" - is UpdateStatus.UpdateError -> - "Error checking for updates: ${result.message}" + is UpdateStatus.UpToDate -> "App is up to date!" + is UpdateStatus.NoNetwork -> "No network connection: ${result.message}" + is UpdateStatus.UpdateError -> "Error checking for updates: ${result.message}" - else -> "Unknown status" - } - Toast.makeText(activity, message, Toast.LENGTH_LONG).show() - } - } catch (e: Exception) { - activity.runOnUiThread { - Toast.makeText( - activity, - "Error checking for updates: ${e.message}", - Toast.LENGTH_LONG, - ) - .show() - } + else -> "Unknown status" + } + Toast.makeText(activity, message, Toast.LENGTH_LONG).show() + } + } catch (e: Exception) { + activity.runOnUiThread { + Toast.makeText( + activity, + "Error checking for updates: ${e.message}", + Toast.LENGTH_LONG, + ) + .show() } } + } .start() }, modifier = Modifier, diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ProfilingActivity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ProfilingActivity.kt index e24822b3e42..03789863737 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ProfilingActivity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ProfilingActivity.kt @@ -91,11 +91,11 @@ class ProfilingActivity : ComponentActivity() { Toast.makeText(context, R.string.profiling_manual_stopped, Toast.LENGTH_SHORT).show() } - } + }, ) { Text( if (manualActive) stringResource(R.string.profiling_stop_manual) - else stringResource(R.string.profiling_start_manual) + else stringResource(R.string.profiling_start_manual), ) } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ReplayAnimationsActivity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ReplayAnimationsActivity.kt index 0fe6cda581f..f437eb719de 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ReplayAnimationsActivity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ReplayAnimationsActivity.kt @@ -199,7 +199,9 @@ private fun ComposeCanvasAnimation() { Canvas( modifier = - Modifier.fillMaxWidth().height(160.dp).background(Color(0xFF101820), RoundedCornerShape(8.dp)) + Modifier.fillMaxWidth() + .height(160.dp) + .background(Color(0xFF101820), RoundedCornerShape(8.dp)), ) { val center = Offset(size.width / 2f, size.height / 2f) val orbitRadius = min(size.width, size.height) * 0.32f diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/SecondActivity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/SecondActivity.kt index b8dec7e1059..117b468abf4 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/SecondActivity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/SecondActivity.kt @@ -89,7 +89,7 @@ class SecondActivity : AppCompatActivity() { Sentry.reportFullyDisplayed() } - } + }, ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ThirdFragment.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ThirdFragment.kt index a99185eb48f..4e9df59e6b7 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ThirdFragment.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/ThirdFragment.kt @@ -30,7 +30,7 @@ class ThirdFragment : Fragment(R.layout.third_fragment) { } child?.finish(SpanStatus.OK) } - } + }, ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/TriggerHttpRequestActivity.java b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/TriggerHttpRequestActivity.java index 5671a044437..d8497ab59ab 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/TriggerHttpRequestActivity.java +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/TriggerHttpRequestActivity.java @@ -174,11 +174,10 @@ private void executeRequest(Request request) { @Override public void onFailure(Call call, IOException e) { Sentry.captureException(e); - runOnUiThread( - () -> { - showLoading(false); - displayResponse("ERROR", null, "Request failed: " + e.getMessage(), 0); - }); + runOnUiThread(() -> { + showLoading(false); + displayResponse("ERROR", null, "Request failed: " + e.getMessage(), 0); + }); } @Override @@ -213,12 +212,11 @@ public void onResponse(Call call, Response response) throws IOException { } final String finalResponseHeaders = responseHeaders.toString(); - runOnUiThread( - () -> { - showLoading(false); - displayResponse( - statusMessage, statusCode, finalBody, responseTime, finalResponseHeaders); - }); + runOnUiThread(() -> { + showLoading(false); + displayResponse( + statusMessage, statusCode, finalBody, responseTime, finalResponseHeaders); + }); response.close(); } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/WebViewActivity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/WebViewActivity.kt new file mode 100644 index 00000000000..aa46a032a27 --- /dev/null +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/WebViewActivity.kt @@ -0,0 +1,129 @@ +package io.sentry.samples.android + +import android.annotation.SuppressLint +import android.graphics.Typeface +import android.os.Bundle +import android.webkit.JavascriptInterface +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.webkit.WebViewAssetLoader +import io.sentry.Sentry +import io.sentry.android.core.SentryWebViewTracing + +/** + * Connects the app's trace with a page shown in a WebView. + * + * The page is bundled in `assets/webview` and served over https by [WebViewAssetLoader], so its + * host can be allowed like any other. It runs `@sentry/browser`, which continues the injected trace + * on pageload, and reports back the `sentry-trace` meta tag its first synchronous `` script + * saw, so the connection can be checked on the device. + */ +class WebViewActivity : AppCompatActivity() { + + private lateinit var receivedView: TextView + private lateinit var statusView: TextView + + private var nativeTrace: String? = null + private var pageTrace: String? = null + private var installed = false + + @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + val nativeTraceView = valueView() + receivedView = valueView() + statusView = TextView(this).apply { setTypeface(typeface, Typeface.BOLD) } + val webView = WebView(this) + + setContentView( + LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + ViewCompat.setOnApplyWindowInsetsListener(this) { view, insets -> + val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) + view.setPadding(32, systemBars.top + 32, 32, systemBars.bottom) + insets + } + addView(labelView("App trace")) + addView(nativeTraceView) + addView(labelView("WebView received")) + addView(receivedView) + addView(statusView) + addView(webView, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) + }, + ) + + val assetLoader = + WebViewAssetLoader.Builder() + .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this)) + .build() + webView.webViewClient = + object : WebViewClient() { + override fun shouldInterceptRequest( + view: WebView, + request: WebResourceRequest, + ): WebResourceResponse? = assetLoader.shouldInterceptRequest(request.url) + } + webView.settings.javaScriptEnabled = true + // Only the bundled demo page is loaded, so exposing this bridge to it is fine for a sample. + webView.addJavascriptInterface(PageBridge(), "SentrySample") + + // The trace that addTracePropagation injects, read right before it takes its snapshot. + nativeTrace = Sentry.getTraceparent()?.value + nativeTraceView.text = nativeTrace ?: "(no trace)" + + // Before loadUrl: the script applies to documents that start loading after this call. + installed = SentryWebViewTracing.addTracePropagation(webView, ALLOWED_HOST) + updateStatus() + + webView.loadUrl(PAGE_URL) + } + + private fun updateStatus() { + receivedView.text = pageTrace?.ifEmpty { "(none, not injected)" } ?: "(waiting…)" + statusView.text = + when { + !installed -> "Trace propagation not installed, see the Sentry logs" + pageTrace != null && pageTrace == nativeTrace -> "WebView trace connected ✓" + else -> "WebView trace not connected" + } + } + + private fun labelView(text: String): TextView = + TextView(this).apply { + this.text = text + setTypeface(typeface, Typeface.BOLD) + setPadding(0, 16, 0, 0) + } + + private fun valueView(): TextView = + TextView(this).apply { + typeface = Typeface.MONOSPACE + setTextIsSelectable(true) + } + + /** Called by the page's scripts, on a background thread. */ + private inner class PageBridge { + @JavascriptInterface fun dsn(): String? = Sentry.getCurrentScopes().options.dsn + + @JavascriptInterface + fun onPageTrace(trace: String) { + runOnUiThread { + pageTrace = trace + updateStatus() + } + } + } + + private companion object { + const val ALLOWED_HOST = WebViewAssetLoader.DEFAULT_DOMAIN + const val PAGE_URL = "https://$ALLOWED_HOST/assets/webview/index.html" + } +} diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/memory/MemoryLimiterActivity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/memory/MemoryLimiterActivity.kt index 087cfdbb8a1..b1080043a1e 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/memory/MemoryLimiterActivity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/memory/MemoryLimiterActivity.kt @@ -73,7 +73,7 @@ private val cautionTint = Color(0xFFFFF1DB) private val failureTint = Color(0xFFFFE1E3) private enum class AllocationOutcome { - JAVA_OOM + JAVA_OOM, } /** @@ -164,7 +164,7 @@ class MemoryLimiterActivity : ComponentActivity() { private fun releaseBuffers() { resetAllocatorState( - status = "Released retained buffers and requested a fresh start for the next run." + status = "Released retained buffers and requested a fresh start for the next run.", ) } @@ -260,7 +260,7 @@ private fun MemoryLimiterScreen( StepText("2. Run the Apply limit command for this launch's PID.") StepText("3. Tap Start memory pressure and optionally send the app to the background.") StepText( - "4. Reopen the app after the process dies; Sentry should recover the kill on startup." + "4. Reopen the app after the process dies; Sentry should recover the kill on startup.", ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationRouteWorkDialog.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationRouteWorkDialog.kt index bfddc3129e1..9bda017b3b9 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationRouteWorkDialog.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/NavigationRouteWorkDialog.kt @@ -41,7 +41,7 @@ private fun routeWorkDialogTitle(context: Context): View = textSize = 20f setTypeface(null, Typeface.BOLD) setTextColor(context.themeColor(R.attr.textColorPrimary)) - } + }, ) addView( TextView(context).apply { @@ -49,7 +49,7 @@ private fun routeWorkDialogTitle(context: Context): View = textSize = 14f setTextColor(context.themeColor(R.attr.textColorSecondary)) setPadding(0, context.dp(8), 0, 0) - } + }, ) } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/RouteWorkApi.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/RouteWorkApi.kt index 8b12ee51fa3..faefe542994 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/RouteWorkApi.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/common/RouteWorkApi.kt @@ -19,7 +19,7 @@ internal object RouteWorkApi { SentryOkHttpInterceptor( captureFailedRequests = true, failedRequestStatusCodes = listOf(HttpStatusCodeRange(400, 599)), - ) + ), ) .build() @@ -49,7 +49,7 @@ internal object RouteWorkApi { override fun onFailure(call: retrofit2.Call, t: Throwable) { onFailure(t) } - } + }, ) } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2Activity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2Activity.kt index 0cbd4ac14b3..77b6f7a9865 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2Activity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2Activity.kt @@ -273,7 +273,7 @@ class Nav2Activity : AppCompatActivity() { currentRoute = "/${backStack.lastOrNull()?.routeName ?: RouteNames.HOME}", backStack = nav2PerformanceBackStackPreview( - backStack.map { destination -> "/${destination.routeName}" } + backStack.map { destination -> "/${destination.routeName}" }, ), state = performanceState, onBuildStack = { buildNav2PerformanceStack() }, @@ -318,12 +318,12 @@ class Nav2Activity : AppCompatActivity() { addView( sentryEventButton("Capture Exception", R.id.nav2_capture_exception) { captureSampleException("Nav2") - } + }, ) addView( - sentryEventButton("Crash App", R.id.nav2_crash_app) { showCrashConfirmation("Nav2") } + sentryEventButton("Crash App", R.id.nav2_crash_app) { showCrashConfirmation("Nav2") }, ) - } + }, ) } } @@ -411,7 +411,7 @@ class Nav2Activity : AppCompatActivity() { currentRoute = "/${backStack.lastOrNull()?.routeName ?: RouteNames.HOME}", backStack = nav2PerformanceBackStackPreview( - backStack.map { destination -> "/${destination.routeName}" } + backStack.map { destination -> "/${destination.routeName}" }, ), ) } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2ComposeRoutes.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2ComposeRoutes.kt index 9d083ef7431..8eff5d7803d 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2ComposeRoutes.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2ComposeRoutes.kt @@ -261,7 +261,7 @@ internal fun Nav2ComposeApp( productId = "42", source = "product-list", campaign = "summer-sale", - ) + ), ) }, onOpenProduct7 = { @@ -655,7 +655,7 @@ private fun Nav2ComposePromoDialogRoute( routeSpec.displayArguments(mapOf(NavArgs.PROMO_ID to promoId)).toDisplayString() Text( listOfNotNull(routeSpec.description, argumentText.takeIf { it.isNotEmpty() }) - .joinToString("\n\n") + .joinToString("\n\n"), ) }, confirmButton = { @@ -843,7 +843,7 @@ private fun nav2ComposeBackStackSaver() = restore = { savedDestinations -> mutableStateListOf().apply { addAll( - savedDestinations.map { savedDestination -> savedDestination.toNav2ComposeDestination() } + savedDestinations.map { savedDestination -> savedDestination.toNav2ComposeDestination() }, ) if (isEmpty()) { add(Home) diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2ModalFragments.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2ModalFragments.kt index dc1e593a68b..e4d54129f5b 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2ModalFragments.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2ModalFragments.kt @@ -35,7 +35,7 @@ class Nav2PromoDialogFragment : DialogFragment() { orientation = LinearLayout.VERTICAL setPadding(20.dp(requireContext())) addView(promoDialogContent(activity, promoId)) - } + }, ) } } @@ -62,13 +62,13 @@ class Nav2PromoDialogFragment : DialogFragment() { addView( primaryButton(context, R.id.nav2_modal_capture_exception, "Exception") { activity.captureSampleException("Nav2") - } + }, ) addView(spacer(context, height = 10.dp(context))) addView( secondaryButton(context, R.id.nav2_modal_crash_app, "Crash App") { activity.showCrashConfirmation("Nav2") - } + }, ) addView(spacer(context, height = 10.dp(context))) addView( @@ -77,9 +77,9 @@ class Nav2PromoDialogFragment : DialogFragment() { gravity = Gravity.END layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT) addView( - quietButton(context, R.id.nav2_modal_dismiss, "Dismiss") { activity.navigateBack() } + quietButton(context, R.id.nav2_modal_dismiss, "Dismiss") { activity.navigateBack() }, ) - } + }, ) } } @@ -98,7 +98,7 @@ class Nav2ShareSheetFragment : DialogFragment() { orientation = LinearLayout.VERTICAL setPadding(12.dp(requireContext()), 0, 12.dp(requireContext()), 12.dp(requireContext())) addView(shareSheetContent(activity, productId)) - } + }, ) } } @@ -128,13 +128,13 @@ class Nav2ShareSheetFragment : DialogFragment() { addView( primaryButton(context, R.id.nav2_modal_capture_exception, "Capture Exception") { activity.captureSampleException("Nav2") - } + }, ) addView(spacer(context, height = 10.dp(context))) addView( secondaryButton(context, R.id.nav2_modal_crash_app, "Crash App") { activity.showCrashConfirmation("Nav2") - } + }, ) addView(spacer(context, height = 10.dp(context))) addView( @@ -142,7 +142,7 @@ class Nav2ShareSheetFragment : DialogFragment() { .apply { backgroundTintList = ColorStateList.valueOf(0xFFE8E1F7.toInt()) setTextColor(0xFF4E4569.toInt()) - } + }, ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2RouteFragment.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2RouteFragment.kt index 8a76d3eb301..f1aff222357 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2RouteFragment.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2RouteFragment.kt @@ -45,7 +45,7 @@ class Nav2RouteFragment : Fragment() { listOf( RouteButton(R.id.nav2_fragment_browse_products, "Browse Products") { activity.navigateTo(Nav2Destination.ProductList) - } + }, ), ) @@ -56,7 +56,7 @@ class Nav2RouteFragment : Fragment() { listOf( RouteButton(R.id.nav2_fragment_open_deep_link, "Go to deep link destination") { activity.openSyntheticProductDeepLink() - } + }, ), ) @@ -67,7 +67,7 @@ class Nav2RouteFragment : Fragment() { listOf( RouteButton(R.id.nav2_fragment_open_product_42, "Open Product 42") { activity.navigateTo( - Nav2Destination.ProductDetail("42", "product-list", "summer-sale") + Nav2Destination.ProductDetail("42", "product-list", "summer-sale"), ) }, RouteButton(R.id.nav2_fragment_open_product_7, "Open Product 7") { @@ -85,7 +85,7 @@ class Nav2RouteFragment : Fragment() { else -> routeLayout( - RouteSpec(routeName = routeName, title = "Unknown Route", description = routeName) + RouteSpec(routeName = routeName, title = "Unknown Route", description = routeName), ) } } @@ -151,7 +151,7 @@ class Nav2RouteFragment : Fragment() { listOf( RouteButton(R.id.nav2_fragment_complete_order, "Complete Order") { activity.navigateTo(Nav2Destination.Confirmation("order-$productId")) - } + }, ), ) } @@ -165,7 +165,7 @@ class Nav2RouteFragment : Fragment() { listOf( RouteButton(R.id.nav2_fragment_reset_backstack, "Reset Backstack") { activity.resetToHome() - } + }, ), ) } @@ -191,7 +191,7 @@ class Nav2RouteFragment : Fragment() { setBackgroundColor(context.themeColor(android.R.attr.colorBackgroundFloating)) info.forEach { (label, value) -> addView(infoRow(label, value)) } buttons.forEach { button -> addView(routeButton(button)) } - } + }, ) } trailingContent?.invoke(this) @@ -227,7 +227,7 @@ class Nav2RouteFragment : Fragment() { scrollView.visibility = if (itemsVisible) View.VISIBLE else View.GONE } layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT) - } + }, ) addView(scrollView) } @@ -299,13 +299,13 @@ class Nav2RouteFragment : Fragment() { textSize = 14f setTypeface(null, Typeface.BOLD) layoutParams = LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f) - } + }, ) addView( TextView(context).apply { text = "SKU-$itemNumber" textSize = 14f - } + }, ) } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2SampleConfigAdapter.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2SampleConfigAdapter.kt index 13b97107e3f..a9ebe42002d 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2SampleConfigAdapter.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2SampleConfigAdapter.kt @@ -11,7 +11,7 @@ internal fun currentNav2SampleConfigSnapshot(): NavigationSampleConfigSnapshot = currentNavigationSampleConfigSnapshot() internal fun Intent.previousNav2SampleConfigSnapshot( - fallback: NavigationSampleConfigSnapshot + fallback: NavigationSampleConfigSnapshot, ): NavigationSampleConfigSnapshot = NavigationSampleConfigSnapshot( enableScreenTracking = diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TopBar.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TopBar.kt index 6cacd2959ab..e2a6723f72e 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TopBar.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TopBar.kt @@ -105,12 +105,12 @@ internal class Nav2TopBar( val selected = tabScenario == scenario tabView.label.setTextColor( if (selected) context.themeColor(androidx.appcompat.R.attr.colorPrimary) - else tabView.defaultTextColor + else tabView.defaultTextColor, ) tabView.label.setTypeface(null, if (selected) Typeface.BOLD else Typeface.NORMAL) tabView.indicator.setBackgroundColor( if (selected) context.themeColor(androidx.appcompat.R.attr.colorPrimary) - else color(android.R.color.transparent) + else color(android.R.color.transparent), ) } } @@ -129,11 +129,11 @@ internal class Nav2TopBar( textSize = 20f setTextColor(context.themeColor(android.R.attr.textColorPrimary)) layoutParams = LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f) - } + }, ) addView(transactionHistoryIcon()) addView(routeWorkSettingsIcon()) - } + }, ) addView(View(context), LinearLayout.LayoutParams(MATCH_PARENT, 12.dp)) addView(currentRouteScroll) diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TransactionHistory.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TransactionHistory.kt index f64a78b051d..0c175bf9290 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TransactionHistory.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TransactionHistory.kt @@ -126,18 +126,18 @@ private fun SentrySpan.toNav2TraceSpan(transactionStartTimestamp: Double): Nav2T ) private fun List.withChildren( - spansByParentId: Map> + spansByParentId: Map>, ): List = map { span -> span.withChildren(spansByParentId) } private fun Nav2TraceSpan.withChildren( - spansByParentId: Map> + spansByParentId: Map>, ): Nav2TraceSpan = copy( children = spansByParentId[spanId] .orEmpty() .sortedBy { span -> span.startOffsetMillis } - .withChildren(spansByParentId) + .withChildren(spansByParentId), ) private fun sentryTransactionUrl( diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TransactionHistorySheet.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TransactionHistorySheet.kt index 878f7b5f6b5..4e7e433a5fb 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TransactionHistorySheet.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav2/Nav2TransactionHistorySheet.kt @@ -259,7 +259,7 @@ private fun TraceRow( .height(12.dp) .align(Alignment.CenterStart) .clip(RoundedCornerShape(2.dp)) - .background(color) + .background(color), ) Text( durationMillis.formatMillis(), @@ -283,7 +283,7 @@ private fun TimelineGrid() { Modifier.width(1.dp) .height(24.dp) .align(Alignment.CenterEnd) - .background(MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)) + .background(MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)), ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt index 449ac2b2995..807fedad09a 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Activity.kt @@ -356,7 +356,7 @@ private fun Nav3SampleApp( host.startActivity( Intent(host, Nav3FragmentsActivity::class.java) .putExtra(Nav3FragmentsActivity.EXTRA_MODE, mode.name) - .putExtras(Bundle().apply { putNav3SampleConfiguration(configuration) }) + .putExtras(Bundle().apply { putNav3SampleConfiguration(configuration) }), ) } } @@ -398,7 +398,7 @@ private fun Nav3SampleApp( modifier = Modifier.fillMaxSize() .padding(innerPadding) - .background(MaterialTheme.colorScheme.background) + .background(MaterialTheme.colorScheme.background), ) { NavDisplay( backStack = backStack, @@ -473,7 +473,7 @@ private fun Nav3SampleApp( MultiActivityRoute { activity?.startActivity( Intent(activity, Nav3ProductsActivity::class.java) - .putExtras(Bundle().apply { putNav3SampleConfiguration(configuration) }) + .putExtras(Bundle().apply { putNav3SampleConfiguration(configuration) }), ) } } @@ -610,7 +610,7 @@ private fun Nav3SampleApp( onClick = { onDismissCrashConfirmation() crashSampleApp("Nav3") - } + }, ) { Text("Crash") } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3BottomSheetSceneStrategy.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3BottomSheetSceneStrategy.kt index 2ff41d96845..f28c7e9f424 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3BottomSheetSceneStrategy.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3BottomSheetSceneStrategy.kt @@ -114,7 +114,7 @@ private fun AnimatedOverlayScrim( ) { Box( modifier = - Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.32f)).clickable { onBack() } + Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.32f)).clickable { onBack() }, ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt index b15b1811687..4309cc66f08 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiActivity.kt @@ -121,7 +121,7 @@ class Nav3ProductsActivity : ComponentActivity() { onClick = { productId -> startActivity( checkoutIntent(productId, configuration) - .setClass(this, Nav3TranslucentCheckoutActivity::class.java) + .setClass(this, Nav3TranslucentCheckoutActivity::class.java), ) }, ), @@ -130,7 +130,7 @@ class Nav3ProductsActivity : ComponentActivity() { testTag = nav3TestTag("product_detail_go_to_checkout_for_result"), onClick = { productId -> checkoutForResult.launch( - checkoutIntent(productId, configuration).putExtra(EXTRA_RETURN_RESULT, true) + checkoutIntent(productId, configuration).putExtra(EXTRA_RETURN_RESULT, true), ) }, ), @@ -140,7 +140,7 @@ class Nav3ProductsActivity : ComponentActivity() { onClick = { productId -> startActivity( checkoutIntent(productId, configuration) - .putExtra(EXTRA_CRASH_ON_FIRST_COMPOSITION, true) + .putExtra(EXTRA_CRASH_ON_FIRST_COMPOSITION, true), ) }, ), @@ -373,7 +373,7 @@ internal fun MultiRootNavDisplay( val parentDispatcherOwner = LocalNavigationEventDispatcherOwner.current CompositionLocalProvider( LocalNavigationEventDispatcherOwner provides - rememberNavigationEventDispatcherOwner(enabled = isResumed, parent = parentDispatcherOwner) + rememberNavigationEventDispatcherOwner(enabled = isResumed, parent = parentDispatcherOwner), ) { NavDisplay( backStack = backStack, @@ -425,7 +425,7 @@ internal fun MultiRootNavDisplay( if (crashOnFirstComposition) { SideEffect { throw RuntimeException( - "Fatal Nav3 ${scenario.label} crash after first composition" + "Fatal Nav3 ${scenario.label} crash after first composition", ) } } @@ -460,7 +460,7 @@ internal fun MultiRootNavDisplay( onClick = { showCrashConfirmation = false crashSampleApp("Nav3 ${scenario.label}") - } + }, ) { Text("Crash") } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiFragment.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiFragment.kt index aa99ef7440f..b50ff0d7c6d 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiFragment.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3MultiFragment.kt @@ -53,7 +53,8 @@ import io.sentry.samples.android.navigation.common.applyToCurrentOptions * * - `replace` + back stack (Products → Checkout), optionally with a slow enter animation; * - a full-screen `DialogFragment` overlay whose host Fragment stays resumed; - * - a `ViewPager2` of Fragments, where neighboring pages are preloaded at STARTED. + * - a `ViewPager2` with three Nav3 Fragments and one plain Fragment, where neighbors preload at + * STARTED. */ // FragmentActivity rather than AppCompatActivity: AppCompatActivity.setContentView doesn't install // the NavigationEventDispatcherOwner that NavDisplay needs on the view tree. @@ -107,7 +108,7 @@ class Nav3FragmentsActivity : FragmentActivity() { orientation = LinearLayout.VERTICAL addView(controls, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)) addView(container, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f)) - } + }, ) if (savedInstanceState == null) { @@ -278,8 +279,8 @@ class Nav3CheckoutSheetFragment : DialogFragment() { } /** - * A `ViewPager2` whose pages each own a Nav3 root. With `offscreenPageLimit = 1`, the neighbors of - * the current page are created and capped at STARTED, while only the current page is RESUMED. + * A `ViewPager2` with three Nav3 roots and a plain page without a navigation effect. With + * `offscreenPageLimit = 1`, neighbors are capped at STARTED; only the current page is RESUMED. */ class Nav3PagerFragment : Fragment() { @@ -318,16 +319,18 @@ class Nav3PagerFragment : Fragment() { val viewPager = requireNotNull(pager) viewPager.adapter = object : FragmentStateAdapter(childFragmentManager, viewLifecycleOwner.lifecycle) { - override fun getItemCount(): Int = Nav3RootFragment.pageRoots.size + override fun getItemCount(): Int = PAGER_PAGE_COUNT - override fun createFragment(position: Int): Fragment = Nav3RootFragment.page(position) + override fun createFragment(position: Int): Fragment = + if (position == PAGER_PAGE_COUNT - 1) Nav3PlainFragment() + else Nav3RootFragment.page(position) } viewPager.registerOnPageChangeCallback( object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { currentPage = position } - } + }, ) } @@ -357,7 +360,7 @@ internal fun FragmentScenarioRoute( testTag = nav3TestTag( if (mode == Nav3FragmentMode.REPLACE) "multi_fragment_open_fragments" - else "${mode.name.lowercase()}_open_fragments" + else "${mode.name.lowercase()}_open_fragments", ), ) }, @@ -432,14 +435,14 @@ private fun PagerHeader(currentPage: Int, onSelectPage: (Int) -> Unit) { modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp).semantics { testTagsAsResourceId = true - } + }, ) { Text( "ViewPager2 page $currentPage (neighbors preloaded at STARTED)", modifier = Modifier.testTag(nav3TestTag("multi_fragment_current_page")), ) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Nav3RootFragment.pageRoots.indices.forEach { index -> + (0 until PAGER_PAGE_COUNT).forEach { index -> OutlinedButton( onClick = { onSelectPage(index) }, modifier = Modifier.testTag(nav3TestTag("multi_fragment_page_$index")), @@ -451,5 +454,7 @@ private fun PagerHeader(currentPage: Int, onSelectPage: (Int) -> Unit) { } } +private const val PAGER_PAGE_COUNT = 4 + private const val MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT private const val WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt index 90f90dd2b3a..e923948060f 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PerformanceControls.kt @@ -780,12 +780,12 @@ internal fun Nav3PerformancePanel( enabled = !state.performanceRunActive, onDecrement = { controls.onMaxCapturedBackStackEntriesChange( - (controls.maxCapturedBackStackEntries - 1).coerceAtLeast(0) + (controls.maxCapturedBackStackEntries - 1).coerceAtLeast(0), ) }, onIncrement = { controls.onMaxCapturedBackStackEntriesChange( - (controls.maxCapturedBackStackEntries + 1).coerceAtMost(100) + (controls.maxCapturedBackStackEntries + 1).coerceAtMost(100), ) }, ) diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PlainScreens.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PlainScreens.kt new file mode 100644 index 00000000000..d607f29508d --- /dev/null +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3PlainScreens.kt @@ -0,0 +1,206 @@ +package io.sentry.samples.android.navigation.nav3 + +import android.content.Intent +import android.os.Bundle +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.unit.dp +import androidx.fragment.app.Fragment +import io.sentry.ISpan +import io.sentry.Sentry +import io.sentry.samples.android.navigation.common.NavigationSampleConfigSnapshot +import io.sentry.samples.android.navigation.common.applyToCurrentOptions +import io.sentry.samples.android.navigation.common.currentNavigationSampleConfigSnapshot +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +/** Intentionally has no NavDisplay or SentryNavEffect; launch normally to stay in the same task. */ +class Nav3PlainActivity : ComponentActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // The system can restore this Activity without recreating the Nav3 Activity that set these. + NavigationSampleConfigSnapshot( + enableScreenTracking = intent.getBooleanExtra(EXTRA_ENABLE_SCREEN_TRACKING, true), + enableUserInteractionTransactions = + intent.getBooleanExtra(EXTRA_ENABLE_USER_INTERACTION_TRANSACTIONS, false), + enableUserInteractionBreadcrumbs = + intent.getBooleanExtra(EXTRA_ENABLE_USER_INTERACTION_BREADCRUMBS, false), + ) + .applyToCurrentOptions() + setContent { + Nav3SampleTheme { + PlainNav3Screen("Plain Activity", onBack = ::finish) + // Let ui.load finish normally rather than wait for the sample's TTFD timeout. + LaunchedEffect(Unit) { + reportFullyDrawn() + Sentry.reportFullyDisplayed() + } + } + } + } +} + +/** A real non-candidate pager page: no navigation integration is composed in this Fragment. */ +class Nav3PlainFragment : Fragment() { + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle?, + ): View = + ComposeView(requireContext()).apply { + setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + setContent { Nav3SampleTheme { PlainNav3Screen("Plain page (3)") } } + } +} + +@Composable +internal fun Nav3OpenPlainActivityButton(modifier: Modifier = Modifier) { + val context = LocalContext.current + Nav3SentryButton( + label = "Plain Activity", + onClick = { + val options = currentNavigationSampleConfigSnapshot() + context.startActivity( + Intent(context, Nav3PlainActivity::class.java) + .putExtra(EXTRA_ENABLE_SCREEN_TRACKING, options.enableScreenTracking) + .putExtra( + EXTRA_ENABLE_USER_INTERACTION_TRANSACTIONS, + options.enableUserInteractionTransactions, + ) + .putExtra( + EXTRA_ENABLE_USER_INTERACTION_BREADCRUMBS, + options.enableUserInteractionBreadcrumbs, + ), + ) + }, + modifier = modifier, + ) +} + +/** + * A screen without a SentryNavEffect, for checking manually that no nav data or nav transaction + * from a previously shown Nav3 root is attributed to it. + */ +@OptIn(ExperimentalComposeUiApi::class) +@Composable +private fun PlainNav3Screen(title: String, onBack: (() -> Unit)? = null) { + val coroutineScope = rememberCoroutineScope() + var snapshot by remember { mutableStateOf(PlainScreenScopeProbe.snapshot()) } + var result by remember { mutableStateOf("") } + LaunchedEffect(Unit) { + while (true) { + snapshot = PlainScreenScopeProbe.snapshot() + delay(SNAPSHOT_REFRESH_MILLIS) + } + } + Column( + Modifier.fillMaxSize().safeDrawingPadding().padding(16.dp).semantics { + testTagsAsResourceId = true + }, + ) { + Text(title, modifier = Modifier.testTag(nav3TestTag("plain_title"))) + Text( + "This screen has no SentryNavEffect. The previous root's Navigation context should be absent.", + ) + Text(snapshot, modifier = Modifier.testTag(nav3TestTag("plain_scope_state"))) + Text(result, modifier = Modifier.testTag(nav3TestTag("plain_result"))) + TextButton( + onClick = { coroutineScope.launch { result = PlainScreenScopeProbe.emitSpan() } }, + modifier = Modifier.testTag(nav3TestTag("plain_emit_span")), + ) { + Text("Emit span") + } + TextButton( + onClick = { result = PlainScreenScopeProbe.captureEvent() }, + modifier = Modifier.testTag(nav3TestTag("plain_capture_event")), + ) { + Text("Capture event") + } + if (onBack != null) { + TextButton(onClick = onBack, modifier = Modifier.testTag(nav3TestTag("plain_back"))) { + Text("Back") + } + } + } +} + +/** Reads and exercises the scope from a plain screen. Main-thread only. */ +private object PlainScreenScopeProbe { + + fun snapshot(): String { + var state = "" + Sentry.configureScope { scope -> + val transaction = scope.transaction + state = + "Transaction: ${transaction?.name} (${transaction?.operation})\n" + + "Screen: ${scope.screen}\n" + + "Navigation: ${scope.contexts["Navigation"]}" + } + return state + } + + suspend fun emitSpan(): String { + val parent = Sentry.getSpan() + val span = parent?.startChild("test.navigation.manual", "Nav3 plain screen span") + // The span must finish even if the screen disappears during the delay. + try { + delay(EMITTED_SPAN_DURATION_MILLIS) + } finally { + span?.finish() + } + return record("Emitted span; parent=${parent?.spanContext?.spanId}; ${traceUrl(parent)}") + } + + fun captureEvent(): String { + val id = Sentry.captureMessage("Nav3 plain screen event") + return record("Event: ${sentryEventSearchUrl(dsn, id.toString()) ?: id}") + } + + private fun traceUrl(transaction: ISpan?): String { + val traceId = transaction?.spanContext?.traceId?.toString() ?: return "No parent transaction" + return sentryTraceUrl(dsn, traceId) ?: "Trace: $traceId" + } + + private val dsn: String? + get() = Sentry.getCurrentScopes().options.dsn + + private fun record(message: String): String { + Log.i("Nav3PlainScreen", "$message\n${snapshot()}") + return message + } +} + +private const val SNAPSHOT_REFRESH_MILLIS = 250L +private const val EMITTED_SPAN_DURATION_MILLIS = 300L +private const val EXTRA_ENABLE_SCREEN_TRACKING = "nav3_plain.enable_screen_tracking" +private const val EXTRA_ENABLE_USER_INTERACTION_TRANSACTIONS = + "nav3_plain.enable_user_interaction_transactions" +private const val EXTRA_ENABLE_USER_INTERACTION_BREADCRUMBS = + "nav3_plain.enable_user_interaction_breadcrumbs" diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3RouteScreens.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3RouteScreens.kt index a67ed6d9d4e..dfdeb76ecb6 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3RouteScreens.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3RouteScreens.kt @@ -217,6 +217,7 @@ internal fun SentryControls( onClick = onCaptureException, modifier = Modifier.weight(1f), ) + Nav3OpenPlainActivityButton(modifier = Modifier.weight(1f)) Nav3SentryButton( label = "Crash App", onClick = onCrashApp, @@ -280,7 +281,7 @@ internal fun RouteScaffold( Modifier.fillMaxSize() .background(MaterialTheme.colorScheme.background) .padding(16.dp) - .testTag("${testTagPrefix}_screen") + .testTag("${testTagPrefix}_screen"), ) { Column( modifier = @@ -447,7 +448,7 @@ private fun Nav3CustomTransactionModeSelector( modifier = Modifier.fillMaxWidth() .testTag(nav3TestTag("custom_mode_selector")) - .testTag(nav3CustomModeSelectionTag(selected)) + .testTag(nav3CustomModeSelectionTag(selected)), ) { Nav3CustomTransactionMode.entries.forEachIndexed { index, mode -> SegmentedButton( @@ -525,7 +526,7 @@ internal fun ProductListRoute(backStack: SnapshotStateList) { productId = "42", source = "product-list", campaign = "summer-sale", - ) + ), ) }, testTag = nav3TestTag("product_list_open_product_42"), @@ -778,12 +779,12 @@ private fun nav3RouteTag(routeName: String): String = private fun nav3ButtonTag(label: String): String = nav3TestTag( - "button_${label.lowercase().replace(' ', '_').replace('/', '_').replace('.', '_').replace('-', '_')}" + "button_${label.lowercase().replace(' ', '_').replace('/', '_').replace('.', '_').replace('-', '_')}", ) private fun nav3InfoTag(label: String): String = nav3TestTag( - "info_${label.lowercase().replace(' ', '_').replace('/', '_').replace('.', '_').replace('-', '_')}" + "info_${label.lowercase().replace(' ', '_').replace('/', '_').replace('.', '_').replace('-', '_')}", ) private fun nav3CustomModeSelectionTag(mode: Nav3CustomTransactionMode): String = diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt index 70b5232c533..8dc18c45941 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3Routes.kt @@ -56,8 +56,8 @@ internal fun Nav3Route.routeSpec(): RouteSpec = routeName = Nav3Route.ViewPager2.routeName, title = "ViewPager2", description = - "Each page is a Fragment with its own SentryNavEffect and NavDisplay. Neighboring " + - "pages are preloaded at STARTED. Back returns to the Products Fragment underneath.", + "Pages 0–2 each have a SentryNavEffect and NavDisplay. Page 3 has no navigation " + + "integration. Neighbors are preloaded at STARTED. Back returns to Products.", ) Nav3Route.DeepLink -> RouteSpec( diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3SampleConfig.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3SampleConfig.kt index 45eadc367ca..88d752218cc 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3SampleConfig.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3SampleConfig.kt @@ -7,7 +7,7 @@ import io.sentry.samples.android.navigation.common.NavigationSampleConfig import io.sentry.samples.android.navigation.common.NavigationSampleConfigSnapshot internal fun Intent.previousNav3SampleConfigSnapshot( - fallback: NavigationSampleConfigSnapshot + fallback: NavigationSampleConfigSnapshot, ): NavigationSampleConfigSnapshot = NavigationSampleConfigSnapshot( enableScreenTracking = diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TopBar.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TopBar.kt index d2872f3c939..e4c72994cda 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TopBar.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TopBar.kt @@ -133,7 +133,7 @@ private fun ScenarioBar( Modifier.fillMaxWidth() .horizontalScroll(rememberScrollState()) .padding(start = 24.dp, end = 24.dp) - .testTag(nav3TestTag("scenario_bar")) + .testTag(nav3TestTag("scenario_bar")), ) { scenarios.forEach { scenario -> val selected = selectedScenario == scenario @@ -157,7 +157,7 @@ private fun ScenarioBar( .background( if (selected) selectedTabColor else Color.Transparent, RoundedCornerShape(topStart = 4.dp, topEnd = 4.dp), - ) + ), ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistory.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistory.kt index 21d99a50b2c..80e6cfa9bf2 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistory.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistory.kt @@ -62,7 +62,7 @@ internal object NavigationTransactionHistory { } internal class NavigationTransactionHistoryStore( - private val transactionLimit: Int = TRANSACTION_HISTORY_LIMIT + private val transactionLimit: Int = TRANSACTION_HISTORY_LIMIT, ) { val transactions = mutableStateListOf() @@ -103,7 +103,7 @@ internal data class NavigationTraceSpan( ) internal fun SentryTransaction.toNavigationTransactionTrace( - dsn: String? + dsn: String?, ): NavigationTransactionTrace { val trace = contexts.trace val startTimestamp = startTimestamp @@ -140,7 +140,7 @@ internal fun SentryTransaction.toNavigationTransactionTrace( } private fun SentrySpan.toNavigationTraceSpan( - transactionStartTimestamp: Double + transactionStartTimestamp: Double, ): NavigationTraceSpan = NavigationTraceSpan( spanId = spanId.toString(), @@ -153,18 +153,18 @@ private fun SentrySpan.toNavigationTraceSpan( ) private fun List.withChildren( - spansByParentId: Map> + spansByParentId: Map>, ): List = map { span -> span.withChildren(spansByParentId) } private fun NavigationTraceSpan.withChildren( - spansByParentId: Map> + spansByParentId: Map>, ): NavigationTraceSpan = copy( children = spansByParentId[spanId] .orEmpty() .sortedBy { span -> span.startOffsetMillis } - .withChildren(spansByParentId) + .withChildren(spansByParentId), ) private fun sentryTransactionUrl( @@ -187,6 +187,22 @@ private fun sentryTransactionUrl( "×tamp=${timestampSeconds.toLong()}" } +/** The URL of trace [traceId] in the project [dsn] reports to, or `null` if `dsn` names none. */ +internal fun sentryTraceUrl(dsn: String?, traceId: String): String? { + val projectId = dsn?.projectIdFromDsn() ?: return null + return "https://$SENTRY_SAMPLE_ORG_SLUG.sentry.io/explore/traces/trace/$traceId/" + + "?project=$projectId" +} + +/** + * The URL of an issue search for event [eventId] in the project [dsn] reports to, or `null` if + * `dsn` names none. + */ +internal fun sentryEventSearchUrl(dsn: String?, eventId: String): String? { + val projectId = dsn?.projectIdFromDsn() ?: return null + return "https://$SENTRY_SAMPLE_ORG_SLUG.sentry.io/issues/?project=$projectId&query=$eventId" +} + private fun String.projectIdFromDsn(): String? = substringBefore('?').substringBefore('#').trimEnd('/').substringAfterLast('/').takeIf { projectId -> diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistorySheet.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistorySheet.kt index 94a643ba7ca..e401b42ecbe 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistorySheet.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/navigation/nav3/Nav3TransactionHistorySheet.kt @@ -140,7 +140,7 @@ private fun TransactionCard( verticalAlignment = Alignment.Top, ) { Column( - modifier = Modifier.weight(1f).testTag(historyTag(sampleName, "card_${index}_summary")) + modifier = Modifier.weight(1f).testTag(historyTag(sampleName, "card_${index}_summary")), ) { Text( transaction.name, @@ -308,7 +308,7 @@ private fun TraceRow( .height(12.dp) .align(Alignment.CenterStart) .clip(RoundedCornerShape(2.dp)) - .background(color) + .background(color), ) Text( durationMillis.formatMillis(), @@ -332,7 +332,7 @@ private fun TimelineGrid() { Modifier.width(1.dp) .height(24.dp) .align(Alignment.CenterEnd) - .background(MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)) + .background(MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)), ) } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/SampleDatabases.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/SampleDatabases.kt index f01a529499d..25215301e0f 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/SampleDatabases.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/SampleDatabases.kt @@ -122,7 +122,7 @@ object SampleDatabases { "bridge_room2.db", ) .setDriver( - wrapDriver(SupportSQLiteDriver(buildBridgeRoom2Helper(context.applicationContext))) + wrapDriver(SupportSQLiteDriver(buildBridgeRoom2Helper(context.applicationContext))), ) .setQueryCoroutineContext(Dispatchers.IO) .fallbackToDestructiveMigration(true) @@ -223,7 +223,7 @@ object SampleDatabases { db.execSQL("PRAGMA user_version = 0") } } - } + }, ) .build() return wrapOpenHelper(FrameworkSQLiteOpenHelperFactory().create(configuration)) @@ -241,7 +241,7 @@ object SampleDatabases { override fun onUpgrade(db: SupportSQLiteDatabase, oldVersion: Int, newVersion: Int) = Unit - } + }, ) .build() return wrapOpenHelper(FrameworkSQLiteOpenHelperFactory().create(configuration)) diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/SqlStatements.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/SqlStatements.kt index 9bd2d624694..3015940c3b0 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/SqlStatements.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/SqlStatements.kt @@ -179,7 +179,7 @@ object SqlStatements { // Batch insert: one insertAll() runs all rows in a single transaction, vs. a naive per-row // loop. dao.insertAll( - List(HEAVY_ROW_COUNT) { SongEntity3(title = "song $it", artist = "artist $it") } + List(HEAVY_ROW_COUNT) { SongEntity3(title = "song $it", artist = "artist $it") }, ) dao.getAll().forEach { appWork("${it.id}:${it.title}:${it.artist}") } } diff --git a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/UiLoadScreen.kt b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/UiLoadScreen.kt index 6495726448d..5065773106c 100644 --- a/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/UiLoadScreen.kt +++ b/sentry-samples/sentry-samples-android/src/main/java/io/sentry/samples/android/sqlite/UiLoadScreen.kt @@ -44,7 +44,8 @@ fun UiLoadScreen(status: String, onClose: () -> Unit) { MaterialTheme { Surface { Box( - modifier = Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding().padding(24.dp) + modifier = + Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding().padding(24.dp), ) { Column( modifier = Modifier.align(Alignment.Center).fillMaxWidth().offset(y = (-48).dp), diff --git a/sentry-samples/sentry-samples-console-opentelemetry-noagent/src/main/java/io/sentry/samples/console/Main.java b/sentry-samples/sentry-samples-console-opentelemetry-noagent/src/main/java/io/sentry/samples/console/Main.java index 21438ee496c..24fd08924a1 100644 --- a/sentry-samples/sentry-samples-console-opentelemetry-noagent/src/main/java/io/sentry/samples/console/Main.java +++ b/sentry-samples/sentry-samples-console-opentelemetry-noagent/src/main/java/io/sentry/samples/console/Main.java @@ -26,14 +26,13 @@ public class Main { public static void main(String[] args) throws InterruptedException { AutoConfiguredOpenTelemetrySdk.builder() .setResultAsGlobal() - .addPropertiesSupplier( - () -> { - final Map properties = new HashMap<>(); - properties.put("otel.logs.exporter", "none"); - properties.put("otel.metrics.exporter", "none"); - properties.put("otel.traces.exporter", "none"); - return properties; - }) + .addPropertiesSupplier(() -> { + final Map properties = new HashMap<>(); + properties.put("otel.logs.exporter", "none"); + properties.put("otel.metrics.exporter", "none"); + properties.put("otel.traces.exporter", "none"); + return properties; + }) .build(); Sentry.addBreadcrumb( @@ -41,22 +40,20 @@ public static void main(String[] args) throws InterruptedException { // Data added to the root scope (no PushScope called up to this point) // The modifications done here will affect all events sent and will propagate to child scopes. - Sentry.configureScope( - scope -> { - scope.addEventProcessor(new SomeEventProcessor()); + Sentry.configureScope(scope -> { + scope.addEventProcessor(new SomeEventProcessor()); - scope.setExtra("SomeExtraInfo", "Some value for extra info"); - }); + scope.setExtra("SomeExtraInfo", "Some value for extra info"); + }); // Configures a scope which is only valid within the callback - Sentry.withScope( - scope -> { - scope.setLevel(SentryLevel.FATAL); - scope.setTransaction("main"); - - // This message includes the data set to the scope in this block: - Sentry.captureMessage("Fatal message!"); - }); + Sentry.withScope(scope -> { + scope.setLevel(SentryLevel.FATAL); + scope.setTransaction("main"); + + // This message includes the data set to the scope in this block: + Sentry.captureMessage("Fatal message!"); + }); // Only data added to the scope on `configureScope` above is included. Sentry.captureMessage("Some warning!", SentryLevel.WARNING); diff --git a/sentry-samples/sentry-samples-console-otlp/src/main/java/io/sentry/samples/console/Main.java b/sentry-samples/sentry-samples-console-otlp/src/main/java/io/sentry/samples/console/Main.java index 3a21e8220c6..0ade358b5c5 100644 --- a/sentry-samples/sentry-samples-console-otlp/src/main/java/io/sentry/samples/console/Main.java +++ b/sentry-samples/sentry-samples-console-otlp/src/main/java/io/sentry/samples/console/Main.java @@ -22,140 +22,130 @@ public static void main(String[] args) throws InterruptedException { // Configure OpenTelemetry SDK with Sentry OTLP propagator AutoConfiguredOpenTelemetrySdk.builder() .setResultAsGlobal() - .addPropertiesSupplier( - () -> { - final Map properties = new HashMap<>(); - properties.put("otel.logs.exporter", "none"); - properties.put("otel.metrics.exporter", "none"); - // OTLP traces exporter configuration - properties.put("otel.traces.exporter", "otlp,logging"); - properties.put( - "otel.exporter.otlp.traces.endpoint", - "https://o447951.ingest.us.sentry.io/api/5428563/integration/otlp/v1/traces"); - properties.put("otel.exporter.otlp.traces.protocol", "http/protobuf"); - properties.put( - "otel.exporter.otlp.traces.headers", - "x-sentry-auth=sentry sentry_key=502f25099c204a2fbf4cb16edc5975d1"); - properties.put("otel.propagators", "tracecontext,baggage,sentry"); - return properties; - }) + .addPropertiesSupplier(() -> { + final Map properties = new HashMap<>(); + properties.put("otel.logs.exporter", "none"); + properties.put("otel.metrics.exporter", "none"); + // OTLP traces exporter configuration + properties.put("otel.traces.exporter", "otlp,logging"); + properties.put( + "otel.exporter.otlp.traces.endpoint", + "https://o447951.ingest.us.sentry.io/api/5428563/integration/otlp/v1/traces"); + properties.put("otel.exporter.otlp.traces.protocol", "http/protobuf"); + properties.put( + "otel.exporter.otlp.traces.headers", + "x-sentry-auth=sentry sentry_key=502f25099c204a2fbf4cb16edc5975d1"); + properties.put("otel.propagators", "tracecontext,baggage,sentry"); + return properties; + }) .build(); - Sentry.init( - options -> { - // NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in - // your Sentry project/dashboard - options.setEnableExternalConfiguration(true); - options.setDsn( - "https://502f25099c204a2fbf4cb16edc5975d1@o447951.ingest.sentry.io/5428563"); - - // All events get assigned to the release. See more at - // https://docs.sentry.io/workflow/releases/ - options.setRelease("io.sentry.samples.console@3.0.0+1"); - - // Link Sentry events to OpenTelemetry spans - options.addEventProcessor(new OpenTelemetryOtlpEventProcessor()); - - // Modifications to event before it goes out. Could replace the event altogether - options.setBeforeSend( - (event, hint) -> { - // Drop an event altogether: - if (event.getTag("SomeTag") != null) { - return null; - } - return event; - }); - - options.setBeforeSendTransaction( - (transaction, hint) -> { - // Drop a transaction: - if (transaction.getTag("SomeTransactionTag") != null) { - return null; - } - - return transaction; - }); - - // Allows inspecting and modifying, returning a new or simply rejecting (returning null) - options.setBeforeBreadcrumb( - (breadcrumb, hint) -> { - // Don't add breadcrumbs with message containing: - if (breadcrumb.getMessage() != null - && breadcrumb.getMessage().contains("bad breadcrumb")) { - return null; - } - return breadcrumb; - }); - - // Record data being discarded, including the reason, type of data, and the number of - // items dropped - options.setOnDiscard( - (reason, category, number) -> { - // Only record the number of lost spans due to overflow conditions - if ((reason.equals(DiscardReason.CACHE_OVERFLOW) - || reason.equals(DiscardReason.QUEUE_OVERFLOW)) - && category.equals(DataCategory.Span)) { - numberOfDiscardedSpansDueToOverflow += number; - } - }); - - // Configure the background worker which sends events to sentry: - // Wait up to 5 seconds before shutdown while there are events to send. - options.setShutdownTimeoutMillis(5000); - - // Enable SDK logging with Debug level - options.setDebug(true); - // To change the verbosity, use: - // By default it's DEBUG. - // options.setDiagnosticLevel(SentryLevel.ERROR); - // A good option to have SDK debug log in prod is to use only level ERROR here. - - // Exclude frames from some packages from being "inApp" so are hidden by default in Sentry - // UI: - options.addInAppExclude("org.jboss"); - - // Include frames from our package - options.addInAppInclude("io.sentry.samples"); - - // Performance configuration options - // Set what percentage of traces should be collected - // options.setTracesSampleRate(1.0); // set 0.5 to send 50% of traces - - // Determine traces sample rate based on the sampling context - // options.setTracesSampler( - // context -> { - // // only 10% of transactions with "/product" prefix will be collected - // if (!context.getTransactionContext().getName().startsWith("/products")) - // { - // return 0.1; - // } else { - // return 0.5; - // } - // }); - - }); + Sentry.init(options -> { + // NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in + // your Sentry project/dashboard + options.setEnableExternalConfiguration(true); + options.setDsn("https://502f25099c204a2fbf4cb16edc5975d1@o447951.ingest.sentry.io/5428563"); + + // All events get assigned to the release. See more at + // https://docs.sentry.io/workflow/releases/ + options.setRelease("io.sentry.samples.console@3.0.0+1"); + + // Link Sentry events to OpenTelemetry spans + options.addEventProcessor(new OpenTelemetryOtlpEventProcessor()); + + // Modifications to event before it goes out. Could replace the event altogether + options.setBeforeSend((event, hint) -> { + // Drop an event altogether: + if (event.getTag("SomeTag") != null) { + return null; + } + return event; + }); + + options.setBeforeSendTransaction((transaction, hint) -> { + // Drop a transaction: + if (transaction.getTag("SomeTransactionTag") != null) { + return null; + } + + return transaction; + }); + + // Allows inspecting and modifying, returning a new or simply rejecting (returning null) + options.setBeforeBreadcrumb((breadcrumb, hint) -> { + // Don't add breadcrumbs with message containing: + if (breadcrumb.getMessage() != null && breadcrumb.getMessage().contains("bad breadcrumb")) { + return null; + } + return breadcrumb; + }); + + // Record data being discarded, including the reason, type of data, and the number of + // items dropped + options.setOnDiscard((reason, category, number) -> { + // Only record the number of lost spans due to overflow conditions + if ((reason.equals(DiscardReason.CACHE_OVERFLOW) + || reason.equals(DiscardReason.QUEUE_OVERFLOW)) + && category.equals(DataCategory.Span)) { + numberOfDiscardedSpansDueToOverflow += number; + } + }); + + // Configure the background worker which sends events to sentry: + // Wait up to 5 seconds before shutdown while there are events to send. + options.setShutdownTimeoutMillis(5000); + + // Enable SDK logging with Debug level + options.setDebug(true); + // To change the verbosity, use: + // By default it's DEBUG. + // options.setDiagnosticLevel(SentryLevel.ERROR); + // A good option to have SDK debug log in prod is to use only level ERROR here. + + // Exclude frames from some packages from being "inApp" so are hidden by default in Sentry + // UI: + options.addInAppExclude("org.jboss"); + + // Include frames from our package + options.addInAppInclude("io.sentry.samples"); + + // Performance configuration options + // Set what percentage of traces should be collected + // options.setTracesSampleRate(1.0); // set 0.5 to send 50% of traces + + // Determine traces sample rate based on the sampling context + // options.setTracesSampler( + // context -> { + // // only 10% of transactions with "/product" prefix will be collected + // if (!context.getTransactionContext().getName().startsWith("/products")) + // { + // return 0.1; + // } else { + // return 0.5; + // } + // }); + + }); Sentry.addBreadcrumb( "A 'bad breadcrumb' that will be rejected because of 'BeforeBreadcrumb callback above.'"); // Data added to the root scope (no PushScope called up to this point) // The modifications done here will affect all events sent and will propagate to child scopes. - Sentry.configureScope( - scope -> { - scope.addEventProcessor(new SomeEventProcessor()); + Sentry.configureScope(scope -> { + scope.addEventProcessor(new SomeEventProcessor()); - scope.setExtra("SomeExtraInfo", "Some value for extra info"); - }); + scope.setExtra("SomeExtraInfo", "Some value for extra info"); + }); // Configures a scope which is only valid within the callback - Sentry.withScope( - scope -> { - scope.setLevel(SentryLevel.FATAL); - scope.setTransaction("main"); - - // This message includes the data set to the scope in this block: - Sentry.captureMessage("Fatal message!"); - }); + Sentry.withScope(scope -> { + scope.setLevel(SentryLevel.FATAL); + scope.setTransaction("main"); + + // This message includes the data set to the scope in this block: + Sentry.captureMessage("Fatal message!"); + }); // Only data added to the scope on `configureScope` above is included. Sentry.captureMessage("Some warning!", SentryLevel.WARNING); diff --git a/sentry-samples/sentry-samples-console/src/main/java/io/sentry/samples/console/Main.java b/sentry-samples/sentry-samples-console/src/main/java/io/sentry/samples/console/Main.java index 2a45ef6902c..2d4e30a3a6d 100644 --- a/sentry-samples/sentry-samples-console/src/main/java/io/sentry/samples/console/Main.java +++ b/sentry-samples/sentry-samples-console/src/main/java/io/sentry/samples/console/Main.java @@ -21,121 +21,112 @@ public static void main(String[] args) throws InterruptedException { final boolean kafkaEnabled = kafkaBootstrapServers != null && !kafkaBootstrapServers.trim().isEmpty(); - Sentry.init( - options -> { - // NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in - // your Sentry project/dashboard - options.setEnableExternalConfiguration(true); - options.setDsn( - "https://502f25099c204a2fbf4cb16edc5975d1@o447951.ingest.sentry.io/5428563"); - - // All events get assigned to the release. See more at - // https://docs.sentry.io/workflow/releases/ - options.setRelease("io.sentry.samples.console@3.0.0+1"); - - // Modifications to event before it goes out. Could replace the event altogether - options.setBeforeSend( - (event, hint) -> { - // Drop an event altogether: - if (event.getTag("SomeTag") != null) { - return null; - } - return event; - }); - - options.setBeforeSendTransaction( - (transaction, hint) -> { - // Drop a transaction: - if (transaction.getTag("SomeTransactionTag") != null) { - return null; - } - - return transaction; - }); - - // Allows inspecting and modifying, returning a new or simply rejecting (returning null) - options.setBeforeBreadcrumb( - (breadcrumb, hint) -> { - // Don't add breadcrumbs with message containing: - if (breadcrumb.getMessage() != null - && breadcrumb.getMessage().contains("bad breadcrumb")) { - return null; - } - return breadcrumb; - }); - - // Record data being discarded, including the reason, type of data, and the number of - // items dropped - options.setOnDiscard( - (reason, category, number) -> { - // Only record the number of lost spans due to overflow conditions - if ((reason.equals(DiscardReason.CACHE_OVERFLOW) - || reason.equals(DiscardReason.QUEUE_OVERFLOW)) - && category.equals(DataCategory.Span)) { - numberOfDiscardedSpansDueToOverflow += number; - } - }); - - // Configure the background worker which sends events to sentry: - // Wait up to 5 seconds before shutdown while there are events to send. - options.setShutdownTimeoutMillis(5000); - - // Enable SDK logging with Debug level - options.setDebug(true); - // To change the verbosity, use: - // By default it's DEBUG. - // options.setDiagnosticLevel(SentryLevel.ERROR); - // A good option to have SDK debug log in prod is to use only level ERROR here. - - // Exclude frames from some packages from being "inApp" so are hidden by default in Sentry - // UI: - options.addInAppExclude("org.jboss"); - - // Include frames from our package - options.addInAppInclude("io.sentry.samples"); - - // Performance configuration options - // Set what percentage of traces should be collected - options.setTracesSampleRate(1.0); // set 0.5 to send 50% of traces - - // Enable cache tracing to create spans for cache operations - options.setEnableCacheTracing(true); - options.setEnableQueueTracing(kafkaEnabled); - - // Determine traces sample rate based on the sampling context - // options.setTracesSampler( - // context -> { - // // only 10% of transactions with "/product" prefix will be collected - // if (!context.getTransactionContext().getName().startsWith("/products")) - // { - // return 0.1; - // } else { - // return 0.5; - // } - // }); - }); + Sentry.init(options -> { + // NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in + // your Sentry project/dashboard + options.setEnableExternalConfiguration(true); + options.setDsn("https://502f25099c204a2fbf4cb16edc5975d1@o447951.ingest.sentry.io/5428563"); + + // All events get assigned to the release. See more at + // https://docs.sentry.io/workflow/releases/ + options.setRelease("io.sentry.samples.console@3.0.0+1"); + + // Modifications to event before it goes out. Could replace the event altogether + options.setBeforeSend((event, hint) -> { + // Drop an event altogether: + if (event.getTag("SomeTag") != null) { + return null; + } + return event; + }); + + options.setBeforeSendTransaction((transaction, hint) -> { + // Drop a transaction: + if (transaction.getTag("SomeTransactionTag") != null) { + return null; + } + + return transaction; + }); + + // Allows inspecting and modifying, returning a new or simply rejecting (returning null) + options.setBeforeBreadcrumb((breadcrumb, hint) -> { + // Don't add breadcrumbs with message containing: + if (breadcrumb.getMessage() != null && breadcrumb.getMessage().contains("bad breadcrumb")) { + return null; + } + return breadcrumb; + }); + + // Record data being discarded, including the reason, type of data, and the number of + // items dropped + options.setOnDiscard((reason, category, number) -> { + // Only record the number of lost spans due to overflow conditions + if ((reason.equals(DiscardReason.CACHE_OVERFLOW) + || reason.equals(DiscardReason.QUEUE_OVERFLOW)) + && category.equals(DataCategory.Span)) { + numberOfDiscardedSpansDueToOverflow += number; + } + }); + + // Configure the background worker which sends events to sentry: + // Wait up to 5 seconds before shutdown while there are events to send. + options.setShutdownTimeoutMillis(5000); + + // Enable SDK logging with Debug level + options.setDebug(true); + // To change the verbosity, use: + // By default it's DEBUG. + // options.setDiagnosticLevel(SentryLevel.ERROR); + // A good option to have SDK debug log in prod is to use only level ERROR here. + + // Exclude frames from some packages from being "inApp" so are hidden by default in Sentry + // UI: + options.addInAppExclude("org.jboss"); + + // Include frames from our package + options.addInAppInclude("io.sentry.samples"); + + // Performance configuration options + // Set what percentage of traces should be collected + options.setTracesSampleRate(1.0); // set 0.5 to send 50% of traces + + // Enable cache tracing to create spans for cache operations + options.setEnableCacheTracing(true); + options.setEnableQueueTracing(kafkaEnabled); + + // Determine traces sample rate based on the sampling context + // options.setTracesSampler( + // context -> { + // // only 10% of transactions with "/product" prefix will be collected + // if (!context.getTransactionContext().getName().startsWith("/products")) + // { + // return 0.1; + // } else { + // return 0.5; + // } + // }); + }); Sentry.addBreadcrumb( "A 'bad breadcrumb' that will be rejected because of 'BeforeBreadcrumb callback above.'"); // Data added to the root scope (no PushScope called up to this point) // The modifications done here will affect all events sent and will propagate to child scopes. - Sentry.configureScope( - scope -> { - scope.addEventProcessor(new SomeEventProcessor()); + Sentry.configureScope(scope -> { + scope.addEventProcessor(new SomeEventProcessor()); - scope.setExtra("SomeExtraInfo", "Some value for extra info"); - }); + scope.setExtra("SomeExtraInfo", "Some value for extra info"); + }); // Configures a scope which is only valid within the callback - Sentry.withScope( - scope -> { - scope.setLevel(SentryLevel.FATAL); - scope.setTransaction("main"); - - // This message includes the data set to the scope in this block: - Sentry.captureMessage("Fatal message!"); - }); + Sentry.withScope(scope -> { + scope.setLevel(SentryLevel.FATAL); + scope.setTransaction("main"); + + // This message includes the data set to the scope in this block: + Sentry.captureMessage("Fatal message!"); + }); // Only data added to the scope on `configureScope` above is included. Sentry.captureMessage("Some warning!", SentryLevel.WARNING); diff --git a/sentry-samples/sentry-samples-log4j2/build.gradle.kts b/sentry-samples/sentry-samples-log4j2/build.gradle.kts index ea8373c939f..6959418abc9 100644 --- a/sentry-samples/sentry-samples-log4j2/build.gradle.kts +++ b/sentry-samples/sentry-samples-log4j2/build.gradle.kts @@ -25,7 +25,7 @@ tasks.shadowJar { mergeServiceFiles() // Use Log4j2 cache transformer to properly handle plugin files transform( - com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer() + com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer(), ) } diff --git a/sentry-samples/sentry-samples-netflix-dgs/build.gradle.kts b/sentry-samples/sentry-samples-netflix-dgs/build.gradle.kts index 4503c1b6ebb..58be53439d8 100644 --- a/sentry-samples/sentry-samples-netflix-dgs/build.gradle.kts +++ b/sentry-samples/sentry-samples-netflix-dgs/build.gradle.kts @@ -31,8 +31,8 @@ dependencies { implementation(kotlin("stdlib-jdk8", getKotlinPluginVersion())) implementation("io.sentry:sentry-spring-boot-starter:$sentryVersion") implementation("io.sentry:sentry-graphql:$sentryVersion") - implementation(platform("com.netflix.graphql.dgs:graphql-dgs-platform-dependencies:4.9.2")) - implementation("com.netflix.graphql.dgs:graphql-dgs-subscriptions-websockets-autoconfigure:4.9.2") + implementation(platform(libs.netflix.dgs.platform)) + implementation(libs.netflix.dgs.subscriptions.websockets.autoconfigure) implementation("com.netflix.graphql.dgs:graphql-dgs-spring-boot-starter") testImplementation(libs.springboot.starter.test) { exclude(group = "org.junit.vintage", module = "junit-vintage-engine") @@ -50,7 +50,7 @@ tasks.shadowJar { MergeSpringMetadataAction( runtimeClasspath.get(), MergeSpringMetadataAction.DEFAULT_SPRING_METADATA_FILES, - ) + ), ) } diff --git a/sentry-samples/sentry-samples-netflix-dgs/src/main/java/io/sentry/samples/netflix/dgs/ActorsDataloader.java b/sentry-samples/sentry-samples-netflix-dgs/src/main/java/io/sentry/samples/netflix/dgs/ActorsDataloader.java index 89c2514fb59..572e51a4749 100644 --- a/sentry-samples/sentry-samples-netflix-dgs/src/main/java/io/sentry/samples/netflix/dgs/ActorsDataloader.java +++ b/sentry-samples/sentry-samples-netflix-dgs/src/main/java/io/sentry/samples/netflix/dgs/ActorsDataloader.java @@ -15,16 +15,15 @@ public class ActorsDataloader implements MappedBatchLoader { @Override public CompletionStage> load(Set keys) { - return CompletableFuture.supplyAsync( - () -> { - final @NotNull Map map = new HashMap<>(); - for (Integer key : keys) { - if (key != null && key == -1) { - throw new RuntimeException("Causing an error while loading actor"); - } - map.put(key, new Actor(key, "Name" + key)); - } - return map; - }); + return CompletableFuture.supplyAsync(() -> { + final @NotNull Map map = new HashMap<>(); + for (Integer key : keys) { + if (key != null && key == -1) { + throw new RuntimeException("Causing an error while loading actor"); + } + map.put(key, new Actor(key, "Name" + key)); + } + return map; + }); } } diff --git a/sentry-samples/sentry-samples-netflix-dgs/src/main/java/io/sentry/samples/netflix/dgs/ShowsDatafetcher.java b/sentry-samples/sentry-samples-netflix-dgs/src/main/java/io/sentry/samples/netflix/dgs/ShowsDatafetcher.java index bfd33364d65..ac8eee4235f 100644 --- a/sentry-samples/sentry-samples-netflix-dgs/src/main/java/io/sentry/samples/netflix/dgs/ShowsDatafetcher.java +++ b/sentry-samples/sentry-samples-netflix-dgs/src/main/java/io/sentry/samples/netflix/dgs/ShowsDatafetcher.java @@ -51,15 +51,13 @@ public Publisher notifyNewShow(Integer releaseYear) { } final @NotNull AtomicInteger counter = new AtomicInteger(2); return Flux.interval(Duration.ofSeconds(1)) - .map( - t -> { - int i = counter.incrementAndGet(); - if (releaseYear == -3 && i % 2 == 0) { - throw new RuntimeException( - "Causing error for subscription while producing an element"); - } - return new Show(i, "A new show has arrived " + i, releaseYear, 1); - }); + .map(t -> { + int i = counter.incrementAndGet(); + if (releaseYear == -3 && i % 2 == 0) { + throw new RuntimeException("Causing error for subscription while producing an element"); + } + return new Show(i, "A new show has arrived " + i, releaseYear, 1); + }); } @DgsData(parentType = "Show", field = "actor") diff --git a/sentry-samples/sentry-samples-openfeign/src/main/java/io/sentry/samples/openfeign/Main.java b/sentry-samples/sentry-samples-openfeign/src/main/java/io/sentry/samples/openfeign/Main.java index 2ce13a5263e..00bbb55a11f 100644 --- a/sentry-samples/sentry-samples-openfeign/src/main/java/io/sentry/samples/openfeign/Main.java +++ b/sentry-samples/sentry-samples-openfeign/src/main/java/io/sentry/samples/openfeign/Main.java @@ -14,29 +14,26 @@ public class Main { public static void main(String[] args) { - Sentry.init( - options -> { - // NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in - // your Sentry project/dashboard - options.setDsn( - "https://502f25099c204a2fbf4cb16edc5975d1@o447951.ingest.sentry.io/5428563"); - - // Performance configuration options - // Set what percentage of traces should be collected - options.setTracesSampleRate(1.0); // set 0.5 to send 50% of traces - }); + Sentry.init(options -> { + // NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in + // your Sentry project/dashboard + options.setDsn("https://502f25099c204a2fbf4cb16edc5975d1@o447951.ingest.sentry.io/5428563"); + + // Performance configuration options + // Set what percentage of traces should be collected + options.setTracesSampleRate(1.0); // set 0.5 to send 50% of traces + }); TodoApi todoApi = Feign.builder() .addCapability( - new SentryCapability( - (span, request, response) -> { - // attach tag to request with urls ending with /todos - if (request.url().endsWith("/todos")) { - span.setTag("tag-name", "tag-value"); - } - return span; - })) + new SentryCapability((span, request, response) -> { + // attach tag to request with urls ending with /todos + if (request.url().endsWith("/todos")) { + span.setTag("tag-name", "tag-value"); + } + return span; + })) .encoder(new GsonEncoder()) .decoder(new GsonDecoder()) .target(TodoApi.class, "https://jsonplaceholder.typicode.com/"); diff --git a/sentry-samples/sentry-samples-servlet/build.gradle.kts b/sentry-samples/sentry-samples-servlet/build.gradle.kts index bc4182c9786..65594ce69d0 100644 --- a/sentry-samples/sentry-samples-servlet/build.gradle.kts +++ b/sentry-samples/sentry-samples-servlet/build.gradle.kts @@ -16,7 +16,7 @@ java.targetCompatibility = JavaVersion.VERSION_11 dependencies { implementation("io.sentry:sentry-servlet:$sentryVersion") - implementation("javax.servlet:javax.servlet-api:4.0.1") + implementation(libs.servlet4.api) } tasks.withType().configureEach { useJUnitPlatform() } diff --git a/sentry-samples/sentry-samples-servlet/src/main/java/io/sentry/samples/servlet/SentryInitializer.java b/sentry-samples/sentry-samples-servlet/src/main/java/io/sentry/samples/servlet/SentryInitializer.java index 9f73b796e69..71932d18be6 100644 --- a/sentry-samples/sentry-samples-servlet/src/main/java/io/sentry/samples/servlet/SentryInitializer.java +++ b/sentry-samples/sentry-samples-servlet/src/main/java/io/sentry/samples/servlet/SentryInitializer.java @@ -15,74 +15,67 @@ public final class SentryInitializer implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { - Sentry.init( - options -> { - // NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in - // your Sentry project/dashboard - options.setDsn( - "https://502f25099c204a2fbf4cb16edc5975d1@o447951.ingest.sentry.io/5428563"); + Sentry.init(options -> { + // NOTE: Replace the test DSN below with YOUR OWN DSN to see the events from this app in + // your Sentry project/dashboard + options.setDsn("https://502f25099c204a2fbf4cb16edc5975d1@o447951.ingest.sentry.io/5428563"); - // disables shutdown hook, as Sentry has to be closed on application undeploy. - options.setEnableShutdownHook(false); + // disables shutdown hook, as Sentry has to be closed on application undeploy. + options.setEnableShutdownHook(false); - // All events get assigned to the release. See more at - // https://docs.sentry.io/workflow/releases/ - options.setRelease("io.sentry.samples.servlet@3.0.0+1"); + // All events get assigned to the release. See more at + // https://docs.sentry.io/workflow/releases/ + options.setRelease("io.sentry.samples.servlet@3.0.0+1"); - // Modifications to event before it goes out. Could replace the event altogether - options.setBeforeSend( - (event, hint) -> { - // Drop an event altogether: - if (event.getTag("SomeTag") != null) { - return null; - } - return event; - }); + // Modifications to event before it goes out. Could replace the event altogether + options.setBeforeSend((event, hint) -> { + // Drop an event altogether: + if (event.getTag("SomeTag") != null) { + return null; + } + return event; + }); - // Modifications to transaction before it goes out. Could replace the transaction - // altogether - options.setBeforeSendTransaction( - (transaction, hint) -> { - // Drop a transaction altogether: - if (transaction.getTag("SomeTag") != null) { - return null; - } - return transaction; - }); + // Modifications to transaction before it goes out. Could replace the transaction + // altogether + options.setBeforeSendTransaction((transaction, hint) -> { + // Drop a transaction altogether: + if (transaction.getTag("SomeTag") != null) { + return null; + } + return transaction; + }); - // Allows inspecting and modifying, returning a new or simply rejecting (returning null) - options.setBeforeBreadcrumb( - (breadcrumb, hint) -> { - // Don't add breadcrumbs with message containing: - if (breadcrumb.getMessage() != null - && breadcrumb.getMessage().contains("bad breadcrumb")) { - return null; - } - return breadcrumb; - }); + // Allows inspecting and modifying, returning a new or simply rejecting (returning null) + options.setBeforeBreadcrumb((breadcrumb, hint) -> { + // Don't add breadcrumbs with message containing: + if (breadcrumb.getMessage() != null && breadcrumb.getMessage().contains("bad breadcrumb")) { + return null; + } + return breadcrumb; + }); - // Record data being discarded, including the reason, type of data, and the number of - // items dropped - options.setOnDiscard( - (reason, category, number) -> { - // Only record the number of lost spans due to overflow conditions - if ((reason.equals(DiscardReason.CACHE_OVERFLOW) - || reason.equals(DiscardReason.QUEUE_OVERFLOW)) - && category.equals(DataCategory.Span)) { - numberOfDiscardedSpansDueToOverflow += number; - } - }); + // Record data being discarded, including the reason, type of data, and the number of + // items dropped + options.setOnDiscard((reason, category, number) -> { + // Only record the number of lost spans due to overflow conditions + if ((reason.equals(DiscardReason.CACHE_OVERFLOW) + || reason.equals(DiscardReason.QUEUE_OVERFLOW)) + && category.equals(DataCategory.Span)) { + numberOfDiscardedSpansDueToOverflow += number; + } + }); - // Configure the background worker which sends events to sentry: - // Wait up to 5 seconds before shutdown while there are events to send. - options.setShutdownTimeoutMillis(5000); + // Configure the background worker which sends events to sentry: + // Wait up to 5 seconds before shutdown while there are events to send. + options.setShutdownTimeoutMillis(5000); - // Enable SDK logging with Debug level - options.setDebug(true); + // Enable SDK logging with Debug level + options.setDebug(true); - // Include frames from our package - options.addInAppInclude("io.sentry.samples"); - }); + // Include frames from our package + options.addInAppInclude("io.sentry.samples"); + }); } @Override diff --git a/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/SecurityConfiguration.java b/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/SecurityConfiguration.java index 0f593a1b7c1..05e0102627c 100644 --- a/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/SecurityConfiguration.java +++ b/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/SecurityConfiguration.java @@ -20,9 +20,9 @@ public class SecurityConfiguration { @SuppressWarnings({"lgtm[java/spring-disabled-csrf-protection]", "removal"}) @Bean public SecurityFilterChain filterChain(final @NotNull HttpSecurity http) throws Exception { - return http.csrf((csrf) -> csrf.disable()) - .authorizeHttpRequests((r) -> r.anyRequest().authenticated()) - .httpBasic((h) -> {}) + return http.csrf(csrf -> csrf.disable()) + .authorizeHttpRequests(r -> r.anyRequest().authenticated()) + .httpBasic(h -> {}) .build(); } diff --git a/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/WebConfig.java b/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/WebConfig.java index e8dce9b35c4..8da3f75822d 100644 --- a/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/WebConfig.java +++ b/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/WebConfig.java @@ -24,6 +24,7 @@ public class WebConfig { * @return RestTemplate */ @Bean + @SuppressWarnings("removal") RestTemplate restTemplate(IScopes scopes) { RestTemplate restTemplate = new RestTemplate(); SentrySpanClientHttpRequestInterceptor sentryRestTemplateInterceptor = diff --git a/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/web/PersonService.java b/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/web/PersonService.java index fbe5b67ba4c..753d6eab482 100644 --- a/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/web/PersonService.java +++ b/sentry-samples/sentry-samples-spring-7/src/main/java/io/sentry/samples/spring7/web/PersonService.java @@ -7,8 +7,10 @@ @Service public class PersonService { + @SuppressWarnings("removal") private final RestTemplate restTemplate; + @SuppressWarnings("removal") public PersonService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } diff --git a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java index d12a40fb51d..4d67323c805 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java +++ b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java @@ -18,9 +18,9 @@ public class SecurityConfiguration { @SuppressWarnings({"lgtm[java/spring-disabled-csrf-protection]", "removal"}) @Bean public SecurityFilterChain filterChain(final @NotNull HttpSecurity http) throws Exception { - return http.csrf((csrf) -> csrf.disable()) - .authorizeHttpRequests((r) -> r.anyRequest().authenticated()) - .httpBasic((h) -> {}) + return http.csrf(csrf -> csrf.disable()) + .authorizeHttpRequests(r -> r.anyRequest().authenticated()) + .httpBasic(h -> {}) .build(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java index 13d97fa8442..904c60b0eb4 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java +++ b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java @@ -22,6 +22,7 @@ @SpringBootApplication @EnableCaching @EnableScheduling +@SuppressWarnings("removal") public class SentryDemoApplication { public static void main(String[] args) { SpringApplication.run(SentryDemoApplication.class, args); diff --git a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/TodoController.java index 0f71cca0419..387c7519438 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/TodoController.java @@ -12,6 +12,7 @@ import reactor.core.scheduler.Schedulers; @RestController +@SuppressWarnings("removal") public class TodoController { private final RestTemplate restTemplate; private final WebClient webClient; @@ -35,14 +36,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java index d43cde143d1..7e51d9e637d 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java index 2e1725ea644..1bff0a5e4f8 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java index 9ee0ef2c7a4..2fe87f66fe7 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-log4j2/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java @@ -20,22 +20,20 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .withOptions((builder) -> builder.setBatchingEnabled(true)) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .withOptions(builder -> builder.setBatchingEnabled(true)) + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java index d12a40fb51d..4d67323c805 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java @@ -18,9 +18,9 @@ public class SecurityConfiguration { @SuppressWarnings({"lgtm[java/spring-disabled-csrf-protection]", "removal"}) @Bean public SecurityFilterChain filterChain(final @NotNull HttpSecurity http) throws Exception { - return http.csrf((csrf) -> csrf.disable()) - .authorizeHttpRequests((r) -> r.anyRequest().authenticated()) - .httpBasic((h) -> {}) + return http.csrf(csrf -> csrf.disable()) + .authorizeHttpRequests(r -> r.anyRequest().authenticated()) + .httpBasic(h -> {}) .build(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java index 61e726defcb..80a550e7ef7 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java @@ -22,6 +22,7 @@ @SpringBootApplication @EnableScheduling +@SuppressWarnings("removal") public class SentryDemoApplication { public static void main(String[] args) { SpringApplication.run(SentryDemoApplication.class, args); diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/TodoController.java index d4fda10d0bd..fe3436122af 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/TodoController.java @@ -18,6 +18,7 @@ import reactor.core.scheduler.Schedulers; @RestController +@SuppressWarnings("removal") public class TodoController { private final RestTemplate restTemplate; private final WebClient webClient; @@ -54,14 +55,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java index d43cde143d1..7e51d9e637d 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java index 2e1725ea644..1bff0a5e4f8 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java index f8824abd07f..876076d5cd2 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java @@ -20,21 +20,19 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java index d12a40fb51d..4d67323c805 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java @@ -18,9 +18,9 @@ public class SecurityConfiguration { @SuppressWarnings({"lgtm[java/spring-disabled-csrf-protection]", "removal"}) @Bean public SecurityFilterChain filterChain(final @NotNull HttpSecurity http) throws Exception { - return http.csrf((csrf) -> csrf.disable()) - .authorizeHttpRequests((r) -> r.anyRequest().authenticated()) - .httpBasic((h) -> {}) + return http.csrf(csrf -> csrf.disable()) + .authorizeHttpRequests(r -> r.anyRequest().authenticated()) + .httpBasic(h -> {}) .build(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java index b00609ad9ac..77049f70a56 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java @@ -24,6 +24,7 @@ @SpringBootApplication @EnableCaching @EnableScheduling +@SuppressWarnings("removal") public class SentryDemoApplication { public static void main(String[] args) { SpringApplication.run(SentryDemoApplication.class, args); diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/TodoController.java index d4fda10d0bd..fe3436122af 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/TodoController.java @@ -18,6 +18,7 @@ import reactor.core.scheduler.Schedulers; @RestController +@SuppressWarnings("removal") public class TodoController { private final RestTemplate restTemplate; private final WebClient webClient; @@ -54,14 +55,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java index d43cde143d1..7e51d9e637d 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java index 2e1725ea644..1bff0a5e4f8 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java index f8824abd07f..876076d5cd2 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-opentelemetry/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java @@ -20,21 +20,19 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/SecurityConfiguration.java b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/SecurityConfiguration.java index 69d578f2d89..97db4357d4b 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/SecurityConfiguration.java +++ b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/SecurityConfiguration.java @@ -18,9 +18,9 @@ public class SecurityConfiguration { @SuppressWarnings({"lgtm[java/spring-disabled-csrf-protection]", "removal"}) @Bean public SecurityFilterChain filterChain(final @NotNull HttpSecurity http) throws Exception { - return http.csrf((csrf) -> csrf.disable()) - .authorizeHttpRequests((r) -> r.anyRequest().authenticated()) - .httpBasic((h) -> {}) + return http.csrf(csrf -> csrf.disable()) + .authorizeHttpRequests(r -> r.anyRequest().authenticated()) + .httpBasic(h -> {}) .build(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/SentryDemoApplication.java b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/SentryDemoApplication.java index 1bf622154d0..d0a958c536e 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/SentryDemoApplication.java +++ b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/SentryDemoApplication.java @@ -25,6 +25,7 @@ @SpringBootApplication @EnableCaching @EnableScheduling +@SuppressWarnings("removal") public class SentryDemoApplication { public static void main(String[] args) { SpringApplication.run(SentryDemoApplication.class, args); diff --git a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/TodoController.java index b083e6c1f88..60e617787d9 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/TodoController.java @@ -12,6 +12,7 @@ import reactor.core.scheduler.Schedulers; @RestController +@SuppressWarnings("removal") public class TodoController { private final RestTemplate restTemplate; private final WebClient webClient; @@ -35,14 +36,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/AssigneeController.java index ef4afb1a6f6..50feea99cc2 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/ProjectController.java index 7ec97bc12f2..9079965046a 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/TaskCreatorController.java index 94314cbfcac..c70d30d34bd 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-4-otlp/src/main/java/io/sentry/samples/spring/boot4/otlp/graphql/TaskCreatorController.java @@ -20,22 +20,20 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .withOptions((builder) -> builder.setBatchingEnabled(true)) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .withOptions(builder -> builder.setBatchingEnabled(true)) + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-4-webflux/src/main/java/io/sentry/samples/spring/boot4/PersonService.java b/sentry-samples/sentry-samples-spring-boot-4-webflux/src/main/java/io/sentry/samples/spring/boot4/PersonService.java index a45b9fa85c3..04117cd5b10 100644 --- a/sentry-samples/sentry-samples-spring-boot-4-webflux/src/main/java/io/sentry/samples/spring/boot4/PersonService.java +++ b/sentry-samples/sentry-samples-spring-boot-4-webflux/src/main/java/io/sentry/samples/spring/boot4/PersonService.java @@ -12,10 +12,9 @@ public class PersonService { Mono create(Person person) { return Mono.delay(Duration.ofMillis(100)) .publishOn(Schedulers.boundedElastic()) - .doOnNext( - __ -> { - Sentry.captureMessage("Creating person"); - }) + .doOnNext(__ -> { + Sentry.captureMessage("Creating person"); + }) .map(__ -> person); } } diff --git a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java index d12a40fb51d..4d67323c805 100644 --- a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java +++ b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/SecurityConfiguration.java @@ -18,9 +18,9 @@ public class SecurityConfiguration { @SuppressWarnings({"lgtm[java/spring-disabled-csrf-protection]", "removal"}) @Bean public SecurityFilterChain filterChain(final @NotNull HttpSecurity http) throws Exception { - return http.csrf((csrf) -> csrf.disable()) - .authorizeHttpRequests((r) -> r.anyRequest().authenticated()) - .httpBasic((h) -> {}) + return http.csrf(csrf -> csrf.disable()) + .authorizeHttpRequests(r -> r.anyRequest().authenticated()) + .httpBasic(h -> {}) .build(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java index 03688f1a84c..a8437db87c3 100644 --- a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java +++ b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/SentryDemoApplication.java @@ -23,6 +23,7 @@ @SpringBootApplication @EnableCaching @EnableScheduling +@SuppressWarnings("removal") public class SentryDemoApplication { public static void main(String[] args) { SpringApplication.run(SentryDemoApplication.class, args); diff --git a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/TodoController.java b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/TodoController.java index a24cf2bb3cc..5c458eb8f53 100644 --- a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/TodoController.java @@ -19,6 +19,7 @@ import tools.jackson.databind.ObjectMapper; @RestController +@SuppressWarnings("removal") public class TodoController { private final RestTemplate restTemplate; private final WebClient webClient; @@ -51,14 +52,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java index d43cde143d1..7e51d9e637d 100644 --- a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java index 2e1725ea644..1bff0a5e4f8 100644 --- a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java index 9ee0ef2c7a4..2fe87f66fe7 100644 --- a/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-4/src/main/java/io/sentry/samples/spring/boot4/graphql/TaskCreatorController.java @@ -20,22 +20,20 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .withOptions((builder) -> builder.setBatchingEnabled(true)) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .withOptions(builder -> builder.setBatchingEnabled(true)) + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java index 987d516936b..74d03f8c4ce 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java @@ -35,14 +35,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java index 6fdf96506c8..3d46d0f096a 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java index 63790bca628..5a8c38efb43 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java index 434a4822084..3968b2ed26c 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-log4j2/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java @@ -20,22 +20,20 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .withOptions((builder) -> builder.setBatchingEnabled(true)) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .withOptions(builder -> builder.setBatchingEnabled(true)) + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java index 0fa450a879c..4aa57377b28 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java @@ -54,14 +54,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java index 6fdf96506c8..3d46d0f096a 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java index 63790bca628..5a8c38efb43 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java index cb6677c0c37..dd930f5566b 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java @@ -20,21 +20,19 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java index 0fa450a879c..4aa57377b28 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java @@ -54,14 +54,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java index 6fdf96506c8..3d46d0f096a 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java index 63790bca628..5a8c38efb43 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java index cb6677c0c37..dd930f5566b 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta-opentelemetry/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java @@ -20,21 +20,19 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java b/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java index db0e42e4ab1..f279cadfbe4 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/TodoController.java @@ -51,14 +51,13 @@ Todo todoWebClient(@PathVariable Long id) { return SentryReactorUtils.withSentry( Mono.just(true) .publishOn(Schedulers.boundedElastic()) - .flatMap( - x -> - webClient - .get() - .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) - .retrieve() - .bodyToMono(Todo.class) - .map(response -> response))) + .flatMap(x -> + webClient + .get() + .uri("https://jsonplaceholder.typicode.com/todos/{id}", id) + .retrieve() + .bodyToMono(Todo.class) + .map(response -> response))) .block(); } diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java index 6fdf96506c8..3d46d0f096a 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java index 63790bca628..5a8c38efb43 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java index 434a4822084..3968b2ed26c 100644 --- a/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/graphql/TaskCreatorController.java @@ -20,22 +20,20 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .withOptions((builder) -> builder.setBatchingEnabled(true)) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .withOptions(builder -> builder.setBatchingEnabled(true)) + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/build.gradle.kts b/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/build.gradle.kts index 9234da89f4c..84b6f95d75f 100644 --- a/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/build.gradle.kts +++ b/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/build.gradle.kts @@ -78,7 +78,7 @@ tasks.shadowJar { MergeSpringMetadataAction( runtimeClasspath.get(), MergeSpringMetadataAction.DEFAULT_SPRING_METADATA_FILES, - ) + ), ) } diff --git a/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java index c88984c261f..f9e6607aa8d 100644 --- a/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java index 70e65ad7e5e..4abfc4483db 100644 --- a/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java index bbf123f84c3..3de1434c00e 100644 --- a/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-opentelemetry-noagent/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java @@ -20,21 +20,19 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-opentelemetry/build.gradle.kts b/sentry-samples/sentry-samples-spring-boot-opentelemetry/build.gradle.kts index c67bdbb33fe..87495ef2ebf 100644 --- a/sentry-samples/sentry-samples-spring-boot-opentelemetry/build.gradle.kts +++ b/sentry-samples/sentry-samples-spring-boot-opentelemetry/build.gradle.kts @@ -77,7 +77,7 @@ tasks.shadowJar { MergeSpringMetadataAction( runtimeClasspath.get(), MergeSpringMetadataAction.DEFAULT_SPRING_METADATA_FILES, - ) + ), ) } diff --git a/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java index c88984c261f..f9e6607aa8d 100644 --- a/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java index 70e65ad7e5e..4abfc4483db 100644 --- a/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java index bbf123f84c3..3de1434c00e 100644 --- a/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot-opentelemetry/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java @@ -20,21 +20,19 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-samples/sentry-samples-spring-boot-webflux-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/PersonService.java b/sentry-samples/sentry-samples-spring-boot-webflux-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/PersonService.java index 75b0e38b125..23999d48775 100644 --- a/sentry-samples/sentry-samples-spring-boot-webflux-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/PersonService.java +++ b/sentry-samples/sentry-samples-spring-boot-webflux-jakarta/src/main/java/io/sentry/samples/spring/boot/jakarta/PersonService.java @@ -12,10 +12,9 @@ public class PersonService { Mono create(Person person) { return Mono.delay(Duration.ofMillis(100)) .publishOn(Schedulers.boundedElastic()) - .doOnNext( - __ -> { - Sentry.captureMessage("Creating person"); - }) + .doOnNext(__ -> { + Sentry.captureMessage("Creating person"); + }) .map(__ -> person); } } diff --git a/sentry-samples/sentry-samples-spring-boot-webflux/build.gradle.kts b/sentry-samples/sentry-samples-spring-boot-webflux/build.gradle.kts index 07eca851939..d5eacc41c64 100644 --- a/sentry-samples/sentry-samples-spring-boot-webflux/build.gradle.kts +++ b/sentry-samples/sentry-samples-spring-boot-webflux/build.gradle.kts @@ -54,7 +54,7 @@ tasks.shadowJar { MergeSpringMetadataAction( runtimeClasspath.get(), MergeSpringMetadataAction.DEFAULT_SPRING_METADATA_FILES, - ) + ), ) } diff --git a/sentry-samples/sentry-samples-spring-boot/build.gradle.kts b/sentry-samples/sentry-samples-spring-boot/build.gradle.kts index 13e91956a2d..14d69f3bfd4 100644 --- a/sentry-samples/sentry-samples-spring-boot/build.gradle.kts +++ b/sentry-samples/sentry-samples-spring-boot/build.gradle.kts @@ -85,7 +85,7 @@ tasks.shadowJar { MergeSpringMetadataAction( runtimeClasspath.get(), MergeSpringMetadataAction.DEFAULT_SPRING_METADATA_FILES, - ) + ), ) } diff --git a/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java b/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java index c88984c261f..f9e6607aa8d 100644 --- a/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java +++ b/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/AssigneeController.java @@ -14,21 +14,18 @@ public class AssigneeController { @BatchMapping(typeName = "Task", field = "assignee") public Mono> assignee( final @NotNull Set tasks) { - return Mono.fromCallable( - () -> { - final @NotNull Map map = - new HashMap<>(); - for (final @NotNull ProjectController.Task task : tasks) { - if ("Acrash".equalsIgnoreCase(task.assigneeId)) { - throw new RuntimeException("Causing an error while loading assignee"); - } - if (task.assigneeId != null) { - map.put( - task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); - } - } + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (final @NotNull ProjectController.Task task : tasks) { + if ("Acrash".equalsIgnoreCase(task.assigneeId)) { + throw new RuntimeException("Causing an error while loading assignee"); + } + if (task.assigneeId != null) { + map.put(task, new ProjectController.Assignee(task.assigneeId, "Name" + task.assigneeId)); + } + } - return map; - }); + return map; + }); } } diff --git a/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java b/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java index 70e65ad7e5e..4abfc4483db 100644 --- a/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java +++ b/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/ProjectController.java @@ -76,14 +76,13 @@ public Flux notifyNewTask(@Argument String projectSlug) { final String creatorId = "creatorcrash".equalsIgnoreCase(projectSlug) ? "Ccrash" : "C1"; final @NotNull AtomicInteger counter = new AtomicInteger(1000); return Flux.interval(Duration.ofSeconds(1)) - .map( - num -> { - int i = counter.incrementAndGet(); - if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { - throw new RuntimeException("causing produce error for subscription"); - } - return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); - }); + .map(num -> { + int i = counter.incrementAndGet(); + if ("produceerror".equalsIgnoreCase(projectSlug) && i % 2 == 0) { + throw new RuntimeException("causing produce error for subscription"); + } + return new Task("T" + i, "A new task arrived ", assigneeId, creatorId); + }); } public static class Task { diff --git a/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java b/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java index bbf123f84c3..3de1434c00e 100644 --- a/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java +++ b/sentry-samples/sentry-samples-spring-boot/src/main/java/io/sentry/samples/spring/boot/graphql/TaskCreatorController.java @@ -20,21 +20,19 @@ public TaskCreatorController(final BatchLoaderRegistry batchLoaderRegistry) { // using mapped BatchLoader to not have to deal with correct ordering of items batchLoaderRegistry .forTypePair(String.class, ProjectController.Creator.class) - .registerMappedBatchLoader( - (Set keys, BatchLoaderEnvironment env) -> { - return Mono.fromCallable( - () -> { - final @NotNull Map map = new HashMap<>(); - for (String key : keys) { - if ("Ccrash".equalsIgnoreCase(key)) { - throw new RuntimeException("Causing an error while loading creator"); - } - map.put(key, new ProjectController.Creator(key, "Name" + key)); - } + .registerMappedBatchLoader((Set keys, BatchLoaderEnvironment env) -> { + return Mono.fromCallable(() -> { + final @NotNull Map map = new HashMap<>(); + for (String key : keys) { + if ("Ccrash".equalsIgnoreCase(key)) { + throw new RuntimeException("Causing an error while loading creator"); + } + map.put(key, new ProjectController.Creator(key, "Name" + key)); + } - return map; - }); - }); + return map; + }); + }); } @SchemaMapping(typeName = "Task") diff --git a/sentry-servlet-jakarta/src/main/java/io/sentry/servlet/jakarta/SentryServletRequestListener.java b/sentry-servlet-jakarta/src/main/java/io/sentry/servlet/jakarta/SentryServletRequestListener.java index 909aee9b003..6c0d5821f8f 100644 --- a/sentry-servlet-jakarta/src/main/java/io/sentry/servlet/jakarta/SentryServletRequestListener.java +++ b/sentry-servlet-jakarta/src/main/java/io/sentry/servlet/jakarta/SentryServletRequestListener.java @@ -57,11 +57,10 @@ public void requestInitialized(@NotNull ServletRequestEvent servletRequestEvent) scopes.addBreadcrumb( Breadcrumb.http(httpRequest.getRequestURI(), httpRequest.getMethod()), hint); - scopes.configureScope( - scope -> { - scope.addEventProcessor( - new SentryRequestHttpServletRequestProcessor(httpRequest, scopes.getOptions())); - }); + scopes.configureScope(scope -> { + scope.addEventProcessor( + new SentryRequestHttpServletRequestProcessor(httpRequest, scopes.getOptions())); + }); } } } diff --git a/sentry-servlet-jakarta/src/test/kotlin/io/sentry/servlet/jakarta/SentryServletContainerInitializerTest.kt b/sentry-servlet-jakarta/src/test/kotlin/io/sentry/servlet/jakarta/SentryServletContainerInitializerTest.kt index 3cd7fcab15c..aded31fc379 100644 --- a/sentry-servlet-jakarta/src/test/kotlin/io/sentry/servlet/jakarta/SentryServletContainerInitializerTest.kt +++ b/sentry-servlet-jakarta/src/test/kotlin/io/sentry/servlet/jakarta/SentryServletContainerInitializerTest.kt @@ -19,7 +19,7 @@ class SentryServletContainerInitializerTest { .addListener( check { it: Class -> assertEquals(SentryServletRequestListener::class.java, it) - } + }, ) } } diff --git a/sentry-servlet/src/main/java/io/sentry/servlet/SentryServletRequestListener.java b/sentry-servlet/src/main/java/io/sentry/servlet/SentryServletRequestListener.java index 1874cacc66b..d2abd13bb21 100644 --- a/sentry-servlet/src/main/java/io/sentry/servlet/SentryServletRequestListener.java +++ b/sentry-servlet/src/main/java/io/sentry/servlet/SentryServletRequestListener.java @@ -57,11 +57,10 @@ public void requestInitialized(@NotNull ServletRequestEvent servletRequestEvent) scopes.addBreadcrumb( Breadcrumb.http(httpRequest.getRequestURI(), httpRequest.getMethod()), hint); - scopes.configureScope( - scope -> { - scope.addEventProcessor( - new SentryRequestHttpServletRequestProcessor(httpRequest, scopes.getOptions())); - }); + scopes.configureScope(scope -> { + scope.addEventProcessor( + new SentryRequestHttpServletRequestProcessor(httpRequest, scopes.getOptions())); + }); } } } diff --git a/sentry-servlet/src/test/kotlin/io/sentry/servlet/SentryServletContainerInitializerTest.kt b/sentry-servlet/src/test/kotlin/io/sentry/servlet/SentryServletContainerInitializerTest.kt index 5000e4f2411..5000e8f874e 100644 --- a/sentry-servlet/src/test/kotlin/io/sentry/servlet/SentryServletContainerInitializerTest.kt +++ b/sentry-servlet/src/test/kotlin/io/sentry/servlet/SentryServletContainerInitializerTest.kt @@ -19,7 +19,7 @@ class SentryServletContainerInitializerTest { .addListener( check { it: Class -> assertThat(it).isEqualTo(SentryServletRequestListener::class.java) - } + }, ) } } diff --git a/sentry-spring-7/src/integrationTest/kotlin/io/sentry/spring7/integrationtest/MetricsIntegrationTest.kt b/sentry-spring-7/src/integrationTest/kotlin/io/sentry/spring7/integrationtest/MetricsIntegrationTest.kt index c3178cb1188..b1a0f7e7dd7 100644 --- a/sentry-spring-7/src/integrationTest/kotlin/io/sentry/spring7/integrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-7/src/integrationTest/kotlin/io/sentry/spring7/integrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/SentrySpringFilter.java b/sentry-spring-7/src/main/java/io/sentry/spring7/SentrySpringFilter.java index 869eb1e3f5b..6abb989637e 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/SentrySpringFilter.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/SentrySpringFilter.java @@ -84,23 +84,22 @@ protected void doFilterInternal( private void configureScope( final @NotNull IScopes scopes, final @NotNull HttpServletRequest request) { try { - scopes.configureScope( - scope -> { - // set basic request information on the scope - scope.setRequest(requestResolver.resolveSentryRequest(request)); - // transaction name is known at the later stage of request processing, thus it cannot - // be set on the scope - scope.addEventProcessor( - new SentryRequestHttpServletRequestProcessor( - transactionNameProvider, request, scopes.getOptions().getLogger())); - // only if request caches body, add an event processor that sets body on the event - // body is not on the scope, to avoid using memory when no event is triggered during - // request processing - if (request instanceof ContentCachingRequestWrapper) { - scope.addEventProcessor( - new RequestBodyExtractingEventProcessor(request, scopes.getOptions())); - } - }); + scopes.configureScope(scope -> { + // set basic request information on the scope + scope.setRequest(requestResolver.resolveSentryRequest(request)); + // transaction name is known at the later stage of request processing, thus it cannot + // be set on the scope + scope.addEventProcessor( + new SentryRequestHttpServletRequestProcessor( + transactionNameProvider, request, scopes.getOptions().getLogger())); + // only if request caches body, add an event processor that sets body on the event + // body is not on the scope, to avoid using memory when no event is triggered during + // request processing + if (request instanceof ContentCachingRequestWrapper) { + scope.addEventProcessor( + new RequestBodyExtractingEventProcessor(request, scopes.getOptions())); + } + }); } catch (Throwable e) { scopes .getOptions() diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/cache/SentryCacheWrapper.java b/sentry-spring-7/src/main/java/io/sentry/spring7/cache/SentryCacheWrapper.java index e5cb9ce87e9..7d5b9b7392b 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/cache/SentryCacheWrapper.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/cache/SentryCacheWrapper.java @@ -128,17 +128,16 @@ public SentryCacheWrapper(final @NotNull Cache delegate, final @NotNull IScopes span.finish(); return null; } - return result.whenComplete( - (value, throwable) -> { - if (throwable != null) { - span.setStatus(SpanStatus.INTERNAL_ERROR); - span.setThrowable(throwable); - } else { - span.setData(SpanDataConvention.CACHE_HIT, value != null); - span.setStatus(SpanStatus.OK); - } - span.finish(); - }); + return result.whenComplete((value, throwable) -> { + if (throwable != null) { + span.setStatus(SpanStatus.INTERNAL_ERROR); + span.setThrowable(throwable); + } else { + span.setData(SpanDataConvention.CACHE_HIT, value != null); + span.setStatus(SpanStatus.OK); + } + span.finish(); + }); } @Override @@ -164,18 +163,17 @@ public CompletableFuture retrieve( span.finish(); throw e; } - return result.whenComplete( - (value, throwable) -> { - if (throwable != null) { - span.setStatus(SpanStatus.INTERNAL_ERROR); - span.setThrowable(throwable); - } else { - span.setData(SpanDataConvention.CACHE_HIT, !loaderInvoked.get()); - span.setData(SpanDataConvention.CACHE_WRITE, loaderInvoked.get()); - span.setStatus(SpanStatus.OK); - } - span.finish(); - }); + return result.whenComplete((value, throwable) -> { + if (throwable != null) { + span.setStatus(SpanStatus.INTERNAL_ERROR); + span.setThrowable(throwable); + } else { + span.setData(SpanDataConvention.CACHE_HIT, !loaderInvoked.get()); + span.setData(SpanDataConvention.CACHE_WRITE, loaderInvoked.get()); + span.setStatus(SpanStatus.OK); + } + span.finish(); + }); } @Override diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentryBatchLoaderRegistry.java b/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentryBatchLoaderRegistry.java index 647da383818..461082dbad1 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentryBatchLoaderRegistry.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentryBatchLoaderRegistry.java @@ -87,23 +87,21 @@ public BatchLoaderRegistry.RegistrationSpec withOptions(DataLoaderOptions @Override public void registerBatchLoader(BiFunction, BatchLoaderEnvironment, Flux> loader) { - delegate.registerBatchLoader( - (keys, batchLoaderEnvironment) -> { - scopesFromContext(batchLoaderEnvironment) - .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); - return loader.apply(keys, batchLoaderEnvironment); - }); + delegate.registerBatchLoader((keys, batchLoaderEnvironment) -> { + scopesFromContext(batchLoaderEnvironment) + .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); + return loader.apply(keys, batchLoaderEnvironment); + }); } @Override public void registerMappedBatchLoader( BiFunction, BatchLoaderEnvironment, Mono>> loader) { - delegate.registerMappedBatchLoader( - (keys, batchLoaderEnvironment) -> { - scopesFromContext(batchLoaderEnvironment) - .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); - return loader.apply(keys, batchLoaderEnvironment); - }); + delegate.registerMappedBatchLoader((keys, batchLoaderEnvironment) -> { + scopesFromContext(batchLoaderEnvironment) + .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); + return loader.apply(keys, batchLoaderEnvironment); + }); } private @NotNull IScopes scopesFromContext(final @NotNull BatchLoaderEnvironment environment) { diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentryDgsSubscriptionHandler.java b/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentryDgsSubscriptionHandler.java index baf16ec71bc..46ffd401d71 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentryDgsSubscriptionHandler.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentryDgsSubscriptionHandler.java @@ -22,12 +22,11 @@ public SentryDgsSubscriptionHandler() { final @NotNull InstrumentationFieldFetchParameters parameters) { if (result instanceof Flux) { final @NotNull Flux flux = (Flux) result; - return flux.doOnError( - throwable -> { - final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = - new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); - exceptionReporter.captureThrowable(throwable, exceptionDetails, null); - }); + return flux.doOnError(throwable -> { + final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = + new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); + exceptionReporter.captureThrowable(throwable, exceptionDetails, null); + }); } return result; } diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentrySpringSubscriptionHandler.java b/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentrySpringSubscriptionHandler.java index e0b091d494e..d6eebbffc09 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentrySpringSubscriptionHandler.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/graphql/SentrySpringSubscriptionHandler.java @@ -18,17 +18,15 @@ public final class SentrySpringSubscriptionHandler implements SentrySubscription final @NotNull InstrumentationFieldFetchParameters parameters) { if (result instanceof Flux) { final @NotNull Flux flux = (Flux) result; - return flux.doOnError( - throwable -> { - final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = - new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); - if (throwable instanceof SubscriptionPublisherException - && throwable.getCause() != null) { - exceptionReporter.captureThrowable(throwable.getCause(), exceptionDetails, null); - } else { - exceptionReporter.captureThrowable(throwable, exceptionDetails, null); - } - }); + return flux.doOnError(throwable -> { + final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = + new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); + if (throwable instanceof SubscriptionPublisherException && throwable.getCause() != null) { + exceptionReporter.captureThrowable(throwable.getCause(), exceptionDetails, null); + } else { + exceptionReporter.captureThrowable(throwable, exceptionDetails, null); + } + }); } return result; } diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/tracing/SentrySpanClientWebRequestFilter.java b/sentry-spring-7/src/main/java/io/sentry/spring7/tracing/SentrySpanClientWebRequestFilter.java index 9ab8520484d..2515288721c 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/tracing/SentrySpanClientWebRequestFilter.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/tracing/SentrySpanClientWebRequestFilter.java @@ -58,22 +58,20 @@ public SentrySpanClientWebRequestFilter(final @NotNull IScopes scopes) { final @NotNull ClientRequest modifiedRequest = maybeAddTracingHeaders(request, span); return next.exchange(modifiedRequest) - .flatMap( - response -> { - span.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, response.statusCode().value()); - span.setStatus(SpanStatus.fromHttpStatusCode(response.statusCode().value())); - addBreadcrumb(request, response); - span.finish(); - return Mono.just(response); - }) - .onErrorMap( - throwable -> { - span.setThrowable(throwable); - span.setStatus(SpanStatus.INTERNAL_ERROR); - addBreadcrumb(request, null); - span.finish(); - return throwable; - }); + .flatMap(response -> { + span.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, response.statusCode().value()); + span.setStatus(SpanStatus.fromHttpStatusCode(response.statusCode().value())); + addBreadcrumb(request, response); + span.finish(); + return Mono.just(response); + }) + .onErrorMap(throwable -> { + span.setThrowable(throwable); + span.setStatus(SpanStatus.INTERNAL_ERROR); + addBreadcrumb(request, null); + span.finish(); + return throwable; + }); } private @NotNull ClientRequest maybeAddTracingHeaders( @@ -98,11 +96,10 @@ public SentrySpanClientWebRequestFilter(final @NotNull IScopes scopes) { final @Nullable BaggageHeader baggageHeader = tracingHeaders.getBaggageHeader(); if (baggageHeader != null) { - requestBuilder.headers( - httpHeaders -> { - httpHeaders.remove(BaggageHeader.BAGGAGE_HEADER); - httpHeaders.add(baggageHeader.getName(), baggageHeader.getValue()); - }); + requestBuilder.headers(httpHeaders -> { + httpHeaders.remove(BaggageHeader.BAGGAGE_HEADER); + httpHeaders.add(baggageHeader.getName(), baggageHeader.getValue()); + }); } } diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/AbstractSentryWebFilter.java b/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/AbstractSentryWebFilter.java index 898c9fd5937..729dacbb0e8 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/AbstractSentryWebFilter.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/AbstractSentryWebFilter.java @@ -128,10 +128,9 @@ private void finishTransaction(ServerWebExchange exchange, ITransaction transact if (statusCode != null) { transaction .getContexts() - .withResponse( - (sentryResponse) -> { - sentryResponse.setStatusCode(statusCode.value()); - }); + .withResponse(sentryResponse -> { + sentryResponse.setStatusCode(statusCode.value()); + }); if (transaction.getStatus() == null) { transaction.setStatus(SpanStatus.fromHttpStatusCode(statusCode.value())); } diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebExceptionHandler.java b/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebExceptionHandler.java index 421cb7a2a90..6716a1d1272 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebExceptionHandler.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebExceptionHandler.java @@ -43,30 +43,28 @@ public SentryWebExceptionHandler(final @NotNull IScopes scopes) { return SentryReactorUtils.withSentryScopes( Mono.just(ex) - .map( - it -> { - if (!(ex instanceof ResponseStatusException)) { - final Mechanism mechanism = new Mechanism(); - mechanism.setType(MECHANISM_TYPE); - mechanism.setHandled(false); - final Throwable throwable = - new ExceptionMechanismException(mechanism, ex, Thread.currentThread()); - final SentryEvent event = new SentryEvent(throwable); - event.setLevel(SentryLevel.FATAL); - event.setTransaction( - TransactionNameProvider.provideTransactionName(serverWebExchange)); + .map(it -> { + if (!(ex instanceof ResponseStatusException)) { + final Mechanism mechanism = new Mechanism(); + mechanism.setType(MECHANISM_TYPE); + mechanism.setHandled(false); + final Throwable throwable = + new ExceptionMechanismException(mechanism, ex, Thread.currentThread()); + final SentryEvent event = new SentryEvent(throwable); + event.setLevel(SentryLevel.FATAL); + event.setTransaction( + TransactionNameProvider.provideTransactionName(serverWebExchange)); - final Hint hint = new Hint(); - hint.set(WEBFLUX_EXCEPTION_HANDLER_REQUEST, serverWebExchange.getRequest()); - hint.set( - WEBFLUX_EXCEPTION_HANDLER_RESPONSE, serverWebExchange.getResponse()); - hint.set(WEBFLUX_EXCEPTION_HANDLER_EXCHANGE, serverWebExchange); + final Hint hint = new Hint(); + hint.set(WEBFLUX_EXCEPTION_HANDLER_REQUEST, serverWebExchange.getRequest()); + hint.set(WEBFLUX_EXCEPTION_HANDLER_RESPONSE, serverWebExchange.getResponse()); + hint.set(WEBFLUX_EXCEPTION_HANDLER_EXCHANGE, serverWebExchange); - scopes.captureEvent(event, hint); - } + scopes.captureEvent(event, hint); + } - return it; - }), + return it; + }), scopesToUse) .flatMap(it -> Mono.error(ex)); } diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebFilter.java b/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebFilter.java index 508ddbaf7ce..721ce06bb64 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebFilter.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebFilter.java @@ -36,10 +36,9 @@ public Mono filter( .filter(serverWebExchange) .doFinally(__ -> doFinally(serverWebExchange, requestScopes, transaction)) .doOnError(e -> doOnError(transaction, e)) - .doFirst( - () -> { - Sentry.setCurrentScopes(requestScopes); - doFirst(serverWebExchange, requestScopes); - }); + .doFirst(() -> { + Sentry.setCurrentScopes(requestScopes); + doFirst(serverWebExchange, requestScopes); + }); } } diff --git a/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebFilterWithThreadLocalAccessor.java b/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebFilterWithThreadLocalAccessor.java index ff6c61353a9..4fd67cf876b 100644 --- a/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebFilterWithThreadLocalAccessor.java +++ b/sentry-spring-7/src/main/java/io/sentry/spring7/webflux/SentryWebFilterWithThreadLocalAccessor.java @@ -30,21 +30,17 @@ public Mono filter( return SentryReactorUtils.withSentryForkedRoots( webFilterChain .filter(serverWebExchange) - .doFinally( - __ -> - doFinally( - serverWebExchange, - Sentry.getCurrentScopes(), - transactionContainer.transaction)) + .doFinally(__ -> + doFinally( + serverWebExchange, Sentry.getCurrentScopes(), transactionContainer.transaction)) .doOnError(e -> doOnError(transactionContainer.transaction, e)) - .doFirst( - () -> { - doFirst(serverWebExchange, Sentry.getCurrentScopes()); - final ITransaction transaction = - maybeStartTransaction( - Sentry.getCurrentScopes(), serverWebExchange.getRequest(), TRACE_ORIGIN); - transactionContainer.transaction = transaction; - })); + .doFirst(() -> { + doFirst(serverWebExchange, Sentry.getCurrentScopes()); + final ITransaction transaction = + maybeStartTransaction( + Sentry.getCurrentScopes(), serverWebExchange.getRequest(), TRACE_ORIGIN); + transactionContainer.transaction = transaction; + })); } private static class TransactionContainer { diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/EnableSentryTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/EnableSentryTest.kt index d6588ad4013..4c782ef7a64 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/EnableSentryTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/EnableSentryTest.kt @@ -84,7 +84,7 @@ class EnableSentryTest { fun `creates SentryExceptionResolver with order set in the @EnableSentry annotation`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithExceptionResolverOrderIntegerMaxValue::class.java) + UserConfigurations.of(AppConfigWithExceptionResolverOrderIntegerMaxValue::class.java), ) .run { assertThat(it).hasSingleBean(SentryExceptionResolver::class.java) @@ -98,7 +98,7 @@ class EnableSentryTest { fun `configures custom TracesSamplerCallback`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithCustomTracesSamplerCallback::class.java) + UserConfigurations.of(AppConfigWithCustomTracesSamplerCallback::class.java), ) .run { val options = it.getBean(SentryOptions::class.java) @@ -143,7 +143,7 @@ class EnableSentryTest { fun `configures custom before breadcrumb callback`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithCustomBeforeBreadcrumbCallback::class.java) + UserConfigurations.of(AppConfigWithCustomBeforeBreadcrumbCallback::class.java), ) .run { val beforeBreadcrumbCallback = diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryCheckInAdviceTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryCheckInAdviceTest.kt index 22e02b0b297..6a941e3f52d 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryCheckInAdviceTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryCheckInAdviceTest.kt @@ -53,7 +53,7 @@ import org.springframework.util.StringValueResolver "my.cron.schedule = 0 30 2 * * *", "my.cron.zone = America/New_York", "my.cron.empty.zone = ", - ] + ], ) class SentryCheckInAdviceTest { diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentrySpringFilterTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentrySpringFilterTest.kt index 37c97e99d89..dd23bd933f4 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentrySpringFilterTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentrySpringFilterTest.kt @@ -133,7 +133,7 @@ class SentrySpringFilterTest { MockMvcRequestBuilders.get(URI.create("http://example.com?param1=xyz")) .header("some-header", "some-header value") .accept(MediaType.APPLICATION_JSON) - .buildRequest(MockServletContext()) + .buildRequest(MockServletContext()), ) listener.doFilter(fixture.request, fixture.response, fixture.chain) @@ -157,7 +157,7 @@ class SentrySpringFilterTest { MockMvcRequestBuilders.get(URI.create("http://example.com?param1=xyz")) .header("another-header", "another value") .header("another-header", "another value2") - .buildRequest(MockServletContext()) + .buildRequest(MockServletContext()), ) listener.doFilter(fixture.request, fixture.response, fixture.chain) diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryTaskDecoratorTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryTaskDecoratorTest.kt index d589537d59c..777a03c3b19 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryTaskDecoratorTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryTaskDecoratorTest.kt @@ -43,7 +43,7 @@ class SentryTaskDecoratorTest { sut.decorate { assertNotEquals(mainScopes, Sentry.getCurrentScopes()) assertNotEquals(threadedScopes, Sentry.getCurrentScopes()) - } + }, ) callableFuture.get() diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryUserFilterTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryUserFilterTest.kt index 8d6a2fbcf69..36fb28c5717 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryUserFilterTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/SentryUserFilterTest.kt @@ -63,7 +63,7 @@ class SentryUserFilterTest { fun `when processor returns empty User, user data is not changed`() { val filter = fixture.getSut( - userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { User() }) + userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { User() }), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -75,7 +75,7 @@ class SentryUserFilterTest { fun `when processor returns null, user data is not changed`() { val filter = fixture.getSut( - userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { null }) + userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { null }), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -91,7 +91,7 @@ class SentryUserFilterTest { listOf( SentryUserProvider { User().apply { data = mapOf("key" to "value") } }, SentryUserProvider { User().apply { data = mapOf("new-key" to "new-value") } }, - ) + ), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -166,7 +166,7 @@ class SentryUserFilterTest { SentryUserProvider { sampleUser }, SentryUserProvider { throw failure }, laterProvider, - ) + ), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -184,7 +184,7 @@ class SentryUserFilterTest { assertThat( assertFailsWith { filter.doFilter(fixture.request, fixture.response, fixture.chain) - } + }, ) .isSameAs(failure) verify(fixture.chain, never()).doFilter(fixture.request, fixture.response) diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/TransactionNameProviderUtilsTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/TransactionNameProviderUtilsTest.kt index 80b275d8cca..386ffaae108 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/TransactionNameProviderUtilsTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/TransactionNameProviderUtilsTest.kt @@ -31,7 +31,7 @@ class TransactionNameProviderUtilsTest { assertThat( assertFailsWith { TransactionNameProviderUtils.provideTransactionName(provider, request, logger) - } + }, ) .isSameAs(failure) } diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/checkin/SentryScheduledCheckInTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/checkin/SentryScheduledCheckInTest.kt index 2e60dbcc556..132ec0ca9a1 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/checkin/SentryScheduledCheckInTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/checkin/SentryScheduledCheckInTest.kt @@ -177,11 +177,11 @@ class SentryScheduledCheckInTest { assertEquals("outer-inner-run2-fa", SentryCheckInAdvice.scheduledTaskSlug("Outer.Inner.run2FA")) val first = SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.firstMethod" + "AVeryLongScheduledJobClassNameForReporting.firstMethod", ) val second = SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.secondMethod" + "AVeryLongScheduledJobClassNameForReporting.secondMethod", ) assertTrue(first.length <= 50) assertTrue(first.startsWith("a-very-long-scheduled-job-class-name-for-")) @@ -189,7 +189,7 @@ class SentryScheduledCheckInTest { assertEquals( first, SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.firstMethod" + "AVeryLongScheduledJobClassNameForReporting.firstMethod", ), ) } @@ -292,11 +292,11 @@ class SentryScheduledCheckInTest { @Bean open fun sentryScheduledCheckInAdvisor( - @Qualifier("sentryScheduledCheckInAdvice") advice: SentryCheckInAdvice + @Qualifier("sentryScheduledCheckInAdvice") advice: SentryCheckInAdvice, ): Advisor = DefaultPointcutAdvisor( SentryScheduledCheckInPointcut( - listOf("SentryScheduledCheckInTest.Jobs.excluded", ".*\\.ExcludedJobs\\..*", " ") + listOf("SentryScheduledCheckInTest.Jobs.excluded", ".*\\.ExcludedJobs\\..*", " "), ), advice, ) diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/graphql/SentrySpringSubscriptionHandlerTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/graphql/SentrySpringSubscriptionHandlerTest.kt index 1ed217037a2..ac2e44a859d 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/graphql/SentrySpringSubscriptionHandlerTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/graphql/SentrySpringSubscriptionHandlerTest.kt @@ -2,7 +2,9 @@ package io.sentry.spring7.graphql import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters import graphql.language.Document +import graphql.language.Field import graphql.language.OperationDefinition +import graphql.language.SelectionSet import graphql.schema.DataFetchingEnvironment import io.sentry.IScopes import io.sentry.graphql.ExceptionReporter @@ -20,6 +22,19 @@ import org.springframework.graphql.execution.SubscriptionPublisherException import reactor.core.publisher.Flux class SentrySpringSubscriptionHandlerTest { + private val document = + Document.newDocument() + .definition( + OperationDefinition.newOperationDefinition() + .operation(OperationDefinition.Operation.QUERY) + .name("testQuery") + .selectionSet( + SelectionSet.newSelectionSet().selection(Field.newField("test").build()).build(), + ) + .build(), + ) + .build() + @Test fun `reports exception`() { val exception = IllegalStateException("some exception") @@ -27,15 +42,6 @@ class SentrySpringSubscriptionHandlerTest { val exceptionReporter = mock() val parameters = mock() val dataFetchingEnvironment = mock() - val document = - Document.newDocument() - .definition( - OperationDefinition.newOperationDefinition() - .operation(OperationDefinition.Operation.QUERY) - .name("testQuery") - .build() - ) - .build() whenever(dataFetchingEnvironment.document).thenReturn(document) whenever(parameters.environment).thenReturn(dataFetchingEnvironment) val resultObject = @@ -49,7 +55,7 @@ class SentrySpringSubscriptionHandlerTest { check { assertEquals(true, it.isSubscription) assertSame(scopes, it.scopes) - assertEquals("query testQuery \n", it.query) + assertEquals("query testQuery {\n test\n}\n", it.query) }, anyOrNull(), ) @@ -63,15 +69,6 @@ class SentrySpringSubscriptionHandlerTest { val exceptionReporter = mock() val parameters = mock() val dataFetchingEnvironment = mock() - val document = - Document.newDocument() - .definition( - OperationDefinition.newOperationDefinition() - .operation(OperationDefinition.Operation.QUERY) - .name("testQuery") - .build() - ) - .build() whenever(dataFetchingEnvironment.document).thenReturn(document) whenever(parameters.environment).thenReturn(dataFetchingEnvironment) val resultObject = @@ -90,7 +87,7 @@ class SentrySpringSubscriptionHandlerTest { check { assertEquals(true, it.isSubscription) assertSame(scopes, it.scopes) - assertEquals("query testQuery \n", it.query) + assertEquals("query testQuery {\n test\n}\n", it.query) }, anyOrNull(), ) diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/kafka/SentryKafkaProducerBeanPostProcessorTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/kafka/SentryKafkaProducerBeanPostProcessorTest.kt index d11ac1e6c1b..bf307366e48 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/kafka/SentryKafkaProducerBeanPostProcessorTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/kafka/SentryKafkaProducerBeanPostProcessorTest.kt @@ -42,7 +42,7 @@ class SentryKafkaProducerBeanPostProcessorTest { val captor = argumentCaptor>() verify(factory).addPostProcessor(captor.capture()) assertTrue( - captor.firstValue is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *> + captor.firstValue is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *>, ) } @@ -103,7 +103,7 @@ class SentryKafkaProducerBeanPostProcessorTest { assertEquals(1, factory.postProcessors.size) assertTrue( factory.postProcessors.first() - is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *> + is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *>, ) } } diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentrySpanClientHttpRequestInterceptorTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentrySpanClientHttpRequestInterceptorTest.kt index 267477df6e8..3be29d43929 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentrySpanClientHttpRequestInterceptorTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentrySpanClientHttpRequestInterceptorTest.kt @@ -54,7 +54,7 @@ class SentrySpanClientHttpRequestInterceptorTest { } fun create( - config: Sentry.OptionsConfiguration + config: Sentry.OptionsConfiguration, ): SentrySpanClientHttpRequestInterceptor { config.configure(options) return SentrySpanClientHttpRequestInterceptor(scopes) diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentryTracingFilterTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentryTracingFilterTest.kt index fae0f19ebe6..f3ed0769cd5 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentryTracingFilterTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentryTracingFilterTest.kt @@ -87,7 +87,10 @@ class SentryTracingFilterTest { } response.status = status whenever( - scopes.startTransaction(any(), check { assertTrue(it.isBindToScope) }) + scopes.startTransaction( + any(), + check { assertTrue(it.isBindToScope) }, + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.isEnabled).thenReturn(isEnabled) @@ -98,7 +101,7 @@ class SentryTracingFilterTest { it.arguments[0] as String?, it.arguments[1] as List?, null, - ) + ), ) } return SentryTracingFilter(scopes, transactionNameProvider, isAsyncSupportEnabled) @@ -313,7 +316,7 @@ class SentryTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null val filter = @@ -343,7 +346,7 @@ class SentryTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null fixture.options.setIgnoredSpanOrigins(listOf("auto.http.spring7.webmvc")) @@ -373,7 +376,7 @@ class SentryTracingFilterTest { val sentryTrace = "f9118105af4a2d42b4124532cd1065ff-424cffc8f94feeee-1" val baggage = listOf( - "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" + "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", ) val filter = fixture.getSut( @@ -442,7 +445,7 @@ class SentryTracingFilterTest { val sentryTrace = "f9118105af4a2d42b4124532cd1065ff-424cffc8f94feeee-1" val baggage = listOf( - "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" + "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", ) val filter = fixture.getSut( diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentryTransactionAdviceTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentryTransactionAdviceTest.kt index 1c2359d4489..7fad4a8aa71 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentryTransactionAdviceTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/tracing/SentryTransactionAdviceTest.kt @@ -55,7 +55,7 @@ class SentryTransactionAdviceTest { assertTrue(it.isBindToScope) assertThat(it.origin).isEqualTo("auto.function.spring7.advice") }, - ) + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.options) diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryScheduleHookTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryScheduleHookTest.kt index 189acf89d52..e8796452f18 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryScheduleHookTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryScheduleHookTest.kt @@ -45,7 +45,7 @@ class SentryScheduleHookTest { sut.apply { assertNotEquals(mainScopes, Sentry.getCurrentScopes()) assertNotEquals(threadedScopes, Sentry.getCurrentScopes()) - } + }, ) callableFuture.get() diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryWebFluxTracingFilterTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryWebFluxTracingFilterTest.kt index c6c65b560db..d1a3459abad 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryWebFluxTracingFilterTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryWebFluxTracingFilterTest.kt @@ -87,7 +87,10 @@ class SentryWebFluxTracingFilterTest { ) exchange.response.statusCode = status whenever( - scopes.startTransaction(any(), check { assertTrue(it.isBindToScope) }) + scopes.startTransaction( + any(), + check { assertTrue(it.isBindToScope) }, + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.isEnabled).thenReturn(isEnabled) @@ -99,7 +102,7 @@ class SentryWebFluxTracingFilterTest { it.arguments[0] as String?, it.arguments[1] as List?, null, - ) + ), ) } return SentryWebFilter(scopes) @@ -326,7 +329,7 @@ class SentryWebFluxTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null val filter = @@ -358,7 +361,7 @@ class SentryWebFluxTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null fixture.options.setIgnoredSpanOrigins(listOf("auto.spring7.webflux")) diff --git a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryWebfluxIntegrationTest.kt b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryWebfluxIntegrationTest.kt index 56a7c07df41..f965c81ffd8 100644 --- a/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryWebfluxIntegrationTest.kt +++ b/sentry-spring-7/src/test/kotlin/io/sentry/spring7/webflux/SentryWebfluxIntegrationTest.kt @@ -139,7 +139,7 @@ class SentryWebfluxIntegrationTest { } @SpringBootApplication( - exclude = [ReactiveWebSecurityAutoConfiguration::class, SecurityAutoConfiguration::class] + exclude = [ReactiveWebSecurityAutoConfiguration::class, SecurityAutoConfiguration::class], ) open class App { private val transport = mock().also { whenever(it.isHealthy).thenReturn(true) } diff --git a/sentry-spring-boot-4/build.gradle.kts b/sentry-spring-boot-4/build.gradle.kts index 5629fdd5aa4..e61e8c21053 100644 --- a/sentry-spring-boot-4/build.gradle.kts +++ b/sentry-spring-boot-4/build.gradle.kts @@ -1,4 +1,4 @@ -import io.sentry.gradle.ChildJvmTestArguments +import io.sentry.gradle.otelAgentTests import net.ltgt.gradle.errorprone.errorprone import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import org.springframework.boot.gradle.plugin.SpringBootPlugin @@ -7,6 +7,7 @@ plugins { `java-library` id("io.sentry.javadoc") id("io.sentry.spring-boot-matrix") + id("io.sentry.otel-agent-tests") alias(libs.plugins.kotlin.jvm) alias(libs.plugins.kotlin.spring) alias(libs.plugins.errorprone) @@ -162,22 +163,7 @@ kotlin { } } -// The OpenTelemetry agent tests run this app in a child JVM, on its own classpath like a real app -// with the agent attached, rather than on the test's classpath. -val agentFixture = sourceSets.create("agentFixture") - -// The built agent jar, rather than the plain jar the unit tests compile against. -val otelAgentJar = - configurations.create("otelAgentJar") { - isCanBeResolved = true - isCanBeConsumed = false - isTransitive = false - attributes { - attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) - attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.SHADOWED)) - } - } - +// The app the OpenTelemetry agent tests run in a child JVM. dependencies { "agentFixtureImplementation"(platform(SpringBootPlugin.BOM_COORDINATES)) "agentFixtureImplementation"(projects.sentrySpringBoot4Starter) @@ -200,8 +186,6 @@ dependencies { "agentFixtureImplementation"(libs.springboot4.starter.webclient) "agentFixtureImplementation"(libs.springboot4.starter.webflux) "agentFixtureRuntimeOnly"(libs.hsqldb) - - otelAgentJar(projects.sentryOpentelemetry.sentryOpentelemetryAgent) } // Swaps Logback for Log4j2 where a classpath has both starters, which only @@ -336,9 +320,8 @@ testing { } } - // Runs agentFixture's app with the agent initializing Sentry. - register("integrationTestOtelAgent") { - useJUnit() + // The OpenTelemetry agent tests, against agentFixture's app. + named("integrationTestOtelAgent") { dependencies { implementation(platform(SpringBootPlugin.BOM_COORDINATES)) implementation(projects.sentryTestSupport) @@ -350,7 +333,6 @@ testing { implementation(libs.springboot4.starter.test) implementation(libs.spring.kafka4.test) } - targets.all { testTask.configure { runAgentFixture(autoInit = true) } } } // The servlet app with the OpenTelemetry Spring Boot starter, set up by @@ -388,37 +370,6 @@ testing { } } -/** - * Has the OpenTelemetry agent tests start agentFixture's app in a child JVM, with the built agent - * attached. [autoInit] decides whether the agent initializes Sentry or, as with - * `SENTRY_AUTO_INIT=false`, the Spring Boot starter. [appClasspath] is the app's classpath for - * another Spring Boot version. - */ -fun Test.runAgentFixture( - autoInit: Boolean, - appClasspath: FileCollection = agentFixture.runtimeClasspath, -) { - jvmArgumentProviders.add( - objects.newInstance().apply { - agentJar.from(otelAgentJar) - this.appClasspath.from(appClasspath) - } - ) - systemProperty("sentry.test.agentAutoInit", autoInit) -} - -// The same tests with the Spring Boot starter initializing Sentry. Each test JVM starts one app, so -// this mode needs a task of its own, which Gradle runs in parallel with the suite's. -tasks.register("integrationTestOtelAgentWithoutAutoInit") { - description = "Runs the OpenTelemetry agent tests with SENTRY_AUTO_INIT=false." - group = LifecycleBasePlugin.VERIFICATION_GROUP - val sources = sourceSets["integrationTestOtelAgent"] - testClassesDirs = sources.output.classesDirs - classpath = sources.runtimeClasspath - useJUnit() - runAgentFixture(autoInit = false) -} - // The Spring Boot Gradle plugin compiles apps with parameter names, which Spring reads, for example // to resolve `#id` in a cache key. listOf( @@ -440,10 +391,5 @@ springBootMatrix { test("integrationTestWebflux") test("integrationTestOtelNoAgent") test("integrationTestOtlp") - test("integrationTestOtelAgent") { version -> - runAgentFixture(autoInit = true, appClasspath = runtimeClasspath("agentFixture", version)) - } - test("integrationTestOtelAgent", name = "integrationTestOtelAgentWithoutAutoInit") { version -> - runAgentFixture(autoInit = false, appClasspath = runtimeClasspath("agentFixture", version)) - } + otelAgentTests() } diff --git a/sentry-spring-boot-4/src/agentFixture/kotlin/io/sentry/spring/boot4/agentfixture/TodoController.kt b/sentry-spring-boot-4/src/agentFixture/kotlin/io/sentry/spring/boot4/agentfixture/TodoController.kt index 1b5b51d248f..0bbd4f4e121 100644 --- a/sentry-spring-boot-4/src/agentFixture/kotlin/io/sentry/spring/boot4/agentfixture/TodoController.kt +++ b/sentry-spring-boot-4/src/agentFixture/kotlin/io/sentry/spring/boot4/agentfixture/TodoController.kt @@ -37,7 +37,7 @@ class TodoController( return SentryReactorUtils.withSentry( Mono.just(true).publishOn(Schedulers.boundedElastic()).flatMap { webClient.get().uri(url).retrieve().bodyToMono(Todo::class.java) - } + }, ) .block() } diff --git a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/GraphqlIntegrationTest.kt index c50dca2ec1e..8c27919d43a 100644 --- a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/GraphqlIntegrationTest.kt @@ -60,7 +60,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `batch loaded fields are traced`() { val response = graphql( - """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/MetricsIntegrationTest.kt index 784cddfa2f9..7f02dce8e49 100644 --- a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/PersonIntegrationTest.kt index 30543274d5d..48a17e7337d 100644 --- a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/PersonIntegrationTest.kt @@ -49,14 +49,14 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasOp( "http.server", FeatureFlag("flag.evaluation.transaction-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughSentryApi", FeatureFlag("flag.evaluation.my-feature-flag", true), - ) + ), ) .isTrue() @@ -88,7 +88,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db.query", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/TodoController.kt b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/TodoController.kt index e554718ff26..39b773f280a 100644 --- a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/TodoController.kt +++ b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/TodoController.kt @@ -37,7 +37,7 @@ class TodoController( return SentryReactorUtils.withSentry( Mono.just(true).publishOn(Schedulers.boundedElastic()).flatMap { webClient.get().uri(url).retrieve().bodyToMono(Todo::class.java) - } + }, ) .block() } diff --git a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/TodoIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/TodoIntegrationTest.kt index 5e0bc317552..d4c627df5a4 100644 --- a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/TodoIntegrationTest.kt @@ -40,7 +40,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET http://localhost:$port/stub/todos/1", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/AgentApp.kt b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/AgentApp.kt index 24496ee290a..58c097de2c7 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/AgentApp.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/AgentApp.kt @@ -57,13 +57,13 @@ object AgentApp { app.close() kafka.destroy() server.close() - } + }, ) } // The agent instruments classes as they load, which on a busy CI runner has taken over a minute. val restTemplate = TestRestTemplate( - RestTemplateBuilder().rootUri("http://localhost:${app.awaitPort(timeoutSeconds = 180)}") + RestTemplateBuilder().rootUri("http://localhost:${app.awaitPort(timeoutSeconds = 180)}"), ) } diff --git a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/GraphqlIntegrationTest.kt index 6ee2118dfce..60a49d0f943 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/GraphqlIntegrationTest.kt @@ -65,7 +65,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `query with batch loaded fields is traced`() { val response = graphql( - """query TasksAndAssigneesQuery { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query TasksAndAssigneesQuery { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/MetricsIntegrationTest.kt index 1d32a9e2350..7d6c87779ee 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/MetricsIntegrationTest.kt @@ -34,7 +34,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/PersonIntegrationTest.kt index 09d7aecda14..cf2f5a4490f 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/PersonIntegrationTest.kt @@ -47,21 +47,21 @@ class PersonIntegrationTest : IntegrationTest() { // Whichever initializes Sentry names the SDK, which shows that each mode takes its own path. assertThat(transactionEnvelope.header.sdkVersion!!.name) .isEqualTo( - if (AgentApp.autoInit) "sentry.java.opentelemetry.agent" else "sentry.java.spring-boot-4" + if (AgentApp.autoInit) "sentry.java.opentelemetry.agent" else "sentry.java.spring-boot-4", ) val transaction = transactionEnvelope.transaction()!! assertThat( transaction.hasOp( "http.server", FeatureFlag("flag.evaluation.transaction-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughOtelApi", FeatureFlag("flag.evaluation.my-feature-flag", true), - ) + ), ) .isTrue() assertThat(transaction.hasSpanWithOp("spanCreatedThroughSentryApi")).isTrue() @@ -127,7 +127,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/TodoIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/TodoIntegrationTest.kt index b40e5f4bd3a..48393201e8a 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot4/otelagentintegrationtest/TodoIntegrationTest.kt @@ -39,7 +39,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET ${restTemplate.rootUri}/stub/todos/1", - ) + ), ) .isTrue() return transaction diff --git a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/GraphqlIntegrationTest.kt index 8825ea803c3..55283ffdff0 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/GraphqlIntegrationTest.kt @@ -61,7 +61,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `query with batch loaded fields is traced`() { val response = graphql( - """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/MetricsIntegrationTest.kt index 19b2b362db6..75029fe68f3 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/PersonIntegrationTest.kt index 6e0359c459b..8ee19218dc2 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/PersonIntegrationTest.kt @@ -54,14 +54,14 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOp( "personSpanThroughOtelAnnotation", FeatureFlag("flag.evaluation.outer-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughOtelApi", FeatureFlag("flag.evaluation.inner-feature-flag", true), - ) + ), ) .isTrue() assertThat(transaction.hasSpanWithOp("spanCreatedThroughSentryApi", noFeatureFlags = true)) @@ -128,7 +128,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/TodoController.kt b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/TodoController.kt index cc341620922..c994a0ee6e5 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/TodoController.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/TodoController.kt @@ -37,7 +37,7 @@ class TodoController( return SentryReactorUtils.withSentry( Mono.just(true).publishOn(Schedulers.boundedElastic()).flatMap { webClient.get().uri(url).retrieve().bodyToMono(Todo::class.java) - } + }, ) .block() } diff --git a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/TodoIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/TodoIntegrationTest.kt index 7ca243955f7..2196a33d8cb 100644 --- a/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot4/otelnoagentintegrationtest/TodoIntegrationTest.kt @@ -42,7 +42,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET http://localhost:$port/stub/todos/1", - ) + ), ) .isTrue() return transaction diff --git a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/GraphqlIntegrationTest.kt index b6ebc1e18f6..6b58e2a243f 100644 --- a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/GraphqlIntegrationTest.kt @@ -60,7 +60,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `batch loaded fields are traced`() { val response = graphql( - """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/MetricsIntegrationTest.kt index 074f4e022cb..106a80b1374 100644 --- a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/PersonIntegrationTest.kt index 50b1c660bb0..5cf00447acb 100644 --- a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/PersonIntegrationTest.kt @@ -78,14 +78,14 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasOp( "http.server", FeatureFlag("flag.evaluation.transaction-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughSentryApi", FeatureFlag("flag.evaluation.my-feature-flag", true), - ) + ), ) .isTrue() @@ -117,7 +117,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db.query", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/TodoController.kt b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/TodoController.kt index 08c23022f73..8e053a78c91 100644 --- a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/TodoController.kt +++ b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/TodoController.kt @@ -32,7 +32,7 @@ class TodoController( return SentryReactorUtils.withSentry( Mono.just(true).publishOn(Schedulers.boundedElastic()).flatMap { webClient.get().uri(url).retrieve().bodyToMono(Todo::class.java) - } + }, ) .block() } diff --git a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/TodoIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/TodoIntegrationTest.kt index b2a158aa13c..001f600f843 100644 --- a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/TodoIntegrationTest.kt @@ -35,7 +35,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET http://localhost:$port/stub/todos/1", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestWebflux/kotlin/io/sentry/spring/boot4/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestWebflux/kotlin/io/sentry/spring/boot4/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt index dde8a6d6f87..1681b82cafc 100644 --- a/sentry-spring-boot-4/src/integrationTestWebflux/kotlin/io/sentry/spring/boot4/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestWebflux/kotlin/io/sentry/spring/boot4/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsWebfluxIntegrationTest : WebfluxIntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/integrationTestWebflux/kotlin/io/sentry/spring/boot4/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestWebflux/kotlin/io/sentry/spring/boot4/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt index eb79a9c1c98..17b3e917dbb 100644 --- a/sentry-spring-boot-4/src/integrationTestWebflux/kotlin/io/sentry/spring/boot4/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestWebflux/kotlin/io/sentry/spring/boot4/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt @@ -23,7 +23,7 @@ class TodoWebfluxIntegrationTest : WebfluxIntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET http://localhost:$port/stub/todos/1", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentryAutoConfiguration.java b/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentryAutoConfiguration.java index 4c14b0ea858..15a77212154 100644 --- a/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentryAutoConfiguration.java +++ b/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentryAutoConfiguration.java @@ -173,12 +173,11 @@ static class OpenTelemetryNoAgentConfiguration {} final @NotNull ObjectProvider gitProperties) { optionsConfigurations.forEach( optionsConfiguration -> optionsConfiguration.configure(options)); - gitProperties.ifAvailable( - git -> { - if (options.getRelease() == null && options.isUseGitCommitIdAsRelease()) { - options.setRelease(git.getCommitId()); - } - }); + gitProperties.ifAvailable(git -> { + if (options.getRelease() == null && options.isUseGitCommitIdAsRelease()) { + options.setRelease(git.getCommitId()); + } + }); spanFactory.ifAvailable(options::setSpanFactory); options.setSentryClientName( @@ -511,6 +510,7 @@ static class SentrySpanPointcutAutoConfiguration {} @Configuration(proxyBeanMethods = false) @ConditionalOnClass({RestTemplate.class, RestTemplateAutoConfiguration.class}) @Open + @SuppressWarnings("removal") static class SentryPerformanceRestTemplateConfigurationWrapper { @Configuration(proxyBeanMethods = false) @AutoConfigureBefore(RestTemplateAutoConfiguration.class) diff --git a/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentryLogbackInitializer.java b/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentryLogbackInitializer.java index b2f498e4401..d6fd5f22491 100644 --- a/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentryLogbackInitializer.java +++ b/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentryLogbackInitializer.java @@ -39,27 +39,26 @@ public boolean supportsEventType(final @NotNull ResolvableType eventType) { @Override public void onApplicationEvent(final @NotNull ApplicationEvent event) { - this.loggers.forEach( - loggerName -> { - final Logger logger = (Logger) LoggerFactory.getLogger(loggerName); - if (!isSentryAppenderRegistered(logger)) { - final SentryAppender sentryAppender = getSentryAppender(); + this.loggers.forEach(loggerName -> { + final Logger logger = (Logger) LoggerFactory.getLogger(loggerName); + if (!isSentryAppenderRegistered(logger)) { + final SentryAppender sentryAppender = getSentryAppender(); - sentryAppender.setLogsEnabled(sentryProperties.getLogging().getLogsEnabled()); - Optional.ofNullable(sentryProperties.getLogging().getMinimumBreadcrumbLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumBreadcrumbLevel); - Optional.ofNullable(sentryProperties.getLogging().getMinimumEventLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumEventLevel); - Optional.ofNullable(sentryProperties.getLogging().getMinimumLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumLevel); + sentryAppender.setLogsEnabled(sentryProperties.getLogging().getLogsEnabled()); + Optional.ofNullable(sentryProperties.getLogging().getMinimumBreadcrumbLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumBreadcrumbLevel); + Optional.ofNullable(sentryProperties.getLogging().getMinimumEventLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumEventLevel); + Optional.ofNullable(sentryProperties.getLogging().getMinimumLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumLevel); - sentryAppender.start(); - logger.addAppender(sentryAppender); - } - }); + sentryAppender.start(); + logger.addAppender(sentryAppender); + } + }); } @NotNull diff --git a/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentrySpanRestClientCustomizer.java b/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentrySpanRestClientCustomizer.java index 4611a3be51a..db6a6f2c0f2 100644 --- a/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentrySpanRestClientCustomizer.java +++ b/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentrySpanRestClientCustomizer.java @@ -17,14 +17,13 @@ public SentrySpanRestClientCustomizer(final @NotNull IScopes scopes) { @Override public void customize(final @NotNull RestClient.Builder restClientBuilder) { - restClientBuilder.requestInterceptors( - clientHttpRequestInterceptors -> { - // As the SentrySpanClientHttpRequestInterceptor is being created in this class, this - // might not work - // if somebody registers it from an outside. - if (!clientHttpRequestInterceptors.contains(interceptor)) { - clientHttpRequestInterceptors.add(interceptor); - } - }); + restClientBuilder.requestInterceptors(clientHttpRequestInterceptors -> { + // As the SentrySpanClientHttpRequestInterceptor is being created in this class, this + // might not work + // if somebody registers it from an outside. + if (!clientHttpRequestInterceptors.contains(interceptor)) { + clientHttpRequestInterceptors.add(interceptor); + } + }); } } diff --git a/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentrySpanRestTemplateCustomizer.java b/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentrySpanRestTemplateCustomizer.java index 11a0b5e095a..7e2a56ba521 100644 --- a/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentrySpanRestTemplateCustomizer.java +++ b/sentry-spring-boot-4/src/main/java/io/sentry/spring/boot4/SentrySpanRestTemplateCustomizer.java @@ -11,6 +11,7 @@ import org.springframework.web.client.RestTemplate; @Open +@SuppressWarnings("removal") class SentrySpanRestTemplateCustomizer implements RestTemplateCustomizer { private final @NotNull SentrySpanClientHttpRequestInterceptor interceptor; diff --git a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryAutoConfigurationTest.kt b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryAutoConfigurationTest.kt index bf11bf242fd..778d2ff263b 100644 --- a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryAutoConfigurationTest.kt +++ b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryAutoConfigurationTest.kt @@ -104,7 +104,7 @@ class SentryAutoConfigurationTest { SentryAutoConfiguration::class.java, WebMvcAutoConfiguration::class.java, SentryProfilerAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -125,7 +125,7 @@ class SentryAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runners for different test categories @@ -133,14 +133,14 @@ class SentryAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls private val tracingEnabledRunner = baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj", "sentry.traces-sample-rate=1.0") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls @Test @@ -194,7 +194,7 @@ class SentryAutoConfigurationTest { .run { assertThat(it).hasSingleBean(Sentry.OptionsConfiguration::class.java) assertThat( - it.getBean(Sentry.OptionsConfiguration::class.java, "customOptionsConfiguration") + it.getBean(Sentry.OptionsConfiguration::class.java, "customOptionsConfiguration"), ) .isNotNull } @@ -204,7 +204,7 @@ class SentryAutoConfigurationTest { fun `GraphQL specification error type filtering is disabled by default`() { dsnEnabledRunner.run { assertThat( - it.getBean(SentryProperties::class.java).graphql.isEnableSpecificationErrorTypeFiltering + it.getBean(SentryProperties::class.java).graphql.isEnableSpecificationErrorTypeFiltering, ) .isFalse() } @@ -220,7 +220,7 @@ class SentryAutoConfigurationTest { it .getBean(SentryProperties::class.java) .graphql - .isEnableSpecificationErrorTypeFiltering + .isEnableSpecificationErrorTypeFiltering, ) .isEqualTo(enabled) } @@ -614,7 +614,7 @@ class SentryAutoConfigurationTest { contextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj", "sentry.send-default-pii=true") .withConfiguration( - UserConfigurations.of(SentryHighestOrderUserProviderConfiguration::class.java) + UserConfigurations.of(SentryHighestOrderUserProviderConfiguration::class.java), ) .run { val userProviders = it.getSentryUserProviders() @@ -896,7 +896,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -908,7 +908,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -923,7 +923,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -939,7 +939,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryNoAgent") + .contains("SpringBoot4OpenTelemetryNoAgent"), ) } } @@ -954,7 +954,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryNoAgent") + .contains("SpringBoot4OpenTelemetryNoAgent"), ) } } @@ -968,14 +968,14 @@ class SentryAutoConfigurationTest { FilteredClassLoader( AgentMarker::class.java, SentryAutoConfigurationCustomizerProvider::class.java, - ) + ), ) .withUserConfiguration(OtelBeanConfig::class.java) .run { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryNoAgent") + .contains("SpringBoot4OpenTelemetryNoAgent"), ) } } @@ -990,7 +990,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot4OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -1046,7 +1046,7 @@ class SentryAutoConfigurationTest { FilteredClassLoader( io.sentry.graphql.SentryInstrumentation::class.java, io.sentry.graphql22.SentryInstrumentation::class.java, - ) + ), ) .run { assertThat(it).doesNotHaveBean(io.sentry.graphql.SentryInstrumentation::class.java) @@ -1114,7 +1114,7 @@ class SentryAutoConfigurationTest { captor.allValues.map { envelope -> String(envelope.items.first().data, Charsets.UTF_8) } assertThat(payloads).allMatch { payload -> payload.contains( - "\"monitor_slug\":\"sentry-auto-configuration-test-scheduled-jobs-sync\"" + "\"monitor_slug\":\"sentry-auto-configuration-test-scheduled-jobs-sync\"", ) } assertThat(payloads[0]).contains("\"value\":1,\"unit\":\"hour\"") @@ -1180,7 +1180,7 @@ class SentryAutoConfigurationTest { assertThat(it) .getBean(IProfileConverter::class.java) .isInstanceOf( - AsyncProfilerProfileConverterProvider.AsyncProfilerProfileConverter::class.java + AsyncProfilerProfileConverterProvider.AsyncProfilerProfileConverter::class.java, ) assertThat(it) .getBean(IContinuousProfiler::class.java) diff --git a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryLog4j2AppenderAutoConfigurationTest.kt b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryLog4j2AppenderAutoConfigurationTest.kt index 8ff176c7755..a62b66eaac6 100644 --- a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryLog4j2AppenderAutoConfigurationTest.kt +++ b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryLog4j2AppenderAutoConfigurationTest.kt @@ -40,7 +40,7 @@ class SentryLog4j2AppenderAutoConfigurationTest { AutoConfigurations.of( SentryLog4j2AppenderAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( "sentry.shutdownTimeoutMillis=0", @@ -155,7 +155,7 @@ class SentryLog4j2AppenderAutoConfigurationTest { .run { assertThat(rootLogger.getAppenders(SentryAppender::class.java)).hasSize(1) assertThat( - configuration.getLoggerConfig("com.example").getAppenders(SentryAppender::class.java) + configuration.getLoggerConfig("com.example").getAppenders(SentryAppender::class.java), ) .hasSize(1) } @@ -320,7 +320,7 @@ class SentryLog4j2AppenderAutoConfigurationTest { } fun org.apache.logging.log4j.core.config.LoggerConfig.getAppenders( - clazz: Class + clazz: Class, ): List { return this.appenders.values.filter { it.javaClass == clazz } } diff --git a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryLogbackAppenderAutoConfigurationTest.kt b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryLogbackAppenderAutoConfigurationTest.kt index 90e756d59b6..c2311a56732 100644 --- a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryLogbackAppenderAutoConfigurationTest.kt +++ b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryLogbackAppenderAutoConfigurationTest.kt @@ -27,7 +27,7 @@ class SentryLogbackAppenderAutoConfigurationTest { AutoConfigurations.of( SentryLogbackAppenderAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -48,7 +48,7 @@ class SentryLogbackAppenderAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runner for tests requiring DSN @@ -56,7 +56,7 @@ class SentryLogbackAppenderAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls private val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger diff --git a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryOkHttpAutoConfigurationTest.kt b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryOkHttpAutoConfigurationTest.kt index 20172470d0b..42dfa94f46b 100644 --- a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryOkHttpAutoConfigurationTest.kt +++ b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryOkHttpAutoConfigurationTest.kt @@ -254,7 +254,7 @@ class SentryOkHttpAutoConfigurationTest { SentryOkHttpInterceptor::class.java, SentryAutoConfigurationCustomizerProvider::class.java, AgentMarker::class.java, - ) + ), ) .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration(OkHttpClientConfiguration::class.java) diff --git a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentrySpanRestClientCustomizerTest.kt b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentrySpanRestClientCustomizerTest.kt index 04e6eede7a6..d1d70ce5021 100644 --- a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentrySpanRestClientCustomizerTest.kt +++ b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentrySpanRestClientCustomizerTest.kt @@ -79,7 +79,7 @@ class SentrySpanRestClientCustomizerTest { sentryOptions.dsn = "https://key@sentry.io/proj" mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -155,8 +155,8 @@ class SentrySpanRestClientCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=aTransaction")) @@ -270,8 +270,8 @@ class SentrySpanRestClientCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-trace_id")) diff --git a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentrySpanRestTemplateCustomizerTest.kt b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentrySpanRestTemplateCustomizerTest.kt index a58968a5317..1de9bae1189 100644 --- a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentrySpanRestTemplateCustomizerTest.kt +++ b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentrySpanRestTemplateCustomizerTest.kt @@ -83,7 +83,7 @@ class SentrySpanRestTemplateCustomizerTest { sentryOptions.dsn = "https://key@sentry.io/proj" mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -141,8 +141,8 @@ class SentrySpanRestTemplateCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=aTransaction")) @@ -229,8 +229,8 @@ class SentrySpanRestTemplateCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-trace_id")) diff --git a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryWebfluxAutoConfigurationTest.kt b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryWebfluxAutoConfigurationTest.kt index a338208d8e4..bf92eddd8ab 100644 --- a/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryWebfluxAutoConfigurationTest.kt +++ b/sentry-spring-boot-4/src/test/kotlin/io/sentry/spring/boot4/SentryWebfluxAutoConfigurationTest.kt @@ -25,7 +25,7 @@ class SentryWebfluxAutoConfigurationTest { WebFluxAutoConfiguration::class.java, SentryWebfluxAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -46,7 +46,7 @@ class SentryWebfluxAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runner for tests requiring DSN @@ -54,7 +54,7 @@ class SentryWebfluxAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls @Test diff --git a/sentry-spring-boot-jakarta/build.gradle.kts b/sentry-spring-boot-jakarta/build.gradle.kts index b678bbd709a..c9b68d7ce51 100644 --- a/sentry-spring-boot-jakarta/build.gradle.kts +++ b/sentry-spring-boot-jakarta/build.gradle.kts @@ -1,4 +1,4 @@ -import io.sentry.gradle.ChildJvmTestArguments +import io.sentry.gradle.otelAgentTests import net.ltgt.gradle.errorprone.errorprone import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import org.springframework.boot.gradle.plugin.SpringBootPlugin @@ -7,6 +7,7 @@ plugins { `java-library` id("io.sentry.javadoc") id("io.sentry.spring-boot-matrix") + id("io.sentry.otel-agent-tests") alias(libs.plugins.kotlin.jvm) alias(libs.plugins.errorprone) alias(libs.plugins.gradle.versions) @@ -145,22 +146,7 @@ tasks.jar { } } -// The OpenTelemetry agent tests run this app in a child JVM, on its own classpath like a real app -// with the agent attached, rather than on the test's classpath. -val agentFixture = sourceSets.create("agentFixture") - -// The built agent jar, rather than the plain jar the unit tests compile against. -val otelAgentJar = - configurations.create("otelAgentJar") { - isCanBeResolved = true - isCanBeConsumed = false - isTransitive = false - attributes { - attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) - attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.SHADOWED)) - } - } - +// The app the OpenTelemetry agent tests run in a child JVM. dependencies { "agentFixtureImplementation"(platform(SpringBootPlugin.BOM_COORDINATES)) "agentFixtureImplementation"(projects.sentrySpringBootStarterJakarta) @@ -181,8 +167,6 @@ dependencies { "agentFixtureImplementation"(libs.springboot3.starter.webflux) "agentFixtureImplementation"(libs.spring.kafka3) "agentFixtureRuntimeOnly"(libs.hsqldb) - - otelAgentJar(projects.sentryOpentelemetry.sentryOpentelemetryAgent) } // Swaps Logback for Log4j2 where a classpath has both starters, which only @@ -310,9 +294,8 @@ testing { } } - // Runs agentFixture's app with the agent initializing Sentry. - register("integrationTestOtelAgent") { - useJUnit() + // The OpenTelemetry agent tests, against agentFixture's app. + named("integrationTestOtelAgent") { dependencies { implementation(platform(SpringBootPlugin.BOM_COORDINATES)) implementation(projects.sentryTestSupport) @@ -323,42 +306,10 @@ testing { implementation(libs.springboot3.starter.web) implementation(libs.spring.kafka3.test) } - targets.all { testTask.configure { runAgentFixture(autoInit = true) } } } } } -/** - * Has the OpenTelemetry agent tests start agentFixture's app in a child JVM, with the built agent - * attached. [autoInit] decides whether the agent initializes Sentry or, as with - * `SENTRY_AUTO_INIT=false`, the Spring Boot starter. [appClasspath] is the app's classpath for - * another Spring Boot version. - */ -fun Test.runAgentFixture( - autoInit: Boolean, - appClasspath: FileCollection = agentFixture.runtimeClasspath, -) { - jvmArgumentProviders.add( - objects.newInstance().apply { - agentJar.from(otelAgentJar) - this.appClasspath.from(appClasspath) - } - ) - systemProperty("sentry.test.agentAutoInit", autoInit) -} - -// The same tests with the Spring Boot starter initializing Sentry. Each test JVM starts one app, so -// this mode needs a task of its own, which Gradle runs in parallel with the suite's. -tasks.register("integrationTestOtelAgentWithoutAutoInit") { - description = "Runs the OpenTelemetry agent tests with SENTRY_AUTO_INIT=false." - group = LifecycleBasePlugin.VERIFICATION_GROUP - val sources = sourceSets["integrationTestOtelAgent"] - testClassesDirs = sources.output.classesDirs - classpath = sources.runtimeClasspath - useJUnit() - runAgentFixture(autoInit = false) -} - // The Spring Boot Gradle plugin compiles apps with parameter names, which Spring reads, for example // to resolve `#id` in a cache key. listOf( @@ -378,10 +329,5 @@ springBootMatrix { test("integrationTestLog4j2") test("integrationTestWebflux") test("integrationTestOtelNoAgent") - test("integrationTestOtelAgent") { version -> - runAgentFixture(autoInit = true, appClasspath = runtimeClasspath("agentFixture", version)) - } - test("integrationTestOtelAgent", name = "integrationTestOtelAgentWithoutAutoInit") { version -> - runAgentFixture(autoInit = false, appClasspath = runtimeClasspath("agentFixture", version)) - } + otelAgentTests() } diff --git a/sentry-spring-boot-jakarta/src/agentFixture/kotlin/io/sentry/spring/boot/jakarta/agentfixture/TodoController.kt b/sentry-spring-boot-jakarta/src/agentFixture/kotlin/io/sentry/spring/boot/jakarta/agentfixture/TodoController.kt index 396b4aa4a14..ec1c94ff4ef 100644 --- a/sentry-spring-boot-jakarta/src/agentFixture/kotlin/io/sentry/spring/boot/jakarta/agentfixture/TodoController.kt +++ b/sentry-spring-boot-jakarta/src/agentFixture/kotlin/io/sentry/spring/boot/jakarta/agentfixture/TodoController.kt @@ -37,7 +37,7 @@ open class TodoController( return SentryReactorUtils.withSentry( Mono.just(true).publishOn(Schedulers.boundedElastic()).flatMap { webClient.get().uri(url).retrieve().bodyToMono(Todo::class.java) - } + }, ) .block() } diff --git a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/FeatureFlagController.kt b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/FeatureFlagController.kt index 808d89cb184..2a555b6dd48 100644 --- a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/FeatureFlagController.kt +++ b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/FeatureFlagController.kt @@ -42,8 +42,8 @@ open class OpenFeatureConfig { "new-checkout-flow" to booleanFlag(true), "experimental-feature" to booleanFlag(false), "beta-features" to booleanFlag(true), - ) - ) + ), + ), ) addHooks(SentryOpenFeatureHook()) } diff --git a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/FeatureFlagIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/FeatureFlagIntegrationTest.kt index 421bad16d3a..e8c93a146e8 100644 --- a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/FeatureFlagIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/FeatureFlagIntegrationTest.kt @@ -17,7 +17,7 @@ class FeatureFlagIntegrationTest : IntegrationTest() { assertThat( awaitTransaction("new-checkout-flow") - .hasOp("http.server", FeatureFlag("flag.evaluation.new-checkout-flow", true)) + .hasOp("http.server", FeatureFlag("flag.evaluation.new-checkout-flow", true)), ) .isTrue() } @@ -28,7 +28,7 @@ class FeatureFlagIntegrationTest : IntegrationTest() { assertThat( awaitTransaction("experimental-feature") - .hasOp("http.server", FeatureFlag("flag.evaluation.experimental-feature", false)) + .hasOp("http.server", FeatureFlag("flag.evaluation.experimental-feature", false)), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/GraphqlIntegrationTest.kt index b3b68405c07..1d53b8ae00b 100644 --- a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/GraphqlIntegrationTest.kt @@ -60,7 +60,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `batch loaded fields are traced`() { val response = graphql( - """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/MetricsIntegrationTest.kt index 8feb647f4dd..23a85483e6e 100644 --- a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/PersonIntegrationTest.kt index 3f8ba722099..cde6542b294 100644 --- a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/PersonIntegrationTest.kt @@ -49,14 +49,14 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasOp( "http.server", FeatureFlag("flag.evaluation.transaction-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughSentryApi", FeatureFlag("flag.evaluation.my-feature-flag", true), - ) + ), ) .isTrue() @@ -88,7 +88,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db.query", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/TodoController.kt b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/TodoController.kt index 5edb7bc6aa1..69afbeb4ede 100644 --- a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/TodoController.kt +++ b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/TodoController.kt @@ -37,7 +37,7 @@ open class TodoController( return SentryReactorUtils.withSentry( Mono.just(true).publishOn(Schedulers.boundedElastic()).flatMap { webClient.get().uri(url).retrieve().bodyToMono(Todo::class.java) - } + }, ) .block() } diff --git a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/TodoIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/TodoIntegrationTest.kt index bb3e2d6a99a..bd966e3e370 100644 --- a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/TodoIntegrationTest.kt @@ -40,7 +40,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET http://localhost:$port/stub/todos/1", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/AgentApp.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/AgentApp.kt index 6864d4d55c9..87e28ead08b 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/AgentApp.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/AgentApp.kt @@ -57,13 +57,13 @@ object AgentApp { app.close() kafka.destroy() server.close() - } + }, ) } // The agent instruments classes as they load, which on a busy CI runner has taken over a minute. val restTemplate = TestRestTemplate( - RestTemplateBuilder().rootUri("http://localhost:${app.awaitPort(timeoutSeconds = 180)}") + RestTemplateBuilder().rootUri("http://localhost:${app.awaitPort(timeoutSeconds = 180)}"), ) } diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/GraphqlIntegrationTest.kt index 8d54574b613..c05183b940c 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/GraphqlIntegrationTest.kt @@ -65,7 +65,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `query with batch loaded fields is traced`() { val response = graphql( - """query TasksAndAssigneesQuery { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query TasksAndAssigneesQuery { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/MetricsIntegrationTest.kt index 3ac6b4d2f0c..535396ef5fa 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/MetricsIntegrationTest.kt @@ -34,7 +34,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/PersonIntegrationTest.kt index 62b2012163a..720af739ed6 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/PersonIntegrationTest.kt @@ -48,21 +48,21 @@ class PersonIntegrationTest : IntegrationTest() { assertThat(transactionEnvelope.header.sdkVersion!!.name) .isEqualTo( if (AgentApp.autoInit) "sentry.java.opentelemetry.agent" - else "sentry.java.spring-boot.jakarta" + else "sentry.java.spring-boot.jakarta", ) val transaction = transactionEnvelope.transaction()!! assertThat( transaction.hasOp( "http.server", FeatureFlag("flag.evaluation.transaction-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughOtelApi", FeatureFlag("flag.evaluation.my-feature-flag", true), - ) + ), ) .isTrue() assertThat(transaction.hasSpanWithOp("spanCreatedThroughSentryApi")).isTrue() @@ -128,7 +128,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/TodoIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/TodoIntegrationTest.kt index 0f5e7042b67..c45248c8d60 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/jakarta/otelagentintegrationtest/TodoIntegrationTest.kt @@ -39,7 +39,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET ${restTemplate.rootUri}/stub/todos/1", - ) + ), ) .isTrue() return transaction diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/GraphqlIntegrationTest.kt index d733939e1d4..446ed60bd28 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/GraphqlIntegrationTest.kt @@ -61,7 +61,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `query with batch loaded fields is traced`() { val response = graphql( - """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/MetricsIntegrationTest.kt index f3c52653001..98e40a30724 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/PersonIntegrationTest.kt index e2ca6eb7b56..2a84acf328b 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/PersonIntegrationTest.kt @@ -54,14 +54,14 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOp( "personSpanThroughOtelAnnotation", FeatureFlag("flag.evaluation.outer-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughOtelApi", FeatureFlag("flag.evaluation.inner-feature-flag", true), - ) + ), ) .isTrue() assertThat(transaction.hasSpanWithOp("spanCreatedThroughSentryApi", noFeatureFlags = true)) @@ -128,7 +128,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/TodoController.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/TodoController.kt index 8a8d8bb1d6c..1d2511d7324 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/TodoController.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/TodoController.kt @@ -37,7 +37,7 @@ open class TodoController( return SentryReactorUtils.withSentry( Mono.just(true).publishOn(Schedulers.boundedElastic()).flatMap { webClient.get().uri(url).retrieve().bodyToMono(Todo::class.java) - } + }, ) .block() } diff --git a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/TodoIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/TodoIntegrationTest.kt index 08cb9cdf69d..1c2cf3f62f1 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/jakarta/otelnoagentintegrationtest/TodoIntegrationTest.kt @@ -42,7 +42,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET http://localhost:$port/stub/todos/1", - ) + ), ) .isTrue() return transaction diff --git a/sentry-spring-boot-jakarta/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/jakarta/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/jakarta/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt index 5d5cfb3f732..4decb92942b 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/jakarta/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/jakarta/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsWebfluxIntegrationTest : WebfluxIntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/jakarta/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/jakarta/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt index 57d51eb41bd..b2022186115 100644 --- a/sentry-spring-boot-jakarta/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/jakarta/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/jakarta/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt @@ -21,7 +21,7 @@ class TodoWebfluxIntegrationTest : WebfluxIntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET ${restTemplate.rootUri}/stub/todos/1", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentryAutoConfiguration.java b/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentryAutoConfiguration.java index ea1ed76c31d..dbf73c1618a 100644 --- a/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentryAutoConfiguration.java +++ b/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentryAutoConfiguration.java @@ -175,12 +175,11 @@ static class OpenTelemetryNoAgentConfiguration {} final @NotNull ObjectProvider gitProperties) { optionsConfigurations.forEach( optionsConfiguration -> optionsConfiguration.configure(options)); - gitProperties.ifAvailable( - git -> { - if (options.getRelease() == null && options.isUseGitCommitIdAsRelease()) { - options.setRelease(git.getCommitId()); - } - }); + gitProperties.ifAvailable(git -> { + if (options.getRelease() == null && options.isUseGitCommitIdAsRelease()) { + options.setRelease(git.getCommitId()); + } + }); spanFactory.ifAvailable(options::setSpanFactory); options.setSentryClientName( diff --git a/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentryLogbackInitializer.java b/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentryLogbackInitializer.java index e7902c99668..45963f2c394 100644 --- a/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentryLogbackInitializer.java +++ b/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentryLogbackInitializer.java @@ -39,27 +39,26 @@ public boolean supportsEventType(final @NotNull ResolvableType eventType) { @Override public void onApplicationEvent(final @NotNull ApplicationEvent event) { - this.loggers.forEach( - loggerName -> { - final Logger logger = (Logger) LoggerFactory.getLogger(loggerName); - if (!isSentryAppenderRegistered(logger)) { - final SentryAppender sentryAppender = getSentryAppender(); + this.loggers.forEach(loggerName -> { + final Logger logger = (Logger) LoggerFactory.getLogger(loggerName); + if (!isSentryAppenderRegistered(logger)) { + final SentryAppender sentryAppender = getSentryAppender(); - sentryAppender.setLogsEnabled(sentryProperties.getLogging().getLogsEnabled()); - Optional.ofNullable(sentryProperties.getLogging().getMinimumBreadcrumbLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumBreadcrumbLevel); - Optional.ofNullable(sentryProperties.getLogging().getMinimumEventLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumEventLevel); - Optional.ofNullable(sentryProperties.getLogging().getMinimumLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumLevel); + sentryAppender.setLogsEnabled(sentryProperties.getLogging().getLogsEnabled()); + Optional.ofNullable(sentryProperties.getLogging().getMinimumBreadcrumbLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumBreadcrumbLevel); + Optional.ofNullable(sentryProperties.getLogging().getMinimumEventLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumEventLevel); + Optional.ofNullable(sentryProperties.getLogging().getMinimumLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumLevel); - sentryAppender.start(); - logger.addAppender(sentryAppender); - } - }); + sentryAppender.start(); + logger.addAppender(sentryAppender); + } + }); } @NotNull diff --git a/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentrySpanRestClientCustomizer.java b/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentrySpanRestClientCustomizer.java index 304fb6911e9..9f2439ddaf7 100644 --- a/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentrySpanRestClientCustomizer.java +++ b/sentry-spring-boot-jakarta/src/main/java/io/sentry/spring/boot/jakarta/SentrySpanRestClientCustomizer.java @@ -17,14 +17,13 @@ public SentrySpanRestClientCustomizer(final @NotNull IScopes scopes) { @Override public void customize(final @NotNull RestClient.Builder restClientBuilder) { - restClientBuilder.requestInterceptors( - clientHttpRequestInterceptors -> { - // As the SentrySpanClientHttpRequestInterceptor is being created in this class, this - // might not work - // if somebody registers it from an outside. - if (!clientHttpRequestInterceptors.contains(interceptor)) { - clientHttpRequestInterceptors.add(interceptor); - } - }); + restClientBuilder.requestInterceptors(clientHttpRequestInterceptors -> { + // As the SentrySpanClientHttpRequestInterceptor is being created in this class, this + // might not work + // if somebody registers it from an outside. + if (!clientHttpRequestInterceptors.contains(interceptor)) { + clientHttpRequestInterceptors.add(interceptor); + } + }); } } diff --git a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryAutoConfigurationTest.kt b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryAutoConfigurationTest.kt index 8e127287cfd..e3867e74080 100644 --- a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryAutoConfigurationTest.kt +++ b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryAutoConfigurationTest.kt @@ -107,7 +107,7 @@ class SentryAutoConfigurationTest { SentryAutoConfiguration::class.java, WebMvcAutoConfiguration::class.java, SentryProfilerAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -128,7 +128,7 @@ class SentryAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runners for different test categories @@ -136,14 +136,14 @@ class SentryAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls private val tracingEnabledRunner = baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj", "sentry.traces-sample-rate=1.0") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls @Test @@ -197,7 +197,7 @@ class SentryAutoConfigurationTest { .run { assertThat(it).hasSingleBean(Sentry.OptionsConfiguration::class.java) assertThat( - it.getBean(Sentry.OptionsConfiguration::class.java, "customOptionsConfiguration") + it.getBean(Sentry.OptionsConfiguration::class.java, "customOptionsConfiguration"), ) .isNotNull } @@ -207,7 +207,7 @@ class SentryAutoConfigurationTest { fun `GraphQL specification error type filtering is disabled by default`() { dsnEnabledRunner.run { assertThat( - it.getBean(SentryProperties::class.java).graphql.isEnableSpecificationErrorTypeFiltering + it.getBean(SentryProperties::class.java).graphql.isEnableSpecificationErrorTypeFiltering, ) .isFalse() } @@ -223,7 +223,7 @@ class SentryAutoConfigurationTest { it .getBean(SentryProperties::class.java) .graphql - .isEnableSpecificationErrorTypeFiltering + .isEnableSpecificationErrorTypeFiltering, ) .isEqualTo(enabled) } @@ -633,7 +633,7 @@ class SentryAutoConfigurationTest { contextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj", "sentry.send-default-pii=true") .withConfiguration( - UserConfigurations.of(SentryHighestOrderUserProviderConfiguration::class.java) + UserConfigurations.of(SentryHighestOrderUserProviderConfiguration::class.java), ) .run { val userProviders = it.getSentryUserProviders() @@ -915,7 +915,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -927,7 +927,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -942,7 +942,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -958,7 +958,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryNoAgent") + .contains("SpringBoot3OpenTelemetryNoAgent"), ) } } @@ -973,7 +973,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryNoAgent") + .contains("SpringBoot3OpenTelemetryNoAgent"), ) } } @@ -987,14 +987,14 @@ class SentryAutoConfigurationTest { FilteredClassLoader( AgentMarker::class.java, SentryAutoConfigurationCustomizerProvider::class.java, - ) + ), ) .withUserConfiguration(OtelBeanConfig::class.java) .run { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryNoAgent") + .contains("SpringBoot3OpenTelemetryNoAgent"), ) } } @@ -1009,7 +1009,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit") + .contains("SpringBoot3OpenTelemetryAgentWithoutAutoInit"), ) } } @@ -1065,7 +1065,7 @@ class SentryAutoConfigurationTest { FilteredClassLoader( io.sentry.graphql.SentryInstrumentation::class.java, io.sentry.graphql22.SentryInstrumentation::class.java, - ) + ), ) .run { assertThat(it).doesNotHaveBean(io.sentry.graphql.SentryInstrumentation::class.java) @@ -1133,7 +1133,7 @@ class SentryAutoConfigurationTest { captor.allValues.map { envelope -> String(envelope.items.first().data, Charsets.UTF_8) } assertThat(payloads).allMatch { payload -> payload.contains( - "\"monitor_slug\":\"sentry-auto-configuration-test-scheduled-jobs-sync\"" + "\"monitor_slug\":\"sentry-auto-configuration-test-scheduled-jobs-sync\"", ) } assertThat(payloads[0]).contains("\"value\":1,\"unit\":\"hour\"") @@ -1199,7 +1199,7 @@ class SentryAutoConfigurationTest { assertThat(it) .getBean(IProfileConverter::class.java) .isInstanceOf( - AsyncProfilerProfileConverterProvider.AsyncProfilerProfileConverter::class.java + AsyncProfilerProfileConverterProvider.AsyncProfilerProfileConverter::class.java, ) assertThat(it) .getBean(IContinuousProfiler::class.java) diff --git a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryLog4j2AppenderAutoConfigurationTest.kt b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryLog4j2AppenderAutoConfigurationTest.kt index 4523b09e5c2..4317bc12f7f 100644 --- a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryLog4j2AppenderAutoConfigurationTest.kt +++ b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryLog4j2AppenderAutoConfigurationTest.kt @@ -40,7 +40,7 @@ class SentryLog4j2AppenderAutoConfigurationTest { AutoConfigurations.of( SentryLog4j2AppenderAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( "sentry.shutdownTimeoutMillis=0", @@ -155,7 +155,7 @@ class SentryLog4j2AppenderAutoConfigurationTest { .run { assertThat(rootLogger.getAppenders(SentryAppender::class.java)).hasSize(1) assertThat( - configuration.getLoggerConfig("com.example").getAppenders(SentryAppender::class.java) + configuration.getLoggerConfig("com.example").getAppenders(SentryAppender::class.java), ) .hasSize(1) } @@ -320,7 +320,7 @@ class SentryLog4j2AppenderAutoConfigurationTest { } fun org.apache.logging.log4j.core.config.LoggerConfig.getAppenders( - clazz: Class + clazz: Class, ): List { return this.appenders.values.filter { it.javaClass == clazz } } diff --git a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryLogbackAppenderAutoConfigurationTest.kt b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryLogbackAppenderAutoConfigurationTest.kt index fb324265b97..980883b40f2 100644 --- a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryLogbackAppenderAutoConfigurationTest.kt +++ b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryLogbackAppenderAutoConfigurationTest.kt @@ -27,7 +27,7 @@ class SentryLogbackAppenderAutoConfigurationTest { AutoConfigurations.of( SentryLogbackAppenderAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -48,7 +48,7 @@ class SentryLogbackAppenderAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runner for tests requiring DSN @@ -56,7 +56,7 @@ class SentryLogbackAppenderAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls private val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger diff --git a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryOkHttpAutoConfigurationTest.kt b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryOkHttpAutoConfigurationTest.kt index d53f4ce0a1b..98168c4aa8c 100644 --- a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryOkHttpAutoConfigurationTest.kt +++ b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryOkHttpAutoConfigurationTest.kt @@ -250,7 +250,7 @@ class SentryOkHttpAutoConfigurationTest { SentryOkHttpInterceptor::class.java, SentryAutoConfigurationCustomizerProvider::class.java, AgentMarker::class.java, - ) + ), ) .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration(OkHttpClientConfiguration::class.java) diff --git a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentrySpanRestClientCustomizerTest.kt b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentrySpanRestClientCustomizerTest.kt index bdb6a56e55e..8b8478ca873 100644 --- a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentrySpanRestClientCustomizerTest.kt +++ b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentrySpanRestClientCustomizerTest.kt @@ -79,7 +79,7 @@ class SentrySpanRestClientCustomizerTest { sentryOptions.dsn = "https://key@sentry.io/proj" mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -156,8 +156,8 @@ class SentrySpanRestClientCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=aTransaction")) @@ -271,8 +271,8 @@ class SentrySpanRestClientCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-trace_id")) diff --git a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentrySpanRestTemplateCustomizerTest.kt b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentrySpanRestTemplateCustomizerTest.kt index d00849a025e..f9339dd29fc 100644 --- a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentrySpanRestTemplateCustomizerTest.kt +++ b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentrySpanRestTemplateCustomizerTest.kt @@ -83,7 +83,7 @@ class SentrySpanRestTemplateCustomizerTest { sentryOptions.dsn = "https://key@sentry.io/proj" mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -141,8 +141,8 @@ class SentrySpanRestTemplateCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=aTransaction")) @@ -229,8 +229,8 @@ class SentrySpanRestTemplateCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-trace_id")) diff --git a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryWebfluxAutoConfigurationTest.kt b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryWebfluxAutoConfigurationTest.kt index 6b67f2d6e91..4955cde8be2 100644 --- a/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryWebfluxAutoConfigurationTest.kt +++ b/sentry-spring-boot-jakarta/src/test/kotlin/io/sentry/spring/boot/jakarta/SentryWebfluxAutoConfigurationTest.kt @@ -25,7 +25,7 @@ class SentryWebfluxAutoConfigurationTest { WebFluxAutoConfiguration::class.java, SentryWebfluxAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -46,7 +46,7 @@ class SentryWebfluxAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runner for tests requiring DSN @@ -54,7 +54,7 @@ class SentryWebfluxAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls @Test diff --git a/sentry-spring-boot/build.gradle.kts b/sentry-spring-boot/build.gradle.kts index b05690fa905..7325cbb2e7b 100644 --- a/sentry-spring-boot/build.gradle.kts +++ b/sentry-spring-boot/build.gradle.kts @@ -1,4 +1,4 @@ -import io.sentry.gradle.ChildJvmTestArguments +import io.sentry.gradle.otelAgentTests import net.ltgt.gradle.errorprone.errorprone import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.tasks.KotlinCompile @@ -7,6 +7,7 @@ plugins { `java-library` id("io.sentry.javadoc") id("io.sentry.spring-boot-matrix") + id("io.sentry.otel-agent-tests") alias(libs.plugins.kotlin.jvm) alias(libs.plugins.errorprone) alias(libs.plugins.gradle.versions) @@ -138,22 +139,7 @@ tasks.jar { } } -// The OpenTelemetry agent tests run this app in a child JVM, on its own classpath like a real app -// with the agent attached, rather than on the test's classpath. -val agentFixture = sourceSets.create("agentFixture") - -// The built agent jar, rather than the plain jar the unit tests compile against. -val otelAgentJar = - configurations.create("otelAgentJar") { - isCanBeResolved = true - isCanBeConsumed = false - isTransitive = false - attributes { - attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) - attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.SHADOWED)) - } - } - +// The app the OpenTelemetry agent tests run in a child JVM. dependencies { "agentFixtureImplementation"(platform(libs.springboot2.bom)) "agentFixtureImplementation"(projects.sentrySpringBootStarter) @@ -170,8 +156,6 @@ dependencies { "agentFixtureImplementation"(libs.springboot.starter.webflux) "agentFixtureImplementation"(libs.spring.kafka2) "agentFixtureRuntimeOnly"(libs.hsqldb) - - otelAgentJar(projects.sentryOpentelemetry.sentryOpentelemetryAgent) } testing { @@ -253,9 +237,8 @@ testing { } } - // Runs agentFixture's app with the agent initializing Sentry. - register("integrationTestOtelAgent") { - useJUnit() + // The OpenTelemetry agent tests, against agentFixture's app. + named("integrationTestOtelAgent") { dependencies { implementation(platform(libs.springboot2.bom)) implementation(projects.sentryTestSupport) @@ -266,42 +249,10 @@ testing { implementation(libs.springboot.starter.web) implementation(libs.spring.kafka2.test) } - targets.all { testTask.configure { runAgentFixture(autoInit = true) } } } } } -/** - * Has the OpenTelemetry agent tests start agentFixture's app in a child JVM, with the built agent - * attached. [autoInit] decides whether the agent initializes Sentry or, as with - * `SENTRY_AUTO_INIT=false`, the Spring Boot starter. [appClasspath] is the app's classpath for - * another Spring Boot version. - */ -fun Test.runAgentFixture( - autoInit: Boolean, - appClasspath: FileCollection = agentFixture.runtimeClasspath, -) { - jvmArgumentProviders.add( - objects.newInstance().apply { - agentJar.from(otelAgentJar) - this.appClasspath.from(appClasspath) - } - ) - systemProperty("sentry.test.agentAutoInit", autoInit) -} - -// The same tests with the Spring Boot starter initializing Sentry. Each test JVM starts one app, so -// this mode needs a task of its own, which Gradle runs in parallel with the suite's. -tasks.register("integrationTestOtelAgentWithoutAutoInit") { - description = "Runs the OpenTelemetry agent tests with SENTRY_AUTO_INIT=false." - group = LifecycleBasePlugin.VERIFICATION_GROUP - val sources = sourceSets["integrationTestOtelAgent"] - testClassesDirs = sources.output.classesDirs - classpath = sources.runtimeClasspath - useJUnit() - runAgentFixture(autoInit = false) -} - // The Spring Boot Gradle plugin compiles apps with parameter names, which Spring reads, for example // to resolve `#id` in a cache key. listOf( @@ -321,10 +272,5 @@ springBootMatrix { test("integrationTest") test("integrationTestWebflux") test("integrationTestOtelNoAgent") - test("integrationTestOtelAgent") { version -> - runAgentFixture(autoInit = true, appClasspath = runtimeClasspath("agentFixture", version)) - } - test("integrationTestOtelAgent", name = "integrationTestOtelAgentWithoutAutoInit") { version -> - runAgentFixture(autoInit = false, appClasspath = runtimeClasspath("agentFixture", version)) - } + otelAgentTests() } diff --git a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/GraphqlIntegrationTest.kt index 9265ad457c0..30f901be230 100644 --- a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/GraphqlIntegrationTest.kt @@ -60,7 +60,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `batch loaded fields are traced`() { val response = graphql( - """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/MetricsIntegrationTest.kt index edfc5459e7e..c7246a1ef6b 100644 --- a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/PersonIntegrationTest.kt b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/PersonIntegrationTest.kt index 5a15d818166..d6b7d8c1f55 100644 --- a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/PersonIntegrationTest.kt @@ -49,14 +49,14 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasOp( "http.server", FeatureFlag("flag.evaluation.transaction-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughSentryApi", FeatureFlag("flag.evaluation.my-feature-flag", true), - ) + ), ) .isTrue() @@ -88,7 +88,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db.query", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/TodoIntegrationTest.kt b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/TodoIntegrationTest.kt index efe6a0562b0..5a21f1c1d40 100644 --- a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/TodoIntegrationTest.kt @@ -32,7 +32,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET ${restTemplate.rootUri}/stub/todos/1", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/AgentApp.kt b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/AgentApp.kt index 32dd96a86d5..9d63b216e73 100644 --- a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/AgentApp.kt +++ b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/AgentApp.kt @@ -74,7 +74,7 @@ class AgentApp(args: List = emptyList()) : Closeable { private val sharedApp: Result by lazy { try { Result.success( - AgentApp().also { app -> Runtime.getRuntime().addShutdownHook(Thread { app.close() }) } + AgentApp().also { app -> Runtime.getRuntime().addShutdownHook(Thread { app.close() }) }, ) } catch (e: IllegalStateException) { Result.failure(e) diff --git a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/GraphqlIntegrationTest.kt index 14efac1fdbd..e881a8af4d0 100644 --- a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/GraphqlIntegrationTest.kt @@ -65,7 +65,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `query with batch loaded fields is traced`() { val response = graphql( - """query TasksAndAssigneesQuery { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query TasksAndAssigneesQuery { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/KafkaOtelCoexistenceIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/KafkaOtelCoexistenceIntegrationTest.kt index 6913a908fa2..d3f2aa6f4ba 100644 --- a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/KafkaOtelCoexistenceIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/KafkaOtelCoexistenceIntegrationTest.kt @@ -68,7 +68,7 @@ class KafkaOtelCoexistenceIntegrationTest : IntegrationTest() { listOf( "--spring.profiles.active=kafka", "--spring.kafka.bootstrap-servers=${kafka.brokersAsString}", - ) + ), ) } diff --git a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/MetricsIntegrationTest.kt index cc2d771b5d7..6cbe99453d8 100644 --- a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/MetricsIntegrationTest.kt @@ -34,7 +34,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/PersonIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/PersonIntegrationTest.kt index 53a52f77412..4b341af6f64 100644 --- a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/PersonIntegrationTest.kt @@ -47,21 +47,21 @@ class PersonIntegrationTest : IntegrationTest() { // Whichever initializes Sentry names the SDK, which shows that each mode takes its own path. assertThat(transactionEnvelope.header.sdkVersion!!.name) .isEqualTo( - if (AgentApp.autoInit) "sentry.java.opentelemetry.agent" else "sentry.java.spring-boot" + if (AgentApp.autoInit) "sentry.java.opentelemetry.agent" else "sentry.java.spring-boot", ) val transaction = transactionEnvelope.transaction()!! assertThat( transaction.hasOp( "http.server", FeatureFlag("flag.evaluation.transaction-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughOtelApi", FeatureFlag("flag.evaluation.my-feature-flag", true), - ) + ), ) .isTrue() assertThat(transaction.hasSpanWithOp("spanCreatedThroughSentryApi")).isTrue() @@ -127,7 +127,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/TodoIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/TodoIntegrationTest.kt index ca3890e38f6..c2fbd826704 100644 --- a/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelAgent/kotlin/io/sentry/spring/boot/otelagentintegrationtest/TodoIntegrationTest.kt @@ -32,7 +32,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET ${restTemplate.rootUri}/stub/todos/1", - ) + ), ) .isTrue() return transaction diff --git a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/GraphqlIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/GraphqlIntegrationTest.kt index 052da122bd9..dfd19e1fbb2 100644 --- a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/GraphqlIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/GraphqlIntegrationTest.kt @@ -61,7 +61,7 @@ class GraphqlIntegrationTest : IntegrationTest() { fun `query with batch loaded fields is traced`() { val response = graphql( - """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""" + """query { tasks(projectSlug: "project-slug") { id assigneeId assignee { id } creatorId creator { id } } }""", ) assertThat(response.has("errors")).isFalse() diff --git a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/KafkaOtelCoexistenceIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/KafkaOtelCoexistenceIntegrationTest.kt index 5efef8875b1..4a6b3ca2937 100644 --- a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/KafkaOtelCoexistenceIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/KafkaOtelCoexistenceIntegrationTest.kt @@ -18,7 +18,7 @@ import org.springframework.test.context.TestPropertySource @EmbeddedKafka(topics = [KAFKA_TOPIC], bootstrapServersProperty = "spring.kafka.bootstrap-servers") @TestPropertySource( properties = - ["sentry.enable-queue-tracing=true", "spring.kafka.consumer.auto-offset-reset=earliest"] + ["sentry.enable-queue-tracing=true", "spring.kafka.consumer.auto-offset-reset=earliest"], ) class KafkaOtelCoexistenceIntegrationTest : IntegrationTest() { diff --git a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/MetricsIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/MetricsIntegrationTest.kt index e7087c7b377..e39d332b6db 100644 --- a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/PersonIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/PersonIntegrationTest.kt index 6e9b1c1038b..2ca952969b9 100644 --- a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/PersonIntegrationTest.kt @@ -54,14 +54,14 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOp( "personSpanThroughOtelAnnotation", FeatureFlag("flag.evaluation.outer-feature-flag", true), - ) + ), ) .isTrue() assertThat( transaction.hasSpanWithOp( "spanCreatedThroughOtelApi", FeatureFlag("flag.evaluation.inner-feature-flag", true), - ) + ), ) .isTrue() assertThat(transaction.hasSpanWithOp("spanCreatedThroughSentryApi", noFeatureFlags = true)) @@ -128,7 +128,7 @@ class PersonIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "db", "insert into person (firstName, lastName) values (?, ?)", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/TodoIntegrationTest.kt b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/TodoIntegrationTest.kt index 4b87dc571c9..9a65e54ed65 100644 --- a/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/TodoIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestOtelNoAgent/kotlin/io/sentry/spring/boot/otelnoagentintegrationtest/TodoIntegrationTest.kt @@ -32,7 +32,7 @@ class TodoIntegrationTest : IntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET ${restTemplate.rootUri}/stub/todos/1", - ) + ), ) .isTrue() return transaction diff --git a/sentry-spring-boot/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt b/sentry-spring-boot/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt index 1b3eb4775df..f61b022a95c 100644 --- a/sentry-spring-boot/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/webfluxintegrationtest/MetricsWebfluxIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsWebfluxIntegrationTest : WebfluxIntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-boot/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt b/sentry-spring-boot/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt index de7314d0e66..a19fc61d810 100644 --- a/sentry-spring-boot/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTestWebflux/kotlin/io/sentry/spring/boot/webfluxintegrationtest/TodoWebfluxIntegrationTest.kt @@ -21,7 +21,7 @@ class TodoWebfluxIntegrationTest : WebfluxIntegrationTest() { transaction.hasSpanWithOpAndDescription( "http.client", "GET ${restTemplate.rootUri}/stub/todos/1", - ) + ), ) .isTrue() } diff --git a/sentry-spring-boot/src/main/java/io/sentry/spring/boot/SentryAutoConfiguration.java b/sentry-spring-boot/src/main/java/io/sentry/spring/boot/SentryAutoConfiguration.java index ec54ec292b0..e64d5821c96 100644 --- a/sentry-spring-boot/src/main/java/io/sentry/spring/boot/SentryAutoConfiguration.java +++ b/sentry-spring-boot/src/main/java/io/sentry/spring/boot/SentryAutoConfiguration.java @@ -170,12 +170,11 @@ static class OpenTelemetryNoAgentConfiguration {} final @NotNull ObjectProvider gitProperties) { optionsConfigurations.forEach( optionsConfiguration -> optionsConfiguration.configure(options)); - gitProperties.ifAvailable( - git -> { - if (options.getRelease() == null && options.isUseGitCommitIdAsRelease()) { - options.setRelease(git.getCommitId()); - } - }); + gitProperties.ifAvailable(git -> { + if (options.getRelease() == null && options.isUseGitCommitIdAsRelease()) { + options.setRelease(git.getCommitId()); + } + }); spanFactory.ifAvailable(options::setSpanFactory); options.setSentryClientName( diff --git a/sentry-spring-boot/src/main/java/io/sentry/spring/boot/SentryLogbackInitializer.java b/sentry-spring-boot/src/main/java/io/sentry/spring/boot/SentryLogbackInitializer.java index a064d8e1299..c8a306742b8 100644 --- a/sentry-spring-boot/src/main/java/io/sentry/spring/boot/SentryLogbackInitializer.java +++ b/sentry-spring-boot/src/main/java/io/sentry/spring/boot/SentryLogbackInitializer.java @@ -39,27 +39,26 @@ public boolean supportsEventType(final @NotNull ResolvableType eventType) { @Override public void onApplicationEvent(final @NotNull ApplicationEvent event) { - this.loggers.forEach( - loggerName -> { - final Logger logger = (Logger) LoggerFactory.getLogger(loggerName); - if (!isSentryAppenderRegistered(logger)) { - final SentryAppender sentryAppender = getSentryAppender(); + this.loggers.forEach(loggerName -> { + final Logger logger = (Logger) LoggerFactory.getLogger(loggerName); + if (!isSentryAppenderRegistered(logger)) { + final SentryAppender sentryAppender = getSentryAppender(); - sentryAppender.setLogsEnabled(sentryProperties.getLogging().getLogsEnabled()); - Optional.ofNullable(sentryProperties.getLogging().getMinimumBreadcrumbLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumBreadcrumbLevel); - Optional.ofNullable(sentryProperties.getLogging().getMinimumEventLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumEventLevel); - Optional.ofNullable(sentryProperties.getLogging().getMinimumLevel()) - .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) - .ifPresent(sentryAppender::setMinimumLevel); + sentryAppender.setLogsEnabled(sentryProperties.getLogging().getLogsEnabled()); + Optional.ofNullable(sentryProperties.getLogging().getMinimumBreadcrumbLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumBreadcrumbLevel); + Optional.ofNullable(sentryProperties.getLogging().getMinimumEventLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumEventLevel); + Optional.ofNullable(sentryProperties.getLogging().getMinimumLevel()) + .map(slf4jLevel -> Level.toLevel(slf4jLevel.name())) + .ifPresent(sentryAppender::setMinimumLevel); - sentryAppender.start(); - logger.addAppender(sentryAppender); - } - }); + sentryAppender.start(); + logger.addAppender(sentryAppender); + } + }); } @NotNull diff --git a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryAutoConfigurationTest.kt b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryAutoConfigurationTest.kt index 08642d23a87..258154ebb37 100644 --- a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryAutoConfigurationTest.kt +++ b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryAutoConfigurationTest.kt @@ -106,7 +106,7 @@ class SentryAutoConfigurationTest { SentryAutoConfiguration::class.java, WebMvcAutoConfiguration::class.java, SentryProfilerAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -127,7 +127,7 @@ class SentryAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runners for different test categories @@ -135,14 +135,14 @@ class SentryAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls private val tracingEnabledRunner = baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj", "sentry.traces-sample-rate=1.0") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls @Test @@ -195,7 +195,7 @@ class SentryAutoConfigurationTest { .run { assertThat(it).hasSingleBean(Sentry.OptionsConfiguration::class.java) assertThat( - it.getBean(Sentry.OptionsConfiguration::class.java, "customOptionsConfiguration") + it.getBean(Sentry.OptionsConfiguration::class.java, "customOptionsConfiguration"), ) .isNotNull } @@ -205,7 +205,7 @@ class SentryAutoConfigurationTest { fun `GraphQL specification error type filtering is disabled by default`() { dsnEnabledRunner.run { assertThat( - it.getBean(SentryProperties::class.java).graphql.isEnableSpecificationErrorTypeFiltering + it.getBean(SentryProperties::class.java).graphql.isEnableSpecificationErrorTypeFiltering, ) .isFalse() } @@ -221,7 +221,7 @@ class SentryAutoConfigurationTest { it .getBean(SentryProperties::class.java) .graphql - .isEnableSpecificationErrorTypeFiltering + .isEnableSpecificationErrorTypeFiltering, ) .isEqualTo(enabled) } @@ -631,7 +631,7 @@ class SentryAutoConfigurationTest { contextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj", "sentry.send-default-pii=true") .withConfiguration( - UserConfigurations.of(SentryHighestOrderUserProviderConfiguration::class.java) + UserConfigurations.of(SentryHighestOrderUserProviderConfiguration::class.java), ) .run { val userProviders = it.getSentryUserProviders() @@ -906,7 +906,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryAgentWithoutAutoInit") + .contains("SpringBootOpenTelemetryAgentWithoutAutoInit"), ) } } @@ -918,7 +918,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryAgentWithoutAutoInit") + .contains("SpringBootOpenTelemetryAgentWithoutAutoInit"), ) } } @@ -933,7 +933,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryAgentWithoutAutoInit") + .contains("SpringBootOpenTelemetryAgentWithoutAutoInit"), ) } } @@ -949,7 +949,7 @@ class SentryAutoConfigurationTest { assertTrue( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryNoAgent") + .contains("SpringBootOpenTelemetryNoAgent"), ) } } @@ -964,7 +964,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryNoAgent") + .contains("SpringBootOpenTelemetryNoAgent"), ) } } @@ -978,14 +978,14 @@ class SentryAutoConfigurationTest { FilteredClassLoader( AgentMarker::class.java, SentryAutoConfigurationCustomizerProvider::class.java, - ) + ), ) .withUserConfiguration(OtelBeanConfig::class.java) .run { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryNoAgent") + .contains("SpringBootOpenTelemetryNoAgent"), ) } } @@ -1000,7 +1000,7 @@ class SentryAutoConfigurationTest { assertFalse( SentryIntegrationPackageStorage.getInstance() .integrations - .contains("SpringBootOpenTelemetryAgentWithoutAutoInit") + .contains("SpringBootOpenTelemetryAgentWithoutAutoInit"), ) } } @@ -1019,7 +1019,7 @@ class SentryAutoConfigurationTest { assertThat(it) .getBean(IProfileConverter::class.java) .isInstanceOf( - AsyncProfilerProfileConverterProvider.AsyncProfilerProfileConverter::class.java + AsyncProfilerProfileConverterProvider.AsyncProfilerProfileConverter::class.java, ) assertThat(it) .getBean(IContinuousProfiler::class.java) @@ -1170,7 +1170,7 @@ class SentryAutoConfigurationTest { captor.allValues.map { envelope -> String(envelope.items.first().data, Charsets.UTF_8) } assertThat(payloads).allMatch { payload -> payload.contains( - "\"monitor_slug\":\"sentry-auto-configuration-test-scheduled-jobs-sync\"" + "\"monitor_slug\":\"sentry-auto-configuration-test-scheduled-jobs-sync\"", ) } assertThat(payloads[0]).contains("\"value\":1,\"unit\":\"hour\"") diff --git a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryLogbackAppenderAutoConfigurationTest.kt b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryLogbackAppenderAutoConfigurationTest.kt index f6f24bf67ac..7c44d2168b4 100644 --- a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryLogbackAppenderAutoConfigurationTest.kt +++ b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryLogbackAppenderAutoConfigurationTest.kt @@ -27,7 +27,7 @@ class SentryLogbackAppenderAutoConfigurationTest { AutoConfigurations.of( SentryLogbackAppenderAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -48,7 +48,7 @@ class SentryLogbackAppenderAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runner for tests requiring DSN @@ -56,7 +56,7 @@ class SentryLogbackAppenderAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls private val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger diff --git a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryOkHttpAutoConfigurationTest.kt b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryOkHttpAutoConfigurationTest.kt index 92fa6024713..2225ee81d66 100644 --- a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryOkHttpAutoConfigurationTest.kt +++ b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryOkHttpAutoConfigurationTest.kt @@ -250,7 +250,7 @@ class SentryOkHttpAutoConfigurationTest { SentryOkHttpInterceptor::class.java, SentryAutoConfigurationCustomizerProvider::class.java, AgentMarker::class.java, - ) + ), ) .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration(OkHttpClientConfiguration::class.java) diff --git a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentrySpanRestTemplateCustomizerTest.kt b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentrySpanRestTemplateCustomizerTest.kt index 634054d039e..57d8a59603c 100644 --- a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentrySpanRestTemplateCustomizerTest.kt +++ b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentrySpanRestTemplateCustomizerTest.kt @@ -83,7 +83,7 @@ class SentrySpanRestTemplateCustomizerTest { sentryOptions.dsn = "https://key@sentry.io/proj" mockServer.enqueue( - MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()) + MockResponse().setBody("OK").setSocketPolicy(socketPolicy).setResponseCode(status.value()), ) if (isTransactionActive) { @@ -141,8 +141,8 @@ class SentrySpanRestTemplateCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-transaction=aTransaction")) @@ -229,8 +229,8 @@ class SentrySpanRestTemplateCustomizerTest { assertEquals(baggageHeaderValues.size, 1) assertTrue( baggageHeaderValues[0].startsWith( - "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue" - ) + "thirdPartyBaggage=someValue,secondThirdPartyBaggage=secondValue; property;propertyKey=propertyValue,anotherThirdPartyBaggage=anotherValue", + ), ) assertTrue(baggageHeaderValues[0].contains("sentry-public_key=key")) assertTrue(baggageHeaderValues[0].contains("sentry-trace_id")) diff --git a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryWebfluxAutoConfigurationTest.kt b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryWebfluxAutoConfigurationTest.kt index dea2c005881..2f448015cf8 100644 --- a/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryWebfluxAutoConfigurationTest.kt +++ b/sentry-spring-boot/src/test/kotlin/io/sentry/spring/boot/SentryWebfluxAutoConfigurationTest.kt @@ -23,7 +23,7 @@ class SentryWebfluxAutoConfigurationTest { WebFluxAutoConfiguration::class.java, SentryWebfluxAutoConfiguration::class.java, SentryAutoConfiguration::class.java, - ) + ), ) .withPropertyValues( // Speed up tests by reducing timeouts and disabling expensive operations @@ -44,7 +44,7 @@ class SentryWebfluxAutoConfigurationTest { // Use the optimized base runner by default private val contextRunner = baseContextRunner.withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls // Specialized context runner for tests requiring DSN @@ -52,7 +52,7 @@ class SentryWebfluxAutoConfigurationTest { baseContextRunner .withPropertyValues("sentry.dsn=http://key@localhost/proj") .withUserConfiguration( - NoOpTransportConfiguration::class.java + NoOpTransportConfiguration::class.java, ) // Use no-op transport to avoid network calls @Test diff --git a/sentry-spring-jakarta/src/integrationTest/kotlin/io/sentry/spring/jakarta/integrationtest/MetricsIntegrationTest.kt b/sentry-spring-jakarta/src/integrationTest/kotlin/io/sentry/spring/jakarta/integrationtest/MetricsIntegrationTest.kt index 57188f421e7..87c3d8936ca 100644 --- a/sentry-spring-jakarta/src/integrationTest/kotlin/io/sentry/spring/jakarta/integrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring-jakarta/src/integrationTest/kotlin/io/sentry/spring/jakarta/integrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentrySpringFilter.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentrySpringFilter.java index ae26af643ad..a710116896c 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentrySpringFilter.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/SentrySpringFilter.java @@ -84,23 +84,22 @@ protected void doFilterInternal( private void configureScope( final @NotNull IScopes scopes, final @NotNull HttpServletRequest request) { try { - scopes.configureScope( - scope -> { - // set basic request information on the scope - scope.setRequest(requestResolver.resolveSentryRequest(request)); - // transaction name is known at the later stage of request processing, thus it cannot - // be set on the scope - scope.addEventProcessor( - new SentryRequestHttpServletRequestProcessor( - transactionNameProvider, request, scopes.getOptions().getLogger())); - // only if request caches body, add an event processor that sets body on the event - // body is not on the scope, to avoid using memory when no event is triggered during - // request processing - if (request instanceof ContentCachingRequestWrapper) { - scope.addEventProcessor( - new RequestBodyExtractingEventProcessor(request, scopes.getOptions())); - } - }); + scopes.configureScope(scope -> { + // set basic request information on the scope + scope.setRequest(requestResolver.resolveSentryRequest(request)); + // transaction name is known at the later stage of request processing, thus it cannot + // be set on the scope + scope.addEventProcessor( + new SentryRequestHttpServletRequestProcessor( + transactionNameProvider, request, scopes.getOptions().getLogger())); + // only if request caches body, add an event processor that sets body on the event + // body is not on the scope, to avoid using memory when no event is triggered during + // request processing + if (request instanceof ContentCachingRequestWrapper) { + scope.addEventProcessor( + new RequestBodyExtractingEventProcessor(request, scopes.getOptions())); + } + }); } catch (Throwable e) { scopes .getOptions() diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/cache/SentryCacheWrapper.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/cache/SentryCacheWrapper.java index 9b7c551a2d2..1bb201584f0 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/cache/SentryCacheWrapper.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/cache/SentryCacheWrapper.java @@ -128,17 +128,16 @@ public SentryCacheWrapper(final @NotNull Cache delegate, final @NotNull IScopes span.finish(); return null; } - return result.whenComplete( - (value, throwable) -> { - if (throwable != null) { - span.setStatus(SpanStatus.INTERNAL_ERROR); - span.setThrowable(throwable); - } else { - span.setData(SpanDataConvention.CACHE_HIT, value != null); - span.setStatus(SpanStatus.OK); - } - span.finish(); - }); + return result.whenComplete((value, throwable) -> { + if (throwable != null) { + span.setStatus(SpanStatus.INTERNAL_ERROR); + span.setThrowable(throwable); + } else { + span.setData(SpanDataConvention.CACHE_HIT, value != null); + span.setStatus(SpanStatus.OK); + } + span.finish(); + }); } @Override @@ -164,18 +163,17 @@ public CompletableFuture retrieve( span.finish(); throw e; } - return result.whenComplete( - (value, throwable) -> { - if (throwable != null) { - span.setStatus(SpanStatus.INTERNAL_ERROR); - span.setThrowable(throwable); - } else { - span.setData(SpanDataConvention.CACHE_HIT, !loaderInvoked.get()); - span.setData(SpanDataConvention.CACHE_WRITE, loaderInvoked.get()); - span.setStatus(SpanStatus.OK); - } - span.finish(); - }); + return result.whenComplete((value, throwable) -> { + if (throwable != null) { + span.setStatus(SpanStatus.INTERNAL_ERROR); + span.setThrowable(throwable); + } else { + span.setData(SpanDataConvention.CACHE_HIT, !loaderInvoked.get()); + span.setData(SpanDataConvention.CACHE_WRITE, loaderInvoked.get()); + span.setStatus(SpanStatus.OK); + } + span.finish(); + }); } @Override diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentryBatchLoaderRegistry.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentryBatchLoaderRegistry.java index 6a9f33e65f1..8d61a3948f5 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentryBatchLoaderRegistry.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentryBatchLoaderRegistry.java @@ -87,23 +87,21 @@ public BatchLoaderRegistry.RegistrationSpec withOptions(DataLoaderOptions @Override public void registerBatchLoader(BiFunction, BatchLoaderEnvironment, Flux> loader) { - delegate.registerBatchLoader( - (keys, batchLoaderEnvironment) -> { - scopesFromContext(batchLoaderEnvironment) - .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); - return loader.apply(keys, batchLoaderEnvironment); - }); + delegate.registerBatchLoader((keys, batchLoaderEnvironment) -> { + scopesFromContext(batchLoaderEnvironment) + .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); + return loader.apply(keys, batchLoaderEnvironment); + }); } @Override public void registerMappedBatchLoader( BiFunction, BatchLoaderEnvironment, Mono>> loader) { - delegate.registerMappedBatchLoader( - (keys, batchLoaderEnvironment) -> { - scopesFromContext(batchLoaderEnvironment) - .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); - return loader.apply(keys, batchLoaderEnvironment); - }); + delegate.registerMappedBatchLoader((keys, batchLoaderEnvironment) -> { + scopesFromContext(batchLoaderEnvironment) + .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); + return loader.apply(keys, batchLoaderEnvironment); + }); } private @NotNull IScopes scopesFromContext(final @NotNull BatchLoaderEnvironment environment) { diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentryDgsSubscriptionHandler.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentryDgsSubscriptionHandler.java index 3d5b7fe3764..95b20a8ee3f 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentryDgsSubscriptionHandler.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentryDgsSubscriptionHandler.java @@ -22,12 +22,11 @@ public SentryDgsSubscriptionHandler() { final @NotNull InstrumentationFieldFetchParameters parameters) { if (result instanceof Flux) { final @NotNull Flux flux = (Flux) result; - return flux.doOnError( - throwable -> { - final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = - new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); - exceptionReporter.captureThrowable(throwable, exceptionDetails, null); - }); + return flux.doOnError(throwable -> { + final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = + new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); + exceptionReporter.captureThrowable(throwable, exceptionDetails, null); + }); } return result; } diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentrySpringSubscriptionHandler.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentrySpringSubscriptionHandler.java index eec86f5e8b7..654c509ade1 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentrySpringSubscriptionHandler.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/graphql/SentrySpringSubscriptionHandler.java @@ -18,17 +18,15 @@ public final class SentrySpringSubscriptionHandler implements SentrySubscription final @NotNull InstrumentationFieldFetchParameters parameters) { if (result instanceof Flux) { final @NotNull Flux flux = (Flux) result; - return flux.doOnError( - throwable -> { - final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = - new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); - if (throwable instanceof SubscriptionPublisherException - && throwable.getCause() != null) { - exceptionReporter.captureThrowable(throwable.getCause(), exceptionDetails, null); - } else { - exceptionReporter.captureThrowable(throwable, exceptionDetails, null); - } - }); + return flux.doOnError(throwable -> { + final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = + new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); + if (throwable instanceof SubscriptionPublisherException && throwable.getCause() != null) { + exceptionReporter.captureThrowable(throwable.getCause(), exceptionDetails, null); + } else { + exceptionReporter.captureThrowable(throwable, exceptionDetails, null); + } + }); } return result; } diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/tracing/SentrySpanClientWebRequestFilter.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/tracing/SentrySpanClientWebRequestFilter.java index 1a0238e5be0..a29d0e0508a 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/tracing/SentrySpanClientWebRequestFilter.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/tracing/SentrySpanClientWebRequestFilter.java @@ -58,22 +58,20 @@ public SentrySpanClientWebRequestFilter(final @NotNull IScopes scopes) { final @NotNull ClientRequest modifiedRequest = maybeAddTracingHeaders(request, span); return next.exchange(modifiedRequest) - .flatMap( - response -> { - span.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, response.statusCode().value()); - span.setStatus(SpanStatus.fromHttpStatusCode(response.statusCode().value())); - addBreadcrumb(request, response); - span.finish(); - return Mono.just(response); - }) - .onErrorMap( - throwable -> { - span.setThrowable(throwable); - span.setStatus(SpanStatus.INTERNAL_ERROR); - addBreadcrumb(request, null); - span.finish(); - return throwable; - }); + .flatMap(response -> { + span.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, response.statusCode().value()); + span.setStatus(SpanStatus.fromHttpStatusCode(response.statusCode().value())); + addBreadcrumb(request, response); + span.finish(); + return Mono.just(response); + }) + .onErrorMap(throwable -> { + span.setThrowable(throwable); + span.setStatus(SpanStatus.INTERNAL_ERROR); + addBreadcrumb(request, null); + span.finish(); + return throwable; + }); } private @NotNull ClientRequest maybeAddTracingHeaders( @@ -98,11 +96,10 @@ public SentrySpanClientWebRequestFilter(final @NotNull IScopes scopes) { final @Nullable BaggageHeader baggageHeader = tracingHeaders.getBaggageHeader(); if (baggageHeader != null) { - requestBuilder.headers( - httpHeaders -> { - httpHeaders.remove(BaggageHeader.BAGGAGE_HEADER); - httpHeaders.add(baggageHeader.getName(), baggageHeader.getValue()); - }); + requestBuilder.headers(httpHeaders -> { + httpHeaders.remove(BaggageHeader.BAGGAGE_HEADER); + httpHeaders.add(baggageHeader.getName(), baggageHeader.getValue()); + }); } } diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/AbstractSentryWebFilter.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/AbstractSentryWebFilter.java index a3edfd54c83..395de1eb97a 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/AbstractSentryWebFilter.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/AbstractSentryWebFilter.java @@ -128,10 +128,9 @@ private void finishTransaction(ServerWebExchange exchange, ITransaction transact if (statusCode != null) { transaction .getContexts() - .withResponse( - (sentryResponse) -> { - sentryResponse.setStatusCode(statusCode.value()); - }); + .withResponse(sentryResponse -> { + sentryResponse.setStatusCode(statusCode.value()); + }); if (transaction.getStatus() == null) { transaction.setStatus(SpanStatus.fromHttpStatusCode(statusCode.value())); } diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebExceptionHandler.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebExceptionHandler.java index 1e1e387eb21..60e3f7693b6 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebExceptionHandler.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebExceptionHandler.java @@ -43,30 +43,28 @@ public SentryWebExceptionHandler(final @NotNull IScopes scopes) { return SentryReactorUtils.withSentryScopes( Mono.just(ex) - .map( - it -> { - if (!(ex instanceof ResponseStatusException)) { - final Mechanism mechanism = new Mechanism(); - mechanism.setType(MECHANISM_TYPE); - mechanism.setHandled(false); - final Throwable throwable = - new ExceptionMechanismException(mechanism, ex, Thread.currentThread()); - final SentryEvent event = new SentryEvent(throwable); - event.setLevel(SentryLevel.FATAL); - event.setTransaction( - TransactionNameProvider.provideTransactionName(serverWebExchange)); + .map(it -> { + if (!(ex instanceof ResponseStatusException)) { + final Mechanism mechanism = new Mechanism(); + mechanism.setType(MECHANISM_TYPE); + mechanism.setHandled(false); + final Throwable throwable = + new ExceptionMechanismException(mechanism, ex, Thread.currentThread()); + final SentryEvent event = new SentryEvent(throwable); + event.setLevel(SentryLevel.FATAL); + event.setTransaction( + TransactionNameProvider.provideTransactionName(serverWebExchange)); - final Hint hint = new Hint(); - hint.set(WEBFLUX_EXCEPTION_HANDLER_REQUEST, serverWebExchange.getRequest()); - hint.set( - WEBFLUX_EXCEPTION_HANDLER_RESPONSE, serverWebExchange.getResponse()); - hint.set(WEBFLUX_EXCEPTION_HANDLER_EXCHANGE, serverWebExchange); + final Hint hint = new Hint(); + hint.set(WEBFLUX_EXCEPTION_HANDLER_REQUEST, serverWebExchange.getRequest()); + hint.set(WEBFLUX_EXCEPTION_HANDLER_RESPONSE, serverWebExchange.getResponse()); + hint.set(WEBFLUX_EXCEPTION_HANDLER_EXCHANGE, serverWebExchange); - scopes.captureEvent(event, hint); - } + scopes.captureEvent(event, hint); + } - return it; - }), + return it; + }), scopesToUse) .flatMap(it -> Mono.error(ex)); } diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebFilter.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebFilter.java index 0ec4b44a0e5..b97cd11e0e6 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebFilter.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebFilter.java @@ -36,10 +36,9 @@ public Mono filter( .filter(serverWebExchange) .doFinally(__ -> doFinally(serverWebExchange, requestScopes, transaction)) .doOnError(e -> doOnError(transaction, e)) - .doFirst( - () -> { - Sentry.setCurrentScopes(requestScopes); - doFirst(serverWebExchange, requestScopes); - }); + .doFirst(() -> { + Sentry.setCurrentScopes(requestScopes); + doFirst(serverWebExchange, requestScopes); + }); } } diff --git a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebFilterWithThreadLocalAccessor.java b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebFilterWithThreadLocalAccessor.java index 7748d43a012..c4ac2bdf652 100644 --- a/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebFilterWithThreadLocalAccessor.java +++ b/sentry-spring-jakarta/src/main/java/io/sentry/spring/jakarta/webflux/SentryWebFilterWithThreadLocalAccessor.java @@ -30,21 +30,17 @@ public Mono filter( return SentryReactorUtils.withSentryForkedRoots( webFilterChain .filter(serverWebExchange) - .doFinally( - __ -> - doFinally( - serverWebExchange, - Sentry.getCurrentScopes(), - transactionContainer.transaction)) + .doFinally(__ -> + doFinally( + serverWebExchange, Sentry.getCurrentScopes(), transactionContainer.transaction)) .doOnError(e -> doOnError(transactionContainer.transaction, e)) - .doFirst( - () -> { - doFirst(serverWebExchange, Sentry.getCurrentScopes()); - final ITransaction transaction = - maybeStartTransaction( - Sentry.getCurrentScopes(), serverWebExchange.getRequest(), TRACE_ORIGIN); - transactionContainer.transaction = transaction; - })); + .doFirst(() -> { + doFirst(serverWebExchange, Sentry.getCurrentScopes()); + final ITransaction transaction = + maybeStartTransaction( + Sentry.getCurrentScopes(), serverWebExchange.getRequest(), TRACE_ORIGIN); + transactionContainer.transaction = transaction; + })); } private static class TransactionContainer { diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/EnableSentryTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/EnableSentryTest.kt index 52a626d4642..879f30d558b 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/EnableSentryTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/EnableSentryTest.kt @@ -84,7 +84,7 @@ class EnableSentryTest { fun `creates SentryExceptionResolver with order set in the @EnableSentry annotation`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithExceptionResolverOrderIntegerMaxValue::class.java) + UserConfigurations.of(AppConfigWithExceptionResolverOrderIntegerMaxValue::class.java), ) .run { assertThat(it).hasSingleBean(SentryExceptionResolver::class.java) @@ -98,7 +98,7 @@ class EnableSentryTest { fun `configures custom TracesSamplerCallback`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithCustomTracesSamplerCallback::class.java) + UserConfigurations.of(AppConfigWithCustomTracesSamplerCallback::class.java), ) .run { val options = it.getBean(SentryOptions::class.java) @@ -143,7 +143,7 @@ class EnableSentryTest { fun `configures custom before breadcrumb callback`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithCustomBeforeBreadcrumbCallback::class.java) + UserConfigurations.of(AppConfigWithCustomBeforeBreadcrumbCallback::class.java), ) .run { val beforeBreadcrumbCallback = diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryCheckInAdviceTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryCheckInAdviceTest.kt index 84f6e2a8118..aa92ce52128 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryCheckInAdviceTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryCheckInAdviceTest.kt @@ -53,7 +53,7 @@ import org.springframework.util.StringValueResolver "my.cron.schedule = 0 30 2 * * *", "my.cron.zone = America/New_York", "my.cron.empty.zone = ", - ] + ], ) class SentryCheckInAdviceTest { diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentrySpringFilterTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentrySpringFilterTest.kt index 1c30ca58445..2adf22799f0 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentrySpringFilterTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentrySpringFilterTest.kt @@ -133,7 +133,7 @@ class SentrySpringFilterTest { MockMvcRequestBuilders.get(URI.create("http://example.com?param1=xyz")) .header("some-header", "some-header value") .accept(MediaType.APPLICATION_JSON) - .buildRequest(MockServletContext()) + .buildRequest(MockServletContext()), ) listener.doFilter(fixture.request, fixture.response, fixture.chain) @@ -157,7 +157,7 @@ class SentrySpringFilterTest { MockMvcRequestBuilders.get(URI.create("http://example.com?param1=xyz")) .header("another-header", "another value") .header("another-header", "another value2") - .buildRequest(MockServletContext()) + .buildRequest(MockServletContext()), ) listener.doFilter(fixture.request, fixture.response, fixture.chain) diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryTaskDecoratorTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryTaskDecoratorTest.kt index 1f0f74d25cf..949df61d412 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryTaskDecoratorTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryTaskDecoratorTest.kt @@ -43,7 +43,7 @@ class SentryTaskDecoratorTest { sut.decorate { assertNotEquals(mainScopes, Sentry.getCurrentScopes()) assertNotEquals(threadedScopes, Sentry.getCurrentScopes()) - } + }, ) callableFuture.get() diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryUserFilterTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryUserFilterTest.kt index 1cb91b1445f..d54772071a7 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryUserFilterTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/SentryUserFilterTest.kt @@ -63,7 +63,7 @@ class SentryUserFilterTest { fun `when processor returns empty User, user data is not changed`() { val filter = fixture.getSut( - userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { User() }) + userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { User() }), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -75,7 +75,7 @@ class SentryUserFilterTest { fun `when processor returns null, user data is not changed`() { val filter = fixture.getSut( - userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { null }) + userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { null }), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -91,7 +91,7 @@ class SentryUserFilterTest { listOf( SentryUserProvider { User().apply { data = mapOf("key" to "value") } }, SentryUserProvider { User().apply { data = mapOf("new-key" to "new-value") } }, - ) + ), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -166,7 +166,7 @@ class SentryUserFilterTest { SentryUserProvider { sampleUser }, SentryUserProvider { throw failure }, laterProvider, - ) + ), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -184,7 +184,7 @@ class SentryUserFilterTest { assertThat( assertFailsWith { filter.doFilter(fixture.request, fixture.response, fixture.chain) - } + }, ) .isSameAs(failure) verify(fixture.chain, never()).doFilter(fixture.request, fixture.response) diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/TransactionNameProviderUtilsTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/TransactionNameProviderUtilsTest.kt index c1a91c15503..e6fda8e0c50 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/TransactionNameProviderUtilsTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/TransactionNameProviderUtilsTest.kt @@ -31,7 +31,7 @@ class TransactionNameProviderUtilsTest { assertThat( assertFailsWith { TransactionNameProviderUtils.provideTransactionName(provider, request, logger) - } + }, ) .isSameAs(failure) } diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/checkin/SentryScheduledCheckInTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/checkin/SentryScheduledCheckInTest.kt index 00a2864b3f3..8312264b730 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/checkin/SentryScheduledCheckInTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/checkin/SentryScheduledCheckInTest.kt @@ -177,11 +177,11 @@ class SentryScheduledCheckInTest { assertEquals("outer-inner-run2-fa", SentryCheckInAdvice.scheduledTaskSlug("Outer.Inner.run2FA")) val first = SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.firstMethod" + "AVeryLongScheduledJobClassNameForReporting.firstMethod", ) val second = SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.secondMethod" + "AVeryLongScheduledJobClassNameForReporting.secondMethod", ) assertTrue(first.length <= 50) assertTrue(first.startsWith("a-very-long-scheduled-job-class-name-for-")) @@ -189,7 +189,7 @@ class SentryScheduledCheckInTest { assertEquals( first, SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.firstMethod" + "AVeryLongScheduledJobClassNameForReporting.firstMethod", ), ) } @@ -292,11 +292,11 @@ class SentryScheduledCheckInTest { @Bean open fun sentryScheduledCheckInAdvisor( - @Qualifier("sentryScheduledCheckInAdvice") advice: SentryCheckInAdvice + @Qualifier("sentryScheduledCheckInAdvice") advice: SentryCheckInAdvice, ): Advisor = DefaultPointcutAdvisor( SentryScheduledCheckInPointcut( - listOf("SentryScheduledCheckInTest.Jobs.excluded", ".*\\.ExcludedJobs\\..*", " ") + listOf("SentryScheduledCheckInTest.Jobs.excluded", ".*\\.ExcludedJobs\\..*", " "), ), advice, ) diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/graphql/SentrySpringSubscriptionHandlerTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/graphql/SentrySpringSubscriptionHandlerTest.kt index a8039ff7660..f0eb86f3e46 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/graphql/SentrySpringSubscriptionHandlerTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/graphql/SentrySpringSubscriptionHandlerTest.kt @@ -33,7 +33,7 @@ class SentrySpringSubscriptionHandlerTest { OperationDefinition.newOperationDefinition() .operation(OperationDefinition.Operation.QUERY) .name("testQuery") - .build() + .build(), ) .build() whenever(dataFetchingEnvironment.document).thenReturn(document) @@ -69,7 +69,7 @@ class SentrySpringSubscriptionHandlerTest { OperationDefinition.newOperationDefinition() .operation(OperationDefinition.Operation.QUERY) .name("testQuery") - .build() + .build(), ) .build() whenever(dataFetchingEnvironment.document).thenReturn(document) diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/kafka/SentryKafkaProducerBeanPostProcessorTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/kafka/SentryKafkaProducerBeanPostProcessorTest.kt index b3a1a268682..903f949f74b 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/kafka/SentryKafkaProducerBeanPostProcessorTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/kafka/SentryKafkaProducerBeanPostProcessorTest.kt @@ -42,7 +42,7 @@ class SentryKafkaProducerBeanPostProcessorTest { val captor = argumentCaptor>() verify(factory).addPostProcessor(captor.capture()) assertTrue( - captor.firstValue is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *> + captor.firstValue is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *>, ) } @@ -103,7 +103,7 @@ class SentryKafkaProducerBeanPostProcessorTest { assertEquals(1, factory.postProcessors.size) assertTrue( factory.postProcessors.first() - is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *> + is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *>, ) } } diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentrySpanClientHttpRequestInterceptorTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentrySpanClientHttpRequestInterceptorTest.kt index 504b6d7bd12..fd7a2f8882e 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentrySpanClientHttpRequestInterceptorTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentrySpanClientHttpRequestInterceptorTest.kt @@ -54,7 +54,7 @@ class SentrySpanClientHttpRequestInterceptorTest { } fun create( - config: Sentry.OptionsConfiguration + config: Sentry.OptionsConfiguration, ): SentrySpanClientHttpRequestInterceptor { config.configure(options) return SentrySpanClientHttpRequestInterceptor(scopes) diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentryTracingFilterTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentryTracingFilterTest.kt index 61fabb6d478..a13911b3f88 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentryTracingFilterTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentryTracingFilterTest.kt @@ -87,7 +87,10 @@ class SentryTracingFilterTest { } response.status = status whenever( - scopes.startTransaction(any(), check { assertTrue(it.isBindToScope) }) + scopes.startTransaction( + any(), + check { assertTrue(it.isBindToScope) }, + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.isEnabled).thenReturn(isEnabled) @@ -98,7 +101,7 @@ class SentryTracingFilterTest { it.arguments[0] as String?, it.arguments[1] as List?, null, - ) + ), ) } return SentryTracingFilter(scopes, transactionNameProvider, isAsyncSupportEnabled) @@ -313,7 +316,7 @@ class SentryTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null val filter = @@ -343,7 +346,7 @@ class SentryTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null fixture.options.setIgnoredSpanOrigins(listOf("auto.http.spring_jakarta.webmvc")) @@ -373,7 +376,7 @@ class SentryTracingFilterTest { val sentryTrace = "f9118105af4a2d42b4124532cd1065ff-424cffc8f94feeee-1" val baggage = listOf( - "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" + "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", ) val filter = fixture.getSut( @@ -442,7 +445,7 @@ class SentryTracingFilterTest { val sentryTrace = "f9118105af4a2d42b4124532cd1065ff-424cffc8f94feeee-1" val baggage = listOf( - "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" + "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", ) val filter = fixture.getSut( diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentryTransactionAdviceTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentryTransactionAdviceTest.kt index ed9c1f9abb4..87bbb64fc47 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentryTransactionAdviceTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/tracing/SentryTransactionAdviceTest.kt @@ -55,7 +55,7 @@ class SentryTransactionAdviceTest { assertTrue(it.isBindToScope) assertThat(it.origin).isEqualTo("auto.function.spring_jakarta.advice") }, - ) + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.options) diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryScheduleHookTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryScheduleHookTest.kt index 07249866a7e..53251df10bb 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryScheduleHookTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryScheduleHookTest.kt @@ -45,7 +45,7 @@ class SentryScheduleHookTest { sut.apply { assertNotEquals(mainScopes, Sentry.getCurrentScopes()) assertNotEquals(threadedScopes, Sentry.getCurrentScopes()) - } + }, ) callableFuture.get() diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryWebFluxTracingFilterTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryWebFluxTracingFilterTest.kt index 0a01b4cbcc4..035a5266ef4 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryWebFluxTracingFilterTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryWebFluxTracingFilterTest.kt @@ -87,7 +87,10 @@ class SentryWebFluxTracingFilterTest { ) exchange.response.statusCode = status whenever( - scopes.startTransaction(any(), check { assertTrue(it.isBindToScope) }) + scopes.startTransaction( + any(), + check { assertTrue(it.isBindToScope) }, + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.isEnabled).thenReturn(isEnabled) @@ -99,7 +102,7 @@ class SentryWebFluxTracingFilterTest { it.arguments[0] as String?, it.arguments[1] as List?, null, - ) + ), ) } return SentryWebFilter(scopes) @@ -326,7 +329,7 @@ class SentryWebFluxTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null val filter = @@ -358,7 +361,7 @@ class SentryWebFluxTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null fixture.options.setIgnoredSpanOrigins(listOf("auto.spring_jakarta.webflux")) diff --git a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryWebfluxIntegrationTest.kt b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryWebfluxIntegrationTest.kt index e3b3ed55a7c..f3ef34984fc 100644 --- a/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryWebfluxIntegrationTest.kt +++ b/sentry-spring-jakarta/src/test/kotlin/io/sentry/spring/jakarta/webflux/SentryWebfluxIntegrationTest.kt @@ -136,7 +136,7 @@ class SentryWebfluxIntegrationTest { } @SpringBootApplication( - exclude = [ReactiveSecurityAutoConfiguration::class, SecurityAutoConfiguration::class] + exclude = [ReactiveSecurityAutoConfiguration::class, SecurityAutoConfiguration::class], ) open class App { private val transport = mock().also { whenever(it.isHealthy).thenReturn(true) } diff --git a/sentry-spring/src/integrationTest/kotlin/io/sentry/spring/integrationtest/MetricsIntegrationTest.kt b/sentry-spring/src/integrationTest/kotlin/io/sentry/spring/integrationtest/MetricsIntegrationTest.kt index d2e524a3bb3..65b829d3543 100644 --- a/sentry-spring/src/integrationTest/kotlin/io/sentry/spring/integrationtest/MetricsIntegrationTest.kt +++ b/sentry-spring/src/integrationTest/kotlin/io/sentry/spring/integrationtest/MetricsIntegrationTest.kt @@ -35,7 +35,7 @@ class MetricsIntegrationTest : IntegrationTest() { .isEqualTo("distribution metric tracked") assertThat( - awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0) + awaitMetric("distributionMetric").hasMetric("distributionMetric", "distribution", 23.0), ) .isTrue() } diff --git a/sentry-spring/src/main/java/io/sentry/spring/SentrySpringFilter.java b/sentry-spring/src/main/java/io/sentry/spring/SentrySpringFilter.java index 5108238f4ad..4718ee982b1 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/SentrySpringFilter.java +++ b/sentry-spring/src/main/java/io/sentry/spring/SentrySpringFilter.java @@ -84,23 +84,22 @@ protected void doFilterInternal( private void configureScope( final @NotNull IScopes scopes, final @NotNull HttpServletRequest request) { try { - scopes.configureScope( - scope -> { - // set basic request information on the scope - scope.setRequest(requestResolver.resolveSentryRequest(request)); - // transaction name is known at the later stage of request processing, thus it cannot - // be set on the scope - scope.addEventProcessor( - new SentryRequestHttpServletRequestProcessor( - transactionNameProvider, request, scopes.getOptions().getLogger())); - // only if request caches body, add an event processor that sets body on the event - // body is not on the scope, to avoid using memory when no event is triggered during - // request processing - if (request instanceof ContentCachingRequestWrapper) { - scope.addEventProcessor( - new RequestBodyExtractingEventProcessor(request, scopes.getOptions())); - } - }); + scopes.configureScope(scope -> { + // set basic request information on the scope + scope.setRequest(requestResolver.resolveSentryRequest(request)); + // transaction name is known at the later stage of request processing, thus it cannot + // be set on the scope + scope.addEventProcessor( + new SentryRequestHttpServletRequestProcessor( + transactionNameProvider, request, scopes.getOptions().getLogger())); + // only if request caches body, add an event processor that sets body on the event + // body is not on the scope, to avoid using memory when no event is triggered during + // request processing + if (request instanceof ContentCachingRequestWrapper) { + scope.addEventProcessor( + new RequestBodyExtractingEventProcessor(request, scopes.getOptions())); + } + }); } catch (Throwable e) { scopes .getOptions() diff --git a/sentry-spring/src/main/java/io/sentry/spring/graphql/SentryBatchLoaderRegistry.java b/sentry-spring/src/main/java/io/sentry/spring/graphql/SentryBatchLoaderRegistry.java index 5fe8eb265a7..e28ea6f4752 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/graphql/SentryBatchLoaderRegistry.java +++ b/sentry-spring/src/main/java/io/sentry/spring/graphql/SentryBatchLoaderRegistry.java @@ -87,23 +87,21 @@ public BatchLoaderRegistry.RegistrationSpec withOptions(DataLoaderOptions @Override public void registerBatchLoader(BiFunction, BatchLoaderEnvironment, Flux> loader) { - delegate.registerBatchLoader( - (keys, batchLoaderEnvironment) -> { - scopesFromContext(batchLoaderEnvironment) - .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); - return loader.apply(keys, batchLoaderEnvironment); - }); + delegate.registerBatchLoader((keys, batchLoaderEnvironment) -> { + scopesFromContext(batchLoaderEnvironment) + .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); + return loader.apply(keys, batchLoaderEnvironment); + }); } @Override public void registerMappedBatchLoader( BiFunction, BatchLoaderEnvironment, Mono>> loader) { - delegate.registerMappedBatchLoader( - (keys, batchLoaderEnvironment) -> { - scopesFromContext(batchLoaderEnvironment) - .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); - return loader.apply(keys, batchLoaderEnvironment); - }); + delegate.registerMappedBatchLoader((keys, batchLoaderEnvironment) -> { + scopesFromContext(batchLoaderEnvironment) + .addBreadcrumb(Breadcrumb.graphqlDataLoader(keys, keyType, valueType, name)); + return loader.apply(keys, batchLoaderEnvironment); + }); } private @NotNull IScopes scopesFromContext(final @NotNull BatchLoaderEnvironment environment) { diff --git a/sentry-spring/src/main/java/io/sentry/spring/graphql/SentryDgsSubscriptionHandler.java b/sentry-spring/src/main/java/io/sentry/spring/graphql/SentryDgsSubscriptionHandler.java index 5a003ade2d7..62156749bfa 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/graphql/SentryDgsSubscriptionHandler.java +++ b/sentry-spring/src/main/java/io/sentry/spring/graphql/SentryDgsSubscriptionHandler.java @@ -22,12 +22,11 @@ public SentryDgsSubscriptionHandler() { final @NotNull InstrumentationFieldFetchParameters parameters) { if (result instanceof Flux) { final @NotNull Flux flux = (Flux) result; - return flux.doOnError( - throwable -> { - final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = - new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); - exceptionReporter.captureThrowable(throwable, exceptionDetails, null); - }); + return flux.doOnError(throwable -> { + final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = + new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); + exceptionReporter.captureThrowable(throwable, exceptionDetails, null); + }); } return result; } diff --git a/sentry-spring/src/main/java/io/sentry/spring/graphql/SentrySpringSubscriptionHandler.java b/sentry-spring/src/main/java/io/sentry/spring/graphql/SentrySpringSubscriptionHandler.java index b3f0b9830ee..b10502f7154 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/graphql/SentrySpringSubscriptionHandler.java +++ b/sentry-spring/src/main/java/io/sentry/spring/graphql/SentrySpringSubscriptionHandler.java @@ -18,17 +18,15 @@ public final class SentrySpringSubscriptionHandler implements SentrySubscription final @NotNull InstrumentationFieldFetchParameters parameters) { if (result instanceof Flux) { final @NotNull Flux flux = (Flux) result; - return flux.doOnError( - throwable -> { - final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = - new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); - if (throwable instanceof SubscriptionPublisherException - && throwable.getCause() != null) { - exceptionReporter.captureThrowable(throwable.getCause(), exceptionDetails, null); - } else { - exceptionReporter.captureThrowable(throwable, exceptionDetails, null); - } - }); + return flux.doOnError(throwable -> { + final @NotNull ExceptionReporter.ExceptionDetails exceptionDetails = + new ExceptionReporter.ExceptionDetails(scopes, parameters.getEnvironment(), true); + if (throwable instanceof SubscriptionPublisherException && throwable.getCause() != null) { + exceptionReporter.captureThrowable(throwable.getCause(), exceptionDetails, null); + } else { + exceptionReporter.captureThrowable(throwable, exceptionDetails, null); + } + }); } return result; } diff --git a/sentry-spring/src/main/java/io/sentry/spring/tracing/SentrySpanClientWebRequestFilter.java b/sentry-spring/src/main/java/io/sentry/spring/tracing/SentrySpanClientWebRequestFilter.java index 5eeb0604463..0350663a36f 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/tracing/SentrySpanClientWebRequestFilter.java +++ b/sentry-spring/src/main/java/io/sentry/spring/tracing/SentrySpanClientWebRequestFilter.java @@ -55,22 +55,20 @@ public SentrySpanClientWebRequestFilter(final @NotNull IScopes scopes) { final ClientRequest clientRequestWithSentryTraceHeader = maybeAddHeaders(request, span); return next.exchange(clientRequestWithSentryTraceHeader) - .flatMap( - response -> { - span.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, response.statusCode().value()); - span.setStatus(SpanStatus.fromHttpStatusCode(response.statusCode().value())); - addBreadcrumb(request, response); - span.finish(); - return Mono.just(response); - }) - .onErrorMap( - throwable -> { - span.setThrowable(throwable); - span.setStatus(SpanStatus.INTERNAL_ERROR); - addBreadcrumb(request, null); - span.finish(); - return throwable; - }); + .flatMap(response -> { + span.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, response.statusCode().value()); + span.setStatus(SpanStatus.fromHttpStatusCode(response.statusCode().value())); + addBreadcrumb(request, response); + span.finish(); + return Mono.just(response); + }) + .onErrorMap(throwable -> { + span.setThrowable(throwable); + span.setStatus(SpanStatus.INTERNAL_ERROR); + addBreadcrumb(request, null); + span.finish(); + return throwable; + }); } private ClientRequest maybeAddHeaders( @@ -95,11 +93,10 @@ private ClientRequest maybeAddHeaders( final @Nullable BaggageHeader baggageHeader = tracingHeaders.getBaggageHeader(); if (baggageHeader != null) { - requestBuilder.headers( - httpHeaders -> { - httpHeaders.remove(BaggageHeader.BAGGAGE_HEADER); - httpHeaders.add(baggageHeader.getName(), baggageHeader.getValue()); - }); + requestBuilder.headers(httpHeaders -> { + httpHeaders.remove(BaggageHeader.BAGGAGE_HEADER); + httpHeaders.add(baggageHeader.getName(), baggageHeader.getValue()); + }); } } diff --git a/sentry-spring/src/main/java/io/sentry/spring/webflux/SentryWebFilter.java b/sentry-spring/src/main/java/io/sentry/spring/webflux/SentryWebFilter.java index 031f579d4e4..65153e475ec 100644 --- a/sentry-spring/src/main/java/io/sentry/spring/webflux/SentryWebFilter.java +++ b/sentry-spring/src/main/java/io/sentry/spring/webflux/SentryWebFilter.java @@ -72,41 +72,38 @@ isTracingEnabled && shouldTraceRequest(requestScopes, request) return webFilterChain .filter(serverWebExchange) - .doFinally( - __ -> { - if (transaction != null) { - finishTransaction(serverWebExchange, transaction); - } - Sentry.setCurrentScopes(NoOpScopes.getInstance()); - }) - .doOnError( - e -> { - if (transaction != null) { - transaction.setStatus(SpanStatus.INTERNAL_ERROR); - transaction.setThrowable(e); - } - }) - .doFirst( - () -> { - serverWebExchange.getAttributes().put(SENTRY_SCOPES_KEY, requestScopes); - Sentry.setCurrentScopes(requestScopes); - final ServerHttpResponse response = serverWebExchange.getResponse(); - - final Hint hint = new Hint(); - hint.set(WEBFLUX_FILTER_REQUEST, request); - hint.set(WEBFLUX_FILTER_RESPONSE, response); - final String methodName = - request.getMethod() != null ? request.getMethod().name() : "unknown"; - final @NotNull Breadcrumb breadcrumb = - Breadcrumb.http( - request.getURI().toString(), - methodName, - null, - requestScopes.getOptions().getDataCollectionResolver()); - requestScopes.addBreadcrumb(breadcrumb, hint); - requestScopes.configureScope( - scope -> scope.setRequest(sentryRequestResolver.resolveSentryRequest(request))); - }); + .doFinally(__ -> { + if (transaction != null) { + finishTransaction(serverWebExchange, transaction); + } + Sentry.setCurrentScopes(NoOpScopes.getInstance()); + }) + .doOnError(e -> { + if (transaction != null) { + transaction.setStatus(SpanStatus.INTERNAL_ERROR); + transaction.setThrowable(e); + } + }) + .doFirst(() -> { + serverWebExchange.getAttributes().put(SENTRY_SCOPES_KEY, requestScopes); + Sentry.setCurrentScopes(requestScopes); + final ServerHttpResponse response = serverWebExchange.getResponse(); + + final Hint hint = new Hint(); + hint.set(WEBFLUX_FILTER_REQUEST, request); + hint.set(WEBFLUX_FILTER_RESPONSE, response); + final String methodName = + request.getMethod() != null ? request.getMethod().name() : "unknown"; + final @NotNull Breadcrumb breadcrumb = + Breadcrumb.http( + request.getURI().toString(), + methodName, + null, + requestScopes.getOptions().getDataCollectionResolver()); + requestScopes.addBreadcrumb(breadcrumb, hint); + requestScopes.configureScope( + scope -> scope.setRequest(sentryRequestResolver.resolveSentryRequest(request))); + }); } private boolean isIgnored(final @NotNull IScopes scopes) { @@ -157,10 +154,9 @@ private void finishTransaction(ServerWebExchange exchange, ITransaction transact if (rawStatusCode != null) { transaction .getContexts() - .withResponse( - (sentryResponse) -> { - sentryResponse.setStatusCode(rawStatusCode); - }); + .withResponse(sentryResponse -> { + sentryResponse.setStatusCode(rawStatusCode); + }); if (transaction.getStatus() == null) { transaction.setStatus(SpanStatus.fromHttpStatusCode(rawStatusCode)); } diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/EnableSentryTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/EnableSentryTest.kt index f2277128ec8..a54799d89d6 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/EnableSentryTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/EnableSentryTest.kt @@ -84,7 +84,7 @@ class EnableSentryTest { fun `creates SentryExceptionResolver with order set in the @EnableSentry annotation`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithExceptionResolverOrderIntegerMaxValue::class.java) + UserConfigurations.of(AppConfigWithExceptionResolverOrderIntegerMaxValue::class.java), ) .run { assertThat(it).hasSingleBean(SentryExceptionResolver::class.java) @@ -98,7 +98,7 @@ class EnableSentryTest { fun `configures custom TracesSamplerCallback`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithCustomTracesSamplerCallback::class.java) + UserConfigurations.of(AppConfigWithCustomTracesSamplerCallback::class.java), ) .run { val options = it.getBean(SentryOptions::class.java) @@ -143,7 +143,7 @@ class EnableSentryTest { fun `configures custom before breadcrumb callback`() { ApplicationContextRunner() .withConfiguration( - UserConfigurations.of(AppConfigWithCustomBeforeBreadcrumbCallback::class.java) + UserConfigurations.of(AppConfigWithCustomBeforeBreadcrumbCallback::class.java), ) .run { val beforeBreadcrumbCallback = diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/SentryCheckInAdviceTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/SentryCheckInAdviceTest.kt index 0bac0df528c..7b687e90377 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/SentryCheckInAdviceTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/SentryCheckInAdviceTest.kt @@ -54,7 +54,7 @@ import org.springframework.util.StringValueResolver "my.cron.schedule = 0 30 2 * * *", "my.cron.zone = America/New_York", "my.cron.empty.zone = ", - ] + ], ) class SentryCheckInAdviceTest { diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/SentrySpringFilterTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/SentrySpringFilterTest.kt index 8a265eea8a7..c38da356b7f 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/SentrySpringFilterTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/SentrySpringFilterTest.kt @@ -133,7 +133,7 @@ class SentrySpringFilterTest { MockMvcRequestBuilders.get(URI.create("http://example.com?param1=xyz")) .header("some-header", "some-header value") .accept(MediaType.APPLICATION_JSON) - .buildRequest(MockServletContext()) + .buildRequest(MockServletContext()), ) listener.doFilter(fixture.request, fixture.response, fixture.chain) @@ -157,7 +157,7 @@ class SentrySpringFilterTest { MockMvcRequestBuilders.get(URI.create("http://example.com?param1=xyz")) .header("another-header", "another value") .header("another-header", "another value2") - .buildRequest(MockServletContext()) + .buildRequest(MockServletContext()), ) listener.doFilter(fixture.request, fixture.response, fixture.chain) diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/SentryTaskDecoratorTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/SentryTaskDecoratorTest.kt index 5fc955d0031..ee6bd57bd69 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/SentryTaskDecoratorTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/SentryTaskDecoratorTest.kt @@ -43,7 +43,7 @@ class SentryTaskDecoratorTest { sut.decorate { assertNotEquals(mainScopes, Sentry.getCurrentScopes()) assertNotEquals(threadedScopes, Sentry.getCurrentScopes()) - } + }, ) callableFuture.get() diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/SentryUserFilterTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/SentryUserFilterTest.kt index 8c0ed0f2f92..21730ea451f 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/SentryUserFilterTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/SentryUserFilterTest.kt @@ -63,7 +63,7 @@ class SentryUserFilterTest { fun `when processor returns empty User, user data is not changed`() { val filter = fixture.getSut( - userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { User() }) + userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { User() }), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -75,7 +75,7 @@ class SentryUserFilterTest { fun `when processor returns null, user data is not changed`() { val filter = fixture.getSut( - userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { null }) + userProviders = listOf(SentryUserProvider { sampleUser }, SentryUserProvider { null }), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -91,7 +91,7 @@ class SentryUserFilterTest { listOf( SentryUserProvider { User().apply { data = mapOf("key" to "value") } }, SentryUserProvider { User().apply { data = mapOf("new-key" to "new-value") } }, - ) + ), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -166,7 +166,7 @@ class SentryUserFilterTest { SentryUserProvider { sampleUser }, SentryUserProvider { throw failure }, laterProvider, - ) + ), ) filter.doFilter(fixture.request, fixture.response, fixture.chain) @@ -184,7 +184,7 @@ class SentryUserFilterTest { assertThat( assertFailsWith { filter.doFilter(fixture.request, fixture.response, fixture.chain) - } + }, ) .isSameAs(failure) verify(fixture.chain, never()).doFilter(fixture.request, fixture.response) diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/TransactionNameProviderUtilsTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/TransactionNameProviderUtilsTest.kt index 550a1438e82..da440fee291 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/TransactionNameProviderUtilsTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/TransactionNameProviderUtilsTest.kt @@ -31,7 +31,7 @@ class TransactionNameProviderUtilsTest { assertThat( assertFailsWith { TransactionNameProviderUtils.provideTransactionName(provider, request, logger) - } + }, ) .isSameAs(failure) } diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/checkin/SentryScheduledCheckInTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/checkin/SentryScheduledCheckInTest.kt index 1af18fe95f0..08d45e47943 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/checkin/SentryScheduledCheckInTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/checkin/SentryScheduledCheckInTest.kt @@ -177,11 +177,11 @@ class SentryScheduledCheckInTest { assertEquals("outer-inner-run2-fa", SentryCheckInAdvice.scheduledTaskSlug("Outer.Inner.run2FA")) val first = SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.firstMethod" + "AVeryLongScheduledJobClassNameForReporting.firstMethod", ) val second = SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.secondMethod" + "AVeryLongScheduledJobClassNameForReporting.secondMethod", ) assertTrue(first.length <= 50) assertTrue(first.startsWith("a-very-long-scheduled-job-class-name-for-")) @@ -189,7 +189,7 @@ class SentryScheduledCheckInTest { assertEquals( first, SentryCheckInAdvice.scheduledTaskSlug( - "AVeryLongScheduledJobClassNameForReporting.firstMethod" + "AVeryLongScheduledJobClassNameForReporting.firstMethod", ), ) } @@ -292,11 +292,11 @@ class SentryScheduledCheckInTest { @Bean open fun sentryScheduledCheckInAdvisor( - @Qualifier("sentryScheduledCheckInAdvice") advice: SentryCheckInAdvice + @Qualifier("sentryScheduledCheckInAdvice") advice: SentryCheckInAdvice, ): Advisor = DefaultPointcutAdvisor( SentryScheduledCheckInPointcut( - listOf("SentryScheduledCheckInTest.Jobs.excluded", ".*\\.ExcludedJobs\\..*", " ") + listOf("SentryScheduledCheckInTest.Jobs.excluded", ".*\\.ExcludedJobs\\..*", " "), ), advice, ) diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/graphql/SentrySpringSubscriptionHandlerTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/graphql/SentrySpringSubscriptionHandlerTest.kt index 03b11629fb4..bc4e8033e0c 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/graphql/SentrySpringSubscriptionHandlerTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/graphql/SentrySpringSubscriptionHandlerTest.kt @@ -32,7 +32,7 @@ class SentrySpringSubscriptionHandlerTest { OperationDefinition.newOperationDefinition() .operation(OperationDefinition.Operation.QUERY) .name("testQuery") - .build() + .build(), ) .build() whenever(dataFetchingEnvironment.document).thenReturn(document) @@ -68,7 +68,7 @@ class SentrySpringSubscriptionHandlerTest { OperationDefinition.newOperationDefinition() .operation(OperationDefinition.Operation.QUERY) .name("testQuery") - .build() + .build(), ) .build() whenever(dataFetchingEnvironment.document).thenReturn(document) diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/kafka/SentryKafkaProducerBeanPostProcessorTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/kafka/SentryKafkaProducerBeanPostProcessorTest.kt index 11a943307c8..75a68b3a1b1 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/kafka/SentryKafkaProducerBeanPostProcessorTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/kafka/SentryKafkaProducerBeanPostProcessorTest.kt @@ -28,7 +28,7 @@ class SentryKafkaProducerBeanPostProcessorTest { val captor = argumentCaptor>() verify(factory).addPostProcessor(captor.capture()) assertTrue( - captor.firstValue is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *> + captor.firstValue is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *>, ) } @@ -89,7 +89,7 @@ class SentryKafkaProducerBeanPostProcessorTest { assertEquals(1, factory.postProcessors.size) assertTrue( factory.postProcessors.first() - is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *> + is SentryKafkaProducerBeanPostProcessor.SentryProducerPostProcessor<*, *>, ) } } diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentrySpanClientHttpRequestInterceptorTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentrySpanClientHttpRequestInterceptorTest.kt index 6531cd7fd04..efe9a1ca12f 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentrySpanClientHttpRequestInterceptorTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentrySpanClientHttpRequestInterceptorTest.kt @@ -54,7 +54,7 @@ class SentrySpanClientHttpRequestInterceptorTest { } fun create( - config: Sentry.OptionsConfiguration + config: Sentry.OptionsConfiguration, ): SentrySpanClientHttpRequestInterceptor { config.configure(options) return SentrySpanClientHttpRequestInterceptor(scopes) diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentryTracingFilterTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentryTracingFilterTest.kt index acfcdb4ebab..9039fa01e33 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentryTracingFilterTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentryTracingFilterTest.kt @@ -87,7 +87,10 @@ class SentryTracingFilterTest { } response.status = status whenever( - scopes.startTransaction(any(), check { assertTrue(it.isBindToScope) }) + scopes.startTransaction( + any(), + check { assertTrue(it.isBindToScope) }, + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.isEnabled).thenReturn(isEnabled) @@ -98,7 +101,7 @@ class SentryTracingFilterTest { it.arguments[0] as String?, it.arguments[1] as List?, null, - ) + ), ) } return SentryTracingFilter(scopes, transactionNameProvider, isAsyncSupportEnabled) @@ -313,7 +316,7 @@ class SentryTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null val filter = @@ -343,7 +346,7 @@ class SentryTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null fixture.options.setIgnoredSpanOrigins(listOf("auto.http.spring.webmvc")) @@ -373,7 +376,7 @@ class SentryTracingFilterTest { val sentryTrace = "f9118105af4a2d42b4124532cd1065ff-424cffc8f94feeee-1" val baggage = listOf( - "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" + "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", ) val filter = fixture.getSut( @@ -442,7 +445,7 @@ class SentryTracingFilterTest { val sentryTrace = "f9118105af4a2d42b4124532cd1065ff-424cffc8f94feeee-1" val baggage = listOf( - "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d" + "baggage: sentry-environment=production,sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rand=0.456789,sentry-sample_rate=0.5,sentry-sampled=true,sentry-trace_id=df71f5972f754b4c85af13ff5c07017d", ) val filter = fixture.getSut( diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentryTransactionAdviceTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentryTransactionAdviceTest.kt index e398290a966..a7fb87afb0a 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentryTransactionAdviceTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/tracing/SentryTransactionAdviceTest.kt @@ -55,7 +55,7 @@ class SentryTransactionAdviceTest { assertTrue(it.isBindToScope) assertThat(it.origin).isEqualTo("auto.function.spring.advice") }, - ) + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.options) diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryScheduleHookTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryScheduleHookTest.kt index 2c45bf1daa8..511fcdbe826 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryScheduleHookTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryScheduleHookTest.kt @@ -45,7 +45,7 @@ class SentryScheduleHookTest { sut.apply { assertNotEquals(mainScopes, Sentry.getCurrentScopes()) assertNotEquals(threadedScopes, Sentry.getCurrentScopes()) - } + }, ) callableFuture.get() diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryWebFluxTracingFilterTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryWebFluxTracingFilterTest.kt index 326b5979991..c72506e7e90 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryWebFluxTracingFilterTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryWebFluxTracingFilterTest.kt @@ -87,7 +87,10 @@ class SentryWebFluxTracingFilterTest { ) exchange.response.statusCode = status whenever( - scopes.startTransaction(any(), check { assertTrue(it.isBindToScope) }) + scopes.startTransaction( + any(), + check { assertTrue(it.isBindToScope) }, + ), ) .thenAnswer { SentryTracer(it.arguments[0] as TransactionContext, scopes) } whenever(scopes.isEnabled).thenReturn(isEnabled) @@ -99,7 +102,7 @@ class SentryWebFluxTracingFilterTest { it.arguments[0] as String?, it.arguments[1] as List?, null, - ) + ), ) } return SentryWebFilter(scopes) @@ -327,7 +330,7 @@ class SentryWebFluxTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null val filter = @@ -359,7 +362,7 @@ class SentryWebFluxTracingFilterTest { val sentryTraceHeaderString = "2722d9f6ec019ade60c776169d9a8904-$parentSpanId-1" val baggageHeaderStrings = listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) fixture.options.tracesSampleRate = null fixture.options.setIgnoredSpanOrigins(listOf("auto.spring.webflux")) diff --git a/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryWebfluxIntegrationTest.kt b/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryWebfluxIntegrationTest.kt index f1ace818f6d..8c026dfabc7 100644 --- a/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryWebfluxIntegrationTest.kt +++ b/sentry-spring/src/test/kotlin/io/sentry/spring/webflux/SentryWebfluxIntegrationTest.kt @@ -139,7 +139,7 @@ class SentryWebfluxIntegrationTest { } @SpringBootApplication( - exclude = [ReactiveSecurityAutoConfiguration::class, SecurityAutoConfiguration::class] + exclude = [ReactiveSecurityAutoConfiguration::class, SecurityAutoConfiguration::class], ) open class App { private val transport = mock().also { whenever(it.isHealthy).thenReturn(true) } diff --git a/sentry-test-support/src/main/kotlin/io/sentry/Assertions.kt b/sentry-test-support/src/main/kotlin/io/sentry/Assertions.kt index 43b083d50e9..4520dc063b7 100644 --- a/sentry-test-support/src/main/kotlin/io/sentry/Assertions.kt +++ b/sentry-test-support/src/main/kotlin/io/sentry/Assertions.kt @@ -59,7 +59,7 @@ inline fun assertEnvelopeItem( SentryOptions().apply { isDebug = true setLogger(logger) - } + }, ) .deserialize(it.data.inputStream().reader(), T::class.java) deserialized?.let { Pair(index, it) } @@ -123,7 +123,7 @@ private inline fun check(noinline predicate: (T) -> Unit): T = If you are trying to verify an argument to be null, use `isNull()`. If you are using `check` as part of a stubbing, use `argThat` or `argForWhich` instead. """ - .trimIndent() + .trimIndent(), ) } diff --git a/sentry-test-support/src/main/kotlin/io/sentry/test/MockSentryServer.kt b/sentry-test-support/src/main/kotlin/io/sentry/test/MockSentryServer.kt index 0275036526a..d6667eb6d06 100644 --- a/sentry-test-support/src/main/kotlin/io/sentry/test/MockSentryServer.kt +++ b/sentry-test-support/src/main/kotlin/io/sentry/test/MockSentryServer.kt @@ -56,7 +56,7 @@ class MockSentryServer(private val beforeEachCheck: () -> Unit = {}) : Closeable } if (deadline.hasPassed()) { throw AssertionError( - "No matching envelope within ${timeoutMillis}ms, received ${received.size} envelopes" + "No matching envelope within ${timeoutMillis}ms, received ${received.size} envelopes", ) } Thread.sleep(POLL_INTERVAL_MILLIS) diff --git a/sentry/api/sentry.api b/sentry/api/sentry.api index 9f88d6323f9..b5a9276b85d 100644 --- a/sentry/api/sentry.api +++ b/sentry/api/sentry.api @@ -503,6 +503,9 @@ public final class io/sentry/DiagnosticLogger : io/sentry/ILogger { public fun (Lio/sentry/SentryOptions;Lio/sentry/ILogger;)V public fun getLogger ()Lio/sentry/ILogger; public fun isEnabled (Lio/sentry/SentryLevel;)Z + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;)V + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Object;)V + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Throwable;)V public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;[Ljava/lang/Object;)V public fun log (Lio/sentry/SentryLevel;Ljava/lang/Throwable;Ljava/lang/String;[Ljava/lang/Object;)V @@ -784,6 +787,9 @@ public abstract interface class io/sentry/IFeedbackApi { public abstract interface class io/sentry/ILogger { public abstract fun isEnabled (Lio/sentry/SentryLevel;)Z + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;)V + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Object;)V + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V public abstract fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Throwable;)V public abstract fun log (Lio/sentry/SentryLevel;Ljava/lang/String;[Ljava/lang/Object;)V public abstract fun log (Lio/sentry/SentryLevel;Ljava/lang/Throwable;Ljava/lang/String;[Ljava/lang/Object;)V @@ -822,7 +828,9 @@ public abstract interface class io/sentry/IReplayApi { public abstract fun enableDebugMaskingOverlay ()V public abstract fun flush ()V public abstract fun pause ()V + public abstract fun pauseTouchTracking ()V public abstract fun resume ()V + public abstract fun resumeTouchTracking ()V public abstract fun start ()V public abstract fun startBuffering ()V public abstract fun stop ()V @@ -1557,6 +1565,9 @@ public final class io/sentry/NoOpFeedbackApi : io/sentry/IFeedbackApi { public final class io/sentry/NoOpLogger : io/sentry/ILogger { public static fun getInstance ()Lio/sentry/NoOpLogger; public fun isEnabled (Lio/sentry/SentryLevel;)Z + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;)V + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Object;)V + public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;Ljava/lang/Throwable;)V public fun log (Lio/sentry/SentryLevel;Ljava/lang/String;[Ljava/lang/Object;)V public fun log (Lio/sentry/SentryLevel;Ljava/lang/Throwable;Ljava/lang/String;[Ljava/lang/Object;)V @@ -1586,9 +1597,11 @@ public final class io/sentry/NoOpReplayController : io/sentry/ReplayController { public fun onAppForegrounded (Z)V public fun onAppSessionEnded ()V public fun pause ()V + public fun pauseTouchTracking ()V public fun registerSegmentName (Ljava/lang/String;)V public fun registerTraceId (Lio/sentry/protocol/SentryId;)V public fun resume ()V + public fun resumeTouchTracking ()V public fun setBreadcrumbConverter (Lio/sentry/ReplayBreadcrumbConverter;)V public fun start ()V public fun startBuffering ()V diff --git a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java index 14533a7318b..3c2b5ccbcff 100644 --- a/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java +++ b/sentry/src/main/java/io/sentry/DefaultCompositePerformanceCollector.java @@ -169,7 +169,7 @@ public void onSpanFinished(@NotNull ISpan span) { SentryLevel.DEBUG, "stop collecting performance info for transactions %s (%s)", transaction.getName(), - transaction.getSpanContext().getTraceId().toString()); + transaction.getSpanContext().getTraceId()); for (final @NotNull IPerformanceContinuousCollector collector : continuousCollectors) { collector.onSpanFinished(transaction); @@ -181,7 +181,7 @@ public void onSpanFinished(@NotNull ISpan span) { @Override public @Nullable List stop(final @NotNull String id) { final @Nullable CompositeData data = compositeDataMap.remove(id); - options.getLogger().log(SentryLevel.DEBUG, "stop collecting performance info for " + id); + options.getLogger().log(SentryLevel.DEBUG, "stop collecting performance info for %s", id); // close if there are no more running requests if (compositeDataMap.isEmpty()) { diff --git a/sentry/src/main/java/io/sentry/DiagnosticLogger.java b/sentry/src/main/java/io/sentry/DiagnosticLogger.java index 1f067cd6f1b..11b12bc8bd0 100644 --- a/sentry/src/main/java/io/sentry/DiagnosticLogger.java +++ b/sentry/src/main/java/io/sentry/DiagnosticLogger.java @@ -57,6 +57,32 @@ public void log( } } + @Override + public void log(final @NotNull SentryLevel level, final @NotNull String message) { + if (logger != null && isEnabled(level)) { + logger.log(level, message); + } + } + + @Override + public void log( + final @NotNull SentryLevel level, final @NotNull String message, final @Nullable Object arg) { + if (logger != null && isEnabled(level)) { + logger.log(level, message, arg); + } + } + + @Override + public void log( + final @NotNull SentryLevel level, + final @NotNull String message, + final @Nullable Object arg1, + final @Nullable Object arg2) { + if (logger != null && isEnabled(level)) { + logger.log(level, message, arg1, arg2); + } + } + /** * Logs a message with the specified level, message and throwable. * diff --git a/sentry/src/main/java/io/sentry/EnvelopeSender.java b/sentry/src/main/java/io/sentry/EnvelopeSender.java index 9f630fc2602..0aed2d62614 100644 --- a/sentry/src/main/java/io/sentry/EnvelopeSender.java +++ b/sentry/src/main/java/io/sentry/EnvelopeSender.java @@ -67,7 +67,7 @@ protected void processFile(final @NotNull File file, final @NotNull Hint hint) { hint, Flushable.class, logger, - (flushable) -> { + flushable -> { if (!flushable.waitFlush()) { logger.log(SentryLevel.WARNING, "Timed out waiting for envelope submission."); } @@ -83,7 +83,7 @@ protected void processFile(final @NotNull File file, final @NotNull Hint hint) { hint, Retryable.class, logger, - (retryable) -> { + retryable -> { retryable.setRetry(false); logger.log(SentryLevel.INFO, e, "File '%s' won't retry.", file.getAbsolutePath()); }); @@ -93,7 +93,7 @@ protected void processFile(final @NotNull File file, final @NotNull Hint hint) { hint, Retryable.class, logger, - (retryable) -> { + retryable -> { if (!retryable.isRetry()) { safeDelete(file, "after trying to capture it"); logger.log(SentryLevel.DEBUG, "Deleted file %s.", file.getAbsolutePath()); diff --git a/sentry/src/main/java/io/sentry/ILogger.java b/sentry/src/main/java/io/sentry/ILogger.java index d709db01d1b..6d87eb0dfa7 100644 --- a/sentry/src/main/java/io/sentry/ILogger.java +++ b/sentry/src/main/java/io/sentry/ILogger.java @@ -15,6 +15,45 @@ public interface ILogger { */ void log(@NotNull SentryLevel level, @NotNull String message, @Nullable Object... args); + /** + * Logs a message without arguments. This overload and the overloads with one and two arguments do + * not allocate a varargs array at the call site. Thus, a disabled logger costs nothing. + * + * @param level The SentryLevel. + * @param message The message. + */ + default void log(final @NotNull SentryLevel level, final @NotNull String message) { + log(level, message, new Object[0]); + } + + /** + * Logs a message with one formatting argument. + * + * @param level The SentryLevel. + * @param message The message. + * @param arg The argument to format the message. + */ + default void log( + final @NotNull SentryLevel level, final @NotNull String message, final @Nullable Object arg) { + log(level, message, new Object[] {arg}); + } + + /** + * Logs a message with two formatting arguments. + * + * @param level The SentryLevel. + * @param message The message. + * @param arg1 The first argument to format the message. + * @param arg2 The second argument to format the message. + */ + default void log( + final @NotNull SentryLevel level, + final @NotNull String message, + final @Nullable Object arg1, + final @Nullable Object arg2) { + log(level, message, new Object[] {arg1, arg2}); + } + /** * Logs a message with the specified level, message and optional arguments. * diff --git a/sentry/src/main/java/io/sentry/IReplayApi.java b/sentry/src/main/java/io/sentry/IReplayApi.java index e15bcdaa542..aa076b72df1 100644 --- a/sentry/src/main/java/io/sentry/IReplayApi.java +++ b/sentry/src/main/java/io/sentry/IReplayApi.java @@ -32,6 +32,23 @@ public interface IReplayApi { /** Resumes a replay paused with {@link #pause()}. */ void resume(); + /** + * Stops recording touch events until {@link #resumeTouchTracking()} is called. Screenshots are + * still recorded. This can be used on sensitive screens, such as a custom PIN pad, where the + * screen is masked but the touch positions could reveal the input. + * + *

Touch tracking stays paused for all replays in the same process, also if the replay is + * stopped and started again. {@link #resume()} does not resume touch tracking. Has effect + * immediately, also before a replay is started. + */ + void pauseTouchTracking(); + + /** + * Resumes touch tracking paused with {@link #pauseTouchTracking()}. Touch events are recorded + * again only while the replay is not paused with {@link #pause()}. + */ + void resumeTouchTracking(); + /** * Immediately sends the current replay data to Sentry in either session or buffer mode. A * buffering replay continues in session mode after the buffer is sent. If replay is not diff --git a/sentry/src/main/java/io/sentry/NoOpLogger.java b/sentry/src/main/java/io/sentry/NoOpLogger.java index b42f5c6f05e..d78adbaaac0 100644 --- a/sentry/src/main/java/io/sentry/NoOpLogger.java +++ b/sentry/src/main/java/io/sentry/NoOpLogger.java @@ -19,6 +19,19 @@ private NoOpLogger() {} @Override public void log(@NotNull SentryLevel level, @NotNull String message, @Nullable Object... args) {} + @Override + public void log(@NotNull SentryLevel level, @NotNull String message) {} + + @Override + public void log(@NotNull SentryLevel level, @NotNull String message, @Nullable Object arg) {} + + @Override + public void log( + @NotNull SentryLevel level, + @NotNull String message, + @Nullable Object arg1, + @Nullable Object arg2) {} + @Override public void log( @NotNull SentryLevel level, @NotNull String message, @Nullable Throwable throwable) {} diff --git a/sentry/src/main/java/io/sentry/NoOpReplayController.java b/sentry/src/main/java/io/sentry/NoOpReplayController.java index 669e42f3116..a537ca064ff 100644 --- a/sentry/src/main/java/io/sentry/NoOpReplayController.java +++ b/sentry/src/main/java/io/sentry/NoOpReplayController.java @@ -31,6 +31,12 @@ public void pause() {} @Override public void resume() {} + @Override + public void pauseTouchTracking() {} + + @Override + public void resumeTouchTracking() {} + @Override public void flush() {} diff --git a/sentry/src/main/java/io/sentry/OutboxSender.java b/sentry/src/main/java/io/sentry/OutboxSender.java index cbe4f6ee007..21952dc0c5a 100644 --- a/sentry/src/main/java/io/sentry/OutboxSender.java +++ b/sentry/src/main/java/io/sentry/OutboxSender.java @@ -82,7 +82,7 @@ protected void processFile(final @NotNull File file, @NotNull Hint hint) { hint, Retryable.class, logger, - (retryable) -> { + retryable -> { if (!retryable.isRetry()) { try { if (!file.delete()) { @@ -227,7 +227,7 @@ private void processEnvelope(final @NotNull SentryEnvelope envelope, final @NotN } // reset the Hint to its initial state as we use it multiple times. - HintUtils.runIfHasType(hint, Resettable.class, (resettable) -> resettable.reset()); + HintUtils.runIfHasType(hint, Resettable.class, resettable -> resettable.reset()); } } diff --git a/sentry/src/main/java/io/sentry/Scopes.java b/sentry/src/main/java/io/sentry/Scopes.java index 4edd9180d25..75c263c4127 100644 --- a/sentry/src/main/java/io/sentry/Scopes.java +++ b/sentry/src/main/java/io/sentry/Scopes.java @@ -1084,13 +1084,11 @@ public void reportFullyDisplayed() { PropagationContext propagationContext = PropagationContext.fromHeaders( getOptions().getLogger(), sentryTrace, baggageHeaders, getOptions()); - configureScope( - (scope) -> { - scope.withPropagationContext( - oldPropagationContext -> { - scope.setPropagationContext(propagationContext); - }); - }); + configureScope(scope -> { + scope.withPropagationContext(oldPropagationContext -> { + scope.setPropagationContext(propagationContext); + }); + }); if (getOptions().isTracingEnabled()) { return TransactionContext.fromPropagationContext(propagationContext); } else { diff --git a/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java b/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java index 3ba7ab6503a..a9a8c1d8fe2 100644 --- a/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java +++ b/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java @@ -110,62 +110,57 @@ private void sendCachedEnvelopes( try (final @NotNull ISentryLifecycleToken ignored = lock.acquire()) { options .getExecutorService() - .submit( - () -> { - try { - if (isClosed.get()) { - options - .getLogger() - .log( - SentryLevel.INFO, - "SendCachedEnvelopeFireAndForgetIntegration, not trying to send after closing."); - return; - } - - if (!isInitialized.getAndSet(true)) { - connectionStatusProvider = options.getConnectionStatusProvider(); - connectionStatusProvider.addConnectionStatusObserver(this); - - sender = factory.create(scopes, options); - } - - // skip run only if we're certainly disconnected - if (connectionStatusProvider != null - && connectionStatusProvider.getConnectionStatus() - == IConnectionStatusProvider.ConnectionStatus.DISCONNECTED) { - options - .getLogger() - .log( - SentryLevel.INFO, - "SendCachedEnvelopeFireAndForgetIntegration, no connection."); - return; - } - - // in case there's rate limiting active, skip processing - final @Nullable RateLimiter rateLimiter = scopes.getRateLimiter(); - if (rateLimiter != null && rateLimiter.isActiveForCategory(DataCategory.All)) { - options - .getLogger() - .log( - SentryLevel.INFO, - "SendCachedEnvelopeFireAndForgetIntegration, rate limiting active."); - return; - } - - if (sender == null) { - options - .getLogger() - .log(SentryLevel.ERROR, "SendFireAndForget factory is null."); - return; - } - - sender.send(); - } catch (Throwable e) { - options - .getLogger() - .log(SentryLevel.ERROR, "Failed trying to send cached events.", e); - } - }); + .submit(() -> { + try { + if (isClosed.get()) { + options + .getLogger() + .log( + SentryLevel.INFO, + "SendCachedEnvelopeFireAndForgetIntegration, not trying to send after closing."); + return; + } + + if (!isInitialized.getAndSet(true)) { + connectionStatusProvider = options.getConnectionStatusProvider(); + connectionStatusProvider.addConnectionStatusObserver(this); + + sender = factory.create(scopes, options); + } + + // skip run only if we're certainly disconnected + if (connectionStatusProvider != null + && connectionStatusProvider.getConnectionStatus() + == IConnectionStatusProvider.ConnectionStatus.DISCONNECTED) { + options + .getLogger() + .log( + SentryLevel.INFO, + "SendCachedEnvelopeFireAndForgetIntegration, no connection."); + return; + } + + // in case there's rate limiting active, skip processing + final @Nullable RateLimiter rateLimiter = scopes.getRateLimiter(); + if (rateLimiter != null && rateLimiter.isActiveForCategory(DataCategory.All)) { + options + .getLogger() + .log( + SentryLevel.INFO, + "SendCachedEnvelopeFireAndForgetIntegration, rate limiting active."); + return; + } + + if (sender == null) { + options.getLogger().log(SentryLevel.ERROR, "SendFireAndForget factory is null."); + return; + } + + sender.send(); + } catch (Throwable e) { + options.getLogger().log(SentryLevel.ERROR, "Failed trying to send cached events.", e); + } + }); } catch (RejectedExecutionException e) { options .getLogger() diff --git a/sentry/src/main/java/io/sentry/Sentry.java b/sentry/src/main/java/io/sentry/Sentry.java index 932569177b4..ce286600477 100644 --- a/sentry/src/main/java/io/sentry/Sentry.java +++ b/sentry/src/main/java/io/sentry/Sentry.java @@ -442,62 +442,60 @@ private static void handleAppStartProfilingConfig( final @NotNull SentryOptions options, final @NotNull ISentryExecutorService sentryExecutorService) { try { - sentryExecutorService.submit( - () -> { - final String cacheDirPath = options.getCacheDirPathWithoutDsn(); - if (cacheDirPath != null) { - final @NotNull File cacheDir = new File(cacheDirPath); - final @NotNull File appStartProfilingConfigFile = - new File(cacheDir, APP_START_PROFILING_CONFIG_FILE_NAME); - try { - // We always delete the config file for app start profiling - FileUtils.deleteRecursively(appStartProfilingConfigFile); - if (!options.isEnableAppStartProfiling() && !options.isStartProfilerOnAppStart()) { - return; - } - // isStartProfilerOnAppStart doesn't need tracing, as it can be started/stopped - // manually - if (!options.isStartProfilerOnAppStart() && !options.isTracingEnabled()) { - options - .getLogger() - .log( - SentryLevel.INFO, - "Tracing is disabled and app start profiling will not start."); - return; - } - // The cache dir is no longer created during init, so create it here before writing: - // createNewFile() fails if the parent is missing. - if (!FileUtils.createDirectory(cacheDir)) { - options - .getLogger() - .log(SentryLevel.ERROR, "Failed to create cache dir %s", cacheDirPath); - return; - } - if (appStartProfilingConfigFile.createNewFile()) { - // If old app start profiling is false, it means the transaction will not be - // sampled, but we create the file anyway to allow continuous profiling on app - // start - final @NotNull TracesSamplingDecision appStartSamplingDecision = - options.isEnableAppStartProfiling() - ? sampleAppStartProfiling(options) - : new TracesSamplingDecision(false); - final @NotNull SentryAppStartProfilingOptions appStartProfilingOptions = - new SentryAppStartProfilingOptions(options, appStartSamplingDecision); - try (final OutputStream outputStream = - new FileOutputStream(appStartProfilingConfigFile); - final Writer writer = - new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8))) { - options.getSerializer().serialize(appStartProfilingOptions, writer); - } - } - } catch (Throwable e) { - options - .getLogger() - .log( - SentryLevel.ERROR, "Unable to create app start profiling config file. ", e); + sentryExecutorService.submit(() -> { + final String cacheDirPath = options.getCacheDirPathWithoutDsn(); + if (cacheDirPath != null) { + final @NotNull File cacheDir = new File(cacheDirPath); + final @NotNull File appStartProfilingConfigFile = + new File(cacheDir, APP_START_PROFILING_CONFIG_FILE_NAME); + try { + // We always delete the config file for app start profiling + FileUtils.deleteRecursively(appStartProfilingConfigFile); + if (!options.isEnableAppStartProfiling() && !options.isStartProfilerOnAppStart()) { + return; + } + // isStartProfilerOnAppStart doesn't need tracing, as it can be started/stopped + // manually + if (!options.isStartProfilerOnAppStart() && !options.isTracingEnabled()) { + options + .getLogger() + .log( + SentryLevel.INFO, + "Tracing is disabled and app start profiling will not start."); + return; + } + // The cache dir is no longer created during init, so create it here before writing: + // createNewFile() fails if the parent is missing. + if (!FileUtils.createDirectory(cacheDir)) { + options + .getLogger() + .log(SentryLevel.ERROR, "Failed to create cache dir %s", cacheDirPath); + return; + } + if (appStartProfilingConfigFile.createNewFile()) { + // If old app start profiling is false, it means the transaction will not be + // sampled, but we create the file anyway to allow continuous profiling on app + // start + final @NotNull TracesSamplingDecision appStartSamplingDecision = + options.isEnableAppStartProfiling() + ? sampleAppStartProfiling(options) + : new TracesSamplingDecision(false); + final @NotNull SentryAppStartProfilingOptions appStartProfilingOptions = + new SentryAppStartProfilingOptions(options, appStartSamplingDecision); + try (final OutputStream outputStream = + new FileOutputStream(appStartProfilingConfigFile); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8))) { + options.getSerializer().serialize(appStartProfilingOptions, writer); } } - }); + } catch (Throwable e) { + options + .getLogger() + .log(SentryLevel.ERROR, "Unable to create app start profiling config file. ", e); + } + } + }); } catch (Throwable e) { options .getLogger() @@ -549,36 +547,34 @@ private static void notifyOptionsObservers(final @NotNull SentryOptions options) try { options .getExecutorService() - .submit( - () -> { - // for static things like sentry options we can immediately trigger observers - for (final IOptionsObserver observer : options.getOptionsObservers()) { - observer.setRelease(options.getRelease()); - observer.setProguardUuid(options.getProguardUuid()); - observer.setSdkVersion(options.getSdkVersion()); - observer.setDist(options.getDist()); - observer.setEnvironment(options.getEnvironment()); - observer.setTags(options.getTags()); - observer.setReplayErrorSampleRate( - options.getSessionReplay().getOnErrorSampleRate()); - } + .submit(() -> { + // for static things like sentry options we can immediately trigger observers + for (final IOptionsObserver observer : options.getOptionsObservers()) { + observer.setRelease(options.getRelease()); + observer.setProguardUuid(options.getProguardUuid()); + observer.setSdkVersion(options.getSdkVersion()); + observer.setDist(options.getDist()); + observer.setEnvironment(options.getEnvironment()); + observer.setTags(options.getTags()); + observer.setReplayErrorSampleRate(options.getSessionReplay().getOnErrorSampleRate()); + } - // since it's a new SDK init we clean up persisted scope values before serializing - // new ones, so they are not making it to the new events if they were e.g. disabled - // (e.g. replayId) or are simply irrelevant (e.g. breadcrumbs). NOTE: this happens - // after the integrations relying on those values are done with processing them. - final @Nullable PersistingScopeObserver scopeCache = - options.findPersistingScopeObserver(); - if (scopeCache != null) { - scopeCache.resetCache(); - // the scope environment is configuration, not telemetry state, so we persist it - // again after the reset to keep it available for the next app launch - final @Nullable String environment = globalScope.getEnvironment(); - if (environment != null) { - scopeCache.setEnvironment(environment); - } - } - }); + // since it's a new SDK init we clean up persisted scope values before serializing + // new ones, so they are not making it to the new events if they were e.g. disabled + // (e.g. replayId) or are simply irrelevant (e.g. breadcrumbs). NOTE: this happens + // after the integrations relying on those values are done with processing them. + final @Nullable PersistingScopeObserver scopeCache = + options.findPersistingScopeObserver(); + if (scopeCache != null) { + scopeCache.resetCache(); + // the scope environment is configuration, not telemetry state, so we persist it + // again after the reset to keep it available for the next app launch + final @Nullable String environment = globalScope.getEnvironment(); + if (environment != null) { + scopeCache.setEnvironment(environment); + } + } + }); } catch (Throwable e) { options.getLogger().log(SentryLevel.DEBUG, "Failed to notify options observers.", e); } @@ -639,20 +635,19 @@ private static void initConfigurations(final @NotNull SentryOptions options) { try { options .getExecutorService() - .submit( - () -> { - final File[] oldTracesDirContent = profilingTracesDir.listFiles(); - if (oldTracesDirContent == null) return; - // Method trace files are normally deleted at the end of traces, but if that fails - // for some reason we try to clear any old files here. - for (File f : oldTracesDirContent) { - // We delete files 5 minutes older than class creation to account for app - // start profiles, as an app start profile could have a lower creation date. - if (f.lastModified() < classCreationTimestamp - TimeUnit.MINUTES.toMillis(5)) { - FileUtils.deleteRecursively(f); - } - } - }); + .submit(() -> { + final File[] oldTracesDirContent = profilingTracesDir.listFiles(); + if (oldTracesDirContent == null) return; + // Method trace files are normally deleted at the end of traces, but if that fails + // for some reason we try to clear any old files here. + for (File f : oldTracesDirContent) { + // We delete files 5 minutes older than class creation to account for app + // start profiles, as an app start profile could have a lower creation date. + if (f.lastModified() < classCreationTimestamp - TimeUnit.MINUTES.toMillis(5)) { + FileUtils.deleteRecursively(f); + } + } + }); } catch (RejectedExecutionException e) { options .getLogger() diff --git a/sentry/src/main/java/io/sentry/SentryClient.java b/sentry/src/main/java/io/sentry/SentryClient.java index e0b1901f9b8..b5027432625 100644 --- a/sentry/src/main/java/io/sentry/SentryClient.java +++ b/sentry/src/main/java/io/sentry/SentryClient.java @@ -851,45 +851,42 @@ Session updateSessionData( if (HintUtils.shouldApplyScopeData(hint)) { if (scope != null) { clonedSession = - scope.withSession( - session -> { - if (session != null) { - Session.State status = null; - if (event.isCrashed()) { - status = Session.State.Crashed; - } - - boolean crashedOrErrored = false; - if (Session.State.Crashed == status || event.isErrored()) { - crashedOrErrored = true; - } - - String userAgent = null; - if (event.getRequest() != null && event.getRequest().getHeaders() != null) { - if (event.getRequest().getHeaders().containsKey("user-agent")) { - userAgent = event.getRequest().getHeaders().get("user-agent"); - } - } - - final Object sentrySdkHint = HintUtils.getSentrySdkHint(hint); - @Nullable String abnormalMechanism = null; - if (sentrySdkHint instanceof AbnormalExit) { - abnormalMechanism = ((AbnormalExit) sentrySdkHint).mechanism(); - status = Session.State.Abnormal; - } - - if (session.update(status, userAgent, crashedOrErrored, abnormalMechanism)) { - // if session terminated we can end it. - if (session.isTerminated()) { - session.end(); - } - } - } else { - options - .getLogger() - .log(SentryLevel.INFO, "Session is null on scope.withSession"); + scope.withSession(session -> { + if (session != null) { + Session.State status = null; + if (event.isCrashed()) { + status = Session.State.Crashed; + } + + boolean crashedOrErrored = false; + if (Session.State.Crashed == status || event.isErrored()) { + crashedOrErrored = true; + } + + String userAgent = null; + if (event.getRequest() != null && event.getRequest().getHeaders() != null) { + if (event.getRequest().getHeaders().containsKey("user-agent")) { + userAgent = event.getRequest().getHeaders().get("user-agent"); } - }); + } + + final Object sentrySdkHint = HintUtils.getSentrySdkHint(hint); + @Nullable String abnormalMechanism = null; + if (sentrySdkHint instanceof AbnormalExit) { + abnormalMechanism = ((AbnormalExit) sentrySdkHint).mechanism(); + status = Session.State.Abnormal; + } + + if (session.update(status, userAgent, crashedOrErrored, abnormalMechanism)) { + // if session terminated we can end it. + if (session.isTerminated()) { + session.end(); + } + } + } else { + options.getLogger().log(SentryLevel.INFO, "Session is null on scope.withSession"); + } + }); } else { options.getLogger().log(SentryLevel.INFO, "Scope is null on client.captureEvent"); } diff --git a/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java b/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java index 3d1552a523d..2873d2c8ad4 100644 --- a/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java +++ b/sentry/src/main/java/io/sentry/SentryEnvelopeItem.java @@ -85,16 +85,14 @@ public final class SentryEnvelopeItem { Objects.requireNonNull(session, "Session is required."); final CachedItem cachedItem = - new CachedItem( - () -> { - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - serializer.serialize(session, writer); - return stream.toByteArray(); - } - }); + new CachedItem(() -> { + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + serializer.serialize(session, writer); + return stream.toByteArray(); + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -121,16 +119,14 @@ public final class SentryEnvelopeItem { Objects.requireNonNull(event, "SentryEvent is required."); final CachedItem cachedItem = - new CachedItem( - () -> { - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - serializer.serialize(event, writer); - return stream.toByteArray(); - } - }); + new CachedItem(() -> { + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + serializer.serialize(event, writer); + return stream.toByteArray(); + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -182,16 +178,14 @@ public static SentryEnvelopeItem fromCheckIn( Objects.requireNonNull(checkIn, "CheckIn is required."); final CachedItem cachedItem = - new CachedItem( - () -> { - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - serializer.serialize(checkIn, writer); - return stream.toByteArray(); - } - }); + new CachedItem(() -> { + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + serializer.serialize(checkIn, writer); + return stream.toByteArray(); + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -209,40 +203,37 @@ public static SentryEnvelopeItem fromAttachment( final long maxAttachmentSize) { final CachedItem cachedItem = - new CachedItem( - () -> { - if (attachment.getBytes() != null) { - final byte[] data = attachment.getBytes(); - ensureAttachmentSizeLimit(data.length, maxAttachmentSize, attachment.getFilename()); - return data; - } else if (attachment.getSerializable() != null) { - final JsonSerializable serializable = attachment.getSerializable(); - @SuppressWarnings("NullableProblems") - final @Nullable byte[] data = - JsonSerializationUtils.bytesFrom(serializer, logger, serializable); - - if (data != null) { - ensureAttachmentSizeLimit( - data.length, maxAttachmentSize, attachment.getFilename()); - return data; - } - } else if (attachment.getPathname() != null) { - return readBytesFromFile(attachment.getPathname(), maxAttachmentSize); - } else if (attachment.getByteProvider() != null) { - @SuppressWarnings("NullableProblems") - final @Nullable byte[] data = attachment.getByteProvider().call(); - if (data != null) { - ensureAttachmentSizeLimit( - data.length, maxAttachmentSize, attachment.getFilename()); - return data; - } - } - throw new SentryEnvelopeException( - String.format( - "Couldn't attach the attachment %s.\n" - + "Please check that either bytes, serializable, path or provider is set.", - attachment.getFilename())); - }); + new CachedItem(() -> { + if (attachment.getBytes() != null) { + final byte[] data = attachment.getBytes(); + ensureAttachmentSizeLimit(data.length, maxAttachmentSize, attachment.getFilename()); + return data; + } else if (attachment.getSerializable() != null) { + final JsonSerializable serializable = attachment.getSerializable(); + @SuppressWarnings("NullableProblems") + final @Nullable byte[] data = + JsonSerializationUtils.bytesFrom(serializer, logger, serializable); + + if (data != null) { + ensureAttachmentSizeLimit(data.length, maxAttachmentSize, attachment.getFilename()); + return data; + } + } else if (attachment.getPathname() != null) { + return readBytesFromFile(attachment.getPathname(), maxAttachmentSize); + } else if (attachment.getByteProvider() != null) { + @SuppressWarnings("NullableProblems") + final @Nullable byte[] data = attachment.getByteProvider().call(); + if (data != null) { + ensureAttachmentSizeLimit(data.length, maxAttachmentSize, attachment.getFilename()); + return data; + } + } + throw new SentryEnvelopeException( + String.format( + "Couldn't attach the attachment %s.\n" + + "Please check that either bytes, serializable, path or provider is set.", + attachment.getFilename())); + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -287,59 +278,56 @@ private static void ensureAttachmentSizeLimit( final @Nullable File traceFile = profileChunk.getTraceFile(); // Using CachedItem, so we read the trace file in the background final CachedItem cachedItem = - new CachedItem( - () -> { - if (traceFile != null) { - if (!traceFile.exists()) { - throw new SentryEnvelopeException( - String.format( - "Dropping profile chunk, because the file '%s' doesn't exists", - traceFile.getName())); - } - - if (ProfileChunk.PLATFORM_JAVA.equals(profileChunk.getPlatform())) { - if (!NoOpProfileConverter.getInstance().equals(profileConverter)) { - try { - final SentryProfile profile = - profileConverter.convertFromFile(traceFile.getAbsolutePath()); - profileChunk.setSentryProfile(profile); - } catch (Exception e) { - throw new SentryEnvelopeException("Profile conversion failed", e); - } - } else { - throw new SentryEnvelopeException( - "No ProfileConverter available, dropping chunk."); - } - } else { - // The payload of the profile item is a json including the trace file encoded with - // base64 - final byte[] traceFileBytes = - readBytesFromFile(traceFile.getPath(), MAX_PROFILE_CHUNK_SIZE); - final @NotNull String base64Trace = - Base64.encodeToString(traceFileBytes, NO_WRAP | NO_PADDING); - if (base64Trace.isEmpty()) { - throw new SentryEnvelopeException("Profiling trace file is empty"); - } - profileChunk.setSampledProfile(base64Trace); + new CachedItem(() -> { + if (traceFile != null) { + if (!traceFile.exists()) { + throw new SentryEnvelopeException( + String.format( + "Dropping profile chunk, because the file '%s' doesn't exists", + traceFile.getName())); + } + + if (ProfileChunk.PLATFORM_JAVA.equals(profileChunk.getPlatform())) { + if (!NoOpProfileConverter.getInstance().equals(profileConverter)) { + try { + final SentryProfile profile = + profileConverter.convertFromFile(traceFile.getAbsolutePath()); + profileChunk.setSentryProfile(profile); + } catch (Exception e) { + throw new SentryEnvelopeException("Profile conversion failed", e); } + } else { + throw new SentryEnvelopeException("No ProfileConverter available, dropping chunk."); } - - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - serializer.serialize(profileChunk, writer); - return stream.toByteArray(); - } catch (IOException e) { - throw new SentryEnvelopeException( - String.format("Failed to serialize profile chunk\n%s", e.getMessage())); - } finally { - // In any case we delete the trace file - if (traceFile != null) { - traceFile.delete(); - } + } else { + // The payload of the profile item is a json including the trace file encoded with + // base64 + final byte[] traceFileBytes = + readBytesFromFile(traceFile.getPath(), MAX_PROFILE_CHUNK_SIZE); + final @NotNull String base64Trace = + Base64.encodeToString(traceFileBytes, NO_WRAP | NO_PADDING); + if (base64Trace.isEmpty()) { + throw new SentryEnvelopeException("Profiling trace file is empty"); } - }); + profileChunk.setSampledProfile(base64Trace); + } + } + + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + serializer.serialize(profileChunk, writer); + return stream.toByteArray(); + } catch (IOException e) { + throw new SentryEnvelopeException( + String.format("Failed to serialize profile chunk\n%s", e.getMessage())); + } finally { + // In any case we delete the trace file + if (traceFile != null) { + traceFile.delete(); + } + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -376,40 +364,38 @@ private static void ensureAttachmentSizeLimit( final AtomicReference metaLength = new AtomicReference<>(null); final CachedItem cachedItem = - new CachedItem( - () -> { - // Serialize JSON metadata - final byte[] metadataBytes; - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, UTF_8))) { - serializer.serialize(profileChunk, writer); - writer.flush(); - metadataBytes = stream.toByteArray(); - metaLength.set(metadataBytes.length); - } catch (IOException e) { - throw new SentryEnvelopeException( - String.format( - "Failed to serialize perfetto profile chunk\n%s", e.getMessage())); - } - - // Read binary Perfetto trace - final byte[] traceBytes; - try { - traceBytes = readBytesFromFile(traceFile.getPath(), 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; - }); + new CachedItem(() -> { + // Serialize JSON metadata + final byte[] metadataBytes; + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, UTF_8))) { + serializer.serialize(profileChunk, writer); + writer.flush(); + metadataBytes = stream.toByteArray(); + metaLength.set(metadataBytes.length); + } catch (IOException e) { + throw new SentryEnvelopeException( + String.format("Failed to serialize perfetto profile chunk\n%s", e.getMessage())); + } + + // Read binary Perfetto trace + final byte[] traceBytes; + try { + traceBytes = readBytesFromFile(traceFile.getPath(), 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 = new SentryEnvelopeItemHeader( @@ -438,40 +424,37 @@ private static void ensureAttachmentSizeLimit( final @NotNull File traceFile = profilingTraceData.getTraceFile(); // Using CachedItem, so we read the trace file in the background final CachedItem cachedItem = - new CachedItem( - () -> { - if (!traceFile.exists()) { - throw new SentryEnvelopeException( - String.format( - "Dropping profiling trace data, because the file '%s' doesn't exists", - traceFile.getName())); - } - // The payload of the profile item is a json including the trace file encoded with - // base64 - final byte[] traceFileBytes = - readBytesFromFile(traceFile.getPath(), maxTraceFileSize); - final @NotNull String base64Trace = - Base64.encodeToString(traceFileBytes, NO_WRAP | NO_PADDING); - if (base64Trace.isEmpty()) { - throw new SentryEnvelopeException("Profiling trace file is empty"); - } - profilingTraceData.setSampledProfile(base64Trace); - profilingTraceData.readDeviceCpuFrequencies(); - - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - serializer.serialize(profilingTraceData, writer); - return stream.toByteArray(); - } catch (IOException e) { - throw new SentryEnvelopeException( - String.format("Failed to serialize profiling trace data\n%s", e.getMessage())); - } finally { - // In any case we delete the trace file - traceFile.delete(); - } - }); + new CachedItem(() -> { + if (!traceFile.exists()) { + throw new SentryEnvelopeException( + String.format( + "Dropping profiling trace data, because the file '%s' doesn't exists", + traceFile.getName())); + } + // The payload of the profile item is a json including the trace file encoded with + // base64 + final byte[] traceFileBytes = readBytesFromFile(traceFile.getPath(), maxTraceFileSize); + final @NotNull String base64Trace = + Base64.encodeToString(traceFileBytes, NO_WRAP | NO_PADDING); + if (base64Trace.isEmpty()) { + throw new SentryEnvelopeException("Profiling trace file is empty"); + } + profilingTraceData.setSampledProfile(base64Trace); + profilingTraceData.readDeviceCpuFrequencies(); + + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + serializer.serialize(profilingTraceData, writer); + return stream.toByteArray(); + } catch (IOException e) { + throw new SentryEnvelopeException( + String.format("Failed to serialize profiling trace data\n%s", e.getMessage())); + } finally { + // In any case we delete the trace file + traceFile.delete(); + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -492,16 +475,14 @@ private static void ensureAttachmentSizeLimit( Objects.requireNonNull(clientReport, "ClientReport is required."); final CachedItem cachedItem = - new CachedItem( - () -> { - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - serializer.serialize(clientReport, writer); - return stream.toByteArray(); - } - }); + new CachedItem(() -> { + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + serializer.serialize(clientReport, writer); + return stream.toByteArray(); + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -536,53 +517,51 @@ public static SentryEnvelopeItem fromReplay( final File replayVideo = replayEvent.getVideoFile(); final CachedItem cachedItem = - new CachedItem( - () -> { - try { - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - // relay expects the payload to be in this exact order: [event,rrweb,video] - final Map replayPayload = new LinkedHashMap<>(); - // first serialize replay event json bytes - serializer.serialize(replayEvent, writer); - replayPayload.put(SentryItemType.ReplayEvent.getItemType(), stream.toByteArray()); - stream.reset(); - - // next serialize replay recording - if (replayRecording != null) { - serializer.serialize(replayRecording, writer); - replayPayload.put( - SentryItemType.ReplayRecording.getItemType(), stream.toByteArray()); - stream.reset(); - } - - // next serialize replay video bytes from given file - if (replayVideo != null && replayVideo.exists()) { - final byte[] videoBytes = - readBytesFromFile( - replayVideo.getPath(), SentryReplayEvent.REPLAY_VIDEO_MAX_SIZE); - if (videoBytes.length > 0) { - replayPayload.put(SentryItemType.ReplayVideo.getItemType(), videoBytes); - } - } - - return serializeToMsgpack(replayPayload); - } - } catch (Throwable t) { - logger.log(SentryLevel.ERROR, "Could not serialize replay recording", t); - return null; - } finally { - if (replayVideo != null) { - if (cleanupReplayFolder) { - FileUtils.deleteRecursively(replayVideo.getParentFile()); - } else { - replayVideo.delete(); - } + new CachedItem(() -> { + try { + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + // relay expects the payload to be in this exact order: [event,rrweb,video] + final Map replayPayload = new LinkedHashMap<>(); + // first serialize replay event json bytes + serializer.serialize(replayEvent, writer); + replayPayload.put(SentryItemType.ReplayEvent.getItemType(), stream.toByteArray()); + stream.reset(); + + // next serialize replay recording + if (replayRecording != null) { + serializer.serialize(replayRecording, writer); + replayPayload.put( + SentryItemType.ReplayRecording.getItemType(), stream.toByteArray()); + stream.reset(); + } + + // next serialize replay video bytes from given file + if (replayVideo != null && replayVideo.exists()) { + final byte[] videoBytes = + readBytesFromFile( + replayVideo.getPath(), SentryReplayEvent.REPLAY_VIDEO_MAX_SIZE); + if (videoBytes.length > 0) { + replayPayload.put(SentryItemType.ReplayVideo.getItemType(), videoBytes); } } - }); + + return serializeToMsgpack(replayPayload); + } + } catch (Throwable t) { + logger.log(SentryLevel.ERROR, "Could not serialize replay recording", t); + return null; + } finally { + if (replayVideo != null) { + if (cleanupReplayFolder) { + FileUtils.deleteRecursively(replayVideo.getParentFile()); + } else { + replayVideo.delete(); + } + } + } + }); final SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -599,16 +578,14 @@ public static SentryEnvelopeItem fromLogs( Objects.requireNonNull(logEvents, "SentryLogEvents is required."); final CachedItem cachedItem = - new CachedItem( - () -> { - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - serializer.serialize(logEvents, writer); - return stream.toByteArray(); - } - }); + new CachedItem(() -> { + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + serializer.serialize(logEvents, writer); + return stream.toByteArray(); + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( @@ -631,16 +608,14 @@ public static SentryEnvelopeItem fromMetrics( Objects.requireNonNull(metricsEvents, "SentryMetricsEvents is required."); final CachedItem cachedItem = - new CachedItem( - () -> { - try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final Writer writer = - new BufferedWriter( - new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { - serializer.serialize(metricsEvents, writer); - return stream.toByteArray(); - } - }); + new CachedItem(() -> { + try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final Writer writer = + new BufferedWriter(new OutputStreamWriter(stream, UTF_8), WRITER_BUFFER_SIZE)) { + serializer.serialize(metricsEvents, writer); + return stream.toByteArray(); + } + }); SentryEnvelopeItemHeader itemHeader = new SentryEnvelopeItemHeader( diff --git a/sentry/src/main/java/io/sentry/SentryStackTraceFactory.java b/sentry/src/main/java/io/sentry/SentryStackTraceFactory.java index 3a36228784d..611be4fc418 100644 --- a/sentry/src/main/java/io/sentry/SentryStackTraceFactory.java +++ b/sentry/src/main/java/io/sentry/SentryStackTraceFactory.java @@ -130,7 +130,7 @@ List getInAppCallStack(final @NotNull Throwable exception) { } final List inAppFrames = - CollectionUtils.filterListEntries(frames, (frame) -> Boolean.TRUE.equals(frame.isInApp())); + CollectionUtils.filterListEntries(frames, frame -> Boolean.TRUE.equals(frame.isInApp())); if (!inAppFrames.isEmpty()) { return inAppFrames; @@ -140,7 +140,7 @@ List getInAppCallStack(final @NotNull Throwable exception) { // fallback to all the frames that are not system frames return CollectionUtils.filterListEntries( frames, - (frame) -> { + frame -> { final String module = frame.getModule(); boolean isSystemFrame = false; if (module != null) { diff --git a/sentry/src/main/java/io/sentry/SentryTracer.java b/sentry/src/main/java/io/sentry/SentryTracer.java index 93c20d73d05..0970f30bed6 100644 --- a/sentry/src/main/java/io/sentry/SentryTracer.java +++ b/sentry/src/main/java/io/sentry/SentryTracer.java @@ -209,24 +209,22 @@ public void finish( // We set the new spanFinishedCallback here instead of creation time, calling the old one to // avoid the user overwrites it by setting a custom spanFinishedCallback on the root span final @Nullable SpanFinishedCallback oldCallback = this.root.getSpanFinishedCallback(); - this.root.setSpanFinishedCallback( - span -> { - if (oldCallback != null) { - oldCallback.execute(span); - } - - // Let's call the finishCallback here, when the root span has a finished date but it's - // not finished, yet - final @Nullable TransactionFinishedCallback finishedCallback = - transactionFinishedCallback; - if (finishedCallback != null) { - finishedCallback.execute(this); - } - - if (compositePerformanceCollector != null) { - performanceCollectionData.set(compositePerformanceCollector.stop(this)); - } - }); + this.root.setSpanFinishedCallback(span -> { + if (oldCallback != null) { + oldCallback.execute(span); + } + + // Let's call the finishCallback here, when the root span has a finished date but it's + // not finished, yet + final @Nullable TransactionFinishedCallback finishedCallback = transactionFinishedCallback; + if (finishedCallback != null) { + finishedCallback.execute(this); + } + + if (compositePerformanceCollector != null) { + performanceCollectionData.set(compositePerformanceCollector.stop(this)); + } + }); // any un-finished children will remain unfinished // as relay takes care of setting the end-timestamp + deadline_exceeded @@ -251,15 +249,13 @@ public void finish( performanceCollectionData.get().clear(); } - scopes.configureScope( - scope -> { - scope.withTransaction( - transaction -> { - if (transaction == this) { - scope.clearTransaction(); - } - }); - }); + scopes.configureScope(scope -> { + scope.withTransaction(transaction -> { + if (transaction == this) { + scope.clearTransaction(); + } + }); + }); dropUnrecordedProfilerIds(finishTimestamp); final SentryTransaction transaction = new SentryTransaction(this); @@ -963,10 +959,9 @@ public void setName(@NotNull String name, @NotNull TransactionNameSource transac @ApiStatus.Internal @Override public @NotNull ISentryLifecycleToken makeCurrent() { - scopes.configureScope( - (scope) -> { - scope.setTransaction(this); - }); + scopes.configureScope(scope -> { + scope.setTransaction(this); + }); return NoOpScopesLifecycleToken.getInstance(); } diff --git a/sentry/src/main/java/io/sentry/ShutdownHookIntegration.java b/sentry/src/main/java/io/sentry/ShutdownHookIntegration.java index 9a70e31cee6..6cb1260c88f 100644 --- a/sentry/src/main/java/io/sentry/ShutdownHookIntegration.java +++ b/sentry/src/main/java/io/sentry/ShutdownHookIntegration.java @@ -34,12 +34,11 @@ public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions if (options.isEnableShutdownHook()) { thread = new Thread(() -> scopes.flush(options.getFlushTimeoutMillis()), "sentry-shutdownhook"); - handleShutdownInProgress( - () -> { - runtime.addShutdownHook(thread); - options.getLogger().log(SentryLevel.DEBUG, "ShutdownHookIntegration installed."); - addIntegrationToSdkVersion("ShutdownHook"); - }); + handleShutdownInProgress(() -> { + runtime.addShutdownHook(thread); + options.getLogger().log(SentryLevel.DEBUG, "ShutdownHookIntegration installed."); + addIntegrationToSdkVersion("ShutdownHook"); + }); } else { options.getLogger().log(SentryLevel.INFO, "enableShutdownHook is disabled."); } diff --git a/sentry/src/main/java/io/sentry/cache/PersistingScopeObserver.java b/sentry/src/main/java/io/sentry/cache/PersistingScopeObserver.java index 756f36f65da..cf3bfcb3d15 100644 --- a/sentry/src/main/java/io/sentry/cache/PersistingScopeObserver.java +++ b/sentry/src/main/java/io/sentry/cache/PersistingScopeObserver.java @@ -65,66 +65,65 @@ public final class PersistingScopeObserver extends ScopeObserverAdapter { private @NotNull SentryOptions options; private final @NotNull LazyEvaluator> breadcrumbsQueue = - new LazyEvaluator<>( - () -> { - final File cacheDir = ensureCacheDir(options, SCOPE_CACHE); - if (cacheDir == null) { - options.getLogger().log(INFO, "Cache dir is not set, cannot store in scope cache"); - return ObjectQueue.createEmpty(); - } - - QueueFile queueFile = null; - final File file = new File(cacheDir, BREADCRUMBS_FILENAME); - try { - try { - queueFile = - new QueueFile.Builder(file) - .size(options.getMaxBreadcrumbs()) - .synchronousWrites(false) - .build(); - } catch (IOException e) { - // if file is corrupted we simply delete it and try to create it again. We accept - // the trade - // off of losing breadcrumbs for ANRs that happened right before the app has - // received an - // update where the new format was introduced - file.delete(); - - queueFile = - new QueueFile.Builder(file) - .size(options.getMaxBreadcrumbs()) - .synchronousWrites(false) - .build(); + new LazyEvaluator<>(() -> { + final File cacheDir = ensureCacheDir(options, SCOPE_CACHE); + if (cacheDir == null) { + options.getLogger().log(INFO, "Cache dir is not set, cannot store in scope cache"); + return ObjectQueue.createEmpty(); + } + + QueueFile queueFile = null; + final File file = new File(cacheDir, BREADCRUMBS_FILENAME); + try { + try { + queueFile = + new QueueFile.Builder(file) + .size(options.getMaxBreadcrumbs()) + .synchronousWrites(false) + .build(); + } catch (IOException e) { + // if file is corrupted we simply delete it and try to create it again. We accept + // the trade + // off of losing breadcrumbs for ANRs that happened right before the app has + // received an + // update where the new format was introduced + file.delete(); + + queueFile = + new QueueFile.Builder(file) + .size(options.getMaxBreadcrumbs()) + .synchronousWrites(false) + .build(); + } + } catch (IOException e) { + options.getLogger().log(ERROR, "Failed to create breadcrumbs queue", e); + return ObjectQueue.createEmpty(); + } + return ObjectQueue.create( + queueFile, + new ObjectQueue.Converter() { + @Override + @Nullable + public Breadcrumb from(byte[] source) { + try (final Reader reader = + new BufferedReader( + new InputStreamReader(new ByteArrayInputStream(source), UTF_8))) { + return options.getSerializer().deserialize(reader, Breadcrumb.class); + } catch (Throwable e) { + options.getLogger().log(ERROR, e, "Error reading entity from scope cache"); + } + return null; + } + + @Override + public void toStream(Breadcrumb value, OutputStream sink) throws IOException { + try (final Writer writer = + new BufferedWriter(new OutputStreamWriter(sink, UTF_8))) { + options.getSerializer().serialize(value, writer); + } } - } catch (IOException e) { - options.getLogger().log(ERROR, "Failed to create breadcrumbs queue", e); - return ObjectQueue.createEmpty(); - } - return ObjectQueue.create( - queueFile, - new ObjectQueue.Converter() { - @Override - @Nullable - public Breadcrumb from(byte[] source) { - try (final Reader reader = - new BufferedReader( - new InputStreamReader(new ByteArrayInputStream(source), UTF_8))) { - return options.getSerializer().deserialize(reader, Breadcrumb.class); - } catch (Throwable e) { - options.getLogger().log(ERROR, e, "Error reading entity from scope cache"); - } - return null; - } - - @Override - public void toStream(Breadcrumb value, OutputStream sink) throws IOException { - try (final Writer writer = - new BufferedWriter(new OutputStreamWriter(sink, UTF_8))) { - options.getSerializer().serialize(value, writer); - } - } - }); - }); + }); + }); // Latest pending value per file (or DELETE_MARKER), coalesced until the next flush. private final @NotNull Map pendingWrites = new ConcurrentHashMap<>(); diff --git a/sentry/src/main/java/io/sentry/clientreport/AtomicClientReportStorage.java b/sentry/src/main/java/io/sentry/clientreport/AtomicClientReportStorage.java index fd1f9a9de99..41d36adf75b 100644 --- a/sentry/src/main/java/io/sentry/clientreport/AtomicClientReportStorage.java +++ b/sentry/src/main/java/io/sentry/clientreport/AtomicClientReportStorage.java @@ -17,21 +17,20 @@ final class AtomicClientReportStorage implements IClientReportStorage { private final @NotNull LazyEvaluator> lostEventCounts = - new LazyEvaluator<>( - () -> { - final Map modifyableEventCountsForInit = - new ConcurrentHashMap<>(); - - for (final DiscardReason discardReason : DiscardReason.values()) { - for (final DataCategory category : DataCategory.values()) { - modifyableEventCountsForInit.put( - new ClientReportKey(discardReason.getReason(), category.getCategory()), - new AtomicLong(0)); - } - } - - return Collections.unmodifiableMap(modifyableEventCountsForInit); - }); + new LazyEvaluator<>(() -> { + final Map modifyableEventCountsForInit = + new ConcurrentHashMap<>(); + + for (final DiscardReason discardReason : DiscardReason.values()) { + for (final DataCategory category : DataCategory.values()) { + modifyableEventCountsForInit.put( + new ClientReportKey(discardReason.getReason(), category.getCategory()), + new AtomicLong(0)); + } + } + + return Collections.unmodifiableMap(modifyableEventCountsForInit); + }); public AtomicClientReportStorage() {} diff --git a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileInputStream.java b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileInputStream.java index 3119b50b5ed..d32642180e6 100644 --- a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileInputStream.java +++ b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileInputStream.java @@ -86,12 +86,11 @@ public int read() throws IOException { // this is the only case, when the read() operation returns the byte value, and not the count // hence we need this special handling AtomicInteger result = new AtomicInteger(0); - spanManager.performIO( - () -> { - final int res = delegate.read(); - result.set(res); - return res != -1 ? 1 : 0; - }); + spanManager.performIO(() -> { + final int res = delegate.read(); + result.set(res); + return res != -1 ? 1 : 0; + }); return result.get(); } diff --git a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileOutputStream.java b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileOutputStream.java index 76f4cd68cba..15baad00d69 100644 --- a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileOutputStream.java +++ b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileOutputStream.java @@ -92,29 +92,26 @@ private static FileOutputStreamInitData init( @Override public void write(final int b) throws IOException { - spanManager.performIO( - () -> { - delegate.write(b); - return 1; - }); + spanManager.performIO(() -> { + delegate.write(b); + return 1; + }); } @Override public void write(final byte @NotNull [] b) throws IOException { - spanManager.performIO( - () -> { - delegate.write(b); - return b.length; - }); + spanManager.performIO(() -> { + delegate.write(b); + return b.length; + }); } @Override public void write(final byte @NotNull [] b, final int off, final int len) throws IOException { - spanManager.performIO( - () -> { - delegate.write(b, off, len); - return len; - }); + spanManager.performIO(() -> { + delegate.write(b, off, len); + return len; + }); } @Override diff --git a/sentry/src/main/java/io/sentry/internal/gestures/UiElement.java b/sentry/src/main/java/io/sentry/internal/gestures/UiElement.java index c675910800a..92846cd8d96 100644 --- a/sentry/src/main/java/io/sentry/internal/gestures/UiElement.java +++ b/sentry/src/main/java/io/sentry/internal/gestures/UiElement.java @@ -51,7 +51,7 @@ public UiElement( } @Override - public boolean equals(Object o) { + public boolean equals(final @Nullable Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UiElement uiElement = (UiElement) o; diff --git a/sentry/src/main/java/io/sentry/protocol/TransactionNameSource.java b/sentry/src/main/java/io/sentry/protocol/TransactionNameSource.java index ef2f3d0532d..9b19d7a980c 100644 --- a/sentry/src/main/java/io/sentry/protocol/TransactionNameSource.java +++ b/sentry/src/main/java/io/sentry/protocol/TransactionNameSource.java @@ -74,11 +74,11 @@ public enum TransactionNameSource { */ TASK -// /** -// * This is the default value set by Relay for legacy SDKs. -// */ -// UNKNOWN -; + // /** + // * This is the default value set by Relay for legacy SDKs. + // */ + // UNKNOWN + ; public String apiName() { return name().toLowerCase(Locale.ROOT); diff --git a/sentry/src/main/java/io/sentry/protocol/ViewHierarchyNode.java b/sentry/src/main/java/io/sentry/protocol/ViewHierarchyNode.java index 525d644fdc5..97fbea385c0 100644 --- a/sentry/src/main/java/io/sentry/protocol/ViewHierarchyNode.java +++ b/sentry/src/main/java/io/sentry/protocol/ViewHierarchyNode.java @@ -49,7 +49,7 @@ public void setRenderingSystem(String renderingSystem) { this.renderingSystem = renderingSystem; } - public void setType(String type) { + public void setType(final @Nullable String type) { this.type = type; } diff --git a/sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java b/sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java index c4d54c173ef..adf9f749d5c 100644 --- a/sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java +++ b/sentry/src/main/java/io/sentry/transport/AsyncHttpTransport.java @@ -254,7 +254,7 @@ public void run() { HintUtils.runIfHasType( hint, SubmissionResult.class, - (submissionResult) -> { + submissionResult -> { options .getLogger() .log( @@ -276,7 +276,7 @@ public void run() { HintUtils.runIfHasType( hint, DiskFlushNotification.class, - (diskFlushNotification) -> { + diskFlushNotification -> { if (diskFlushNotification.isFlushable(envelope.getHeader().getEventId())) { diskFlushNotification.markFlushed(); options.getLogger().log(SentryLevel.DEBUG, "Disk flush envelope fired"); @@ -326,7 +326,7 @@ public void run() { HintUtils.runIfHasType( hint, Retryable.class, - (retryable) -> { + retryable -> { retryable.setRetry(true); }, (hint, clazz) -> { @@ -344,7 +344,7 @@ public void run() { HintUtils.runIfHasType( hint, Retryable.class, - (retryable) -> { + retryable -> { retryable.setRetry(true); }, (hint, clazz) -> { diff --git a/sentry/src/main/java/io/sentry/transport/RateLimiter.java b/sentry/src/main/java/io/sentry/transport/RateLimiter.java index 9b15cb6fefe..35a543745d8 100644 --- a/sentry/src/main/java/io/sentry/transport/RateLimiter.java +++ b/sentry/src/main/java/io/sentry/transport/RateLimiter.java @@ -181,7 +181,7 @@ private void markHintWhenSendingFailed(final @NotNull Hint hint, final boolean r HintUtils.runIfHasType( hint, DiskFlushNotification.class, - (diskFlushNotification) -> { + diskFlushNotification -> { diskFlushNotification.markFlushed(); config.getLogger().log(SentryLevel.DEBUG, "Disk flush envelope fired due to rate limit"); }); diff --git a/sentry/src/main/java/io/sentry/util/HintUtils.java b/sentry/src/main/java/io/sentry/util/HintUtils.java index 4ccbce3c33f..ac44d3d68ae 100644 --- a/sentry/src/main/java/io/sentry/util/HintUtils.java +++ b/sentry/src/main/java/io/sentry/util/HintUtils.java @@ -85,7 +85,7 @@ public static void runIfDoesNotHaveType( runIfHasType( hint, clazz, - (ignored) -> {}, + ignored -> {}, (value, clazz2) -> { lambda.accept(value); }); diff --git a/sentry/src/main/java/io/sentry/util/Random.java b/sentry/src/main/java/io/sentry/util/Random.java index aec6063dcb2..d455fe91792 100644 --- a/sentry/src/main/java/io/sentry/util/Random.java +++ b/sentry/src/main/java/io/sentry/util/Random.java @@ -180,7 +180,6 @@ public int nextInt(int n) { } return r; } - ; /** * Returns the next pseudorandom, uniformly distributed {@code boolean} value from this random diff --git a/sentry/src/main/java/io/sentry/util/TracingUtils.java b/sentry/src/main/java/io/sentry/util/TracingUtils.java index 7f177ae70cd..c0991d3f2af 100644 --- a/sentry/src/main/java/io/sentry/util/TracingUtils.java +++ b/sentry/src/main/java/io/sentry/util/TracingUtils.java @@ -22,24 +22,20 @@ public final class TracingUtils { public static void startNewTrace(final @NotNull IScopes scopes) { - scopes.configureScope( - scope -> { - scope.withPropagationContext( - propagationContext -> { - scope.setPropagationContext(new PropagationContext()); - }); - }); + scopes.configureScope(scope -> { + scope.withPropagationContext(propagationContext -> { + scope.setPropagationContext(new PropagationContext()); + }); + }); } public static void setTrace( final @NotNull IScopes scopes, final @NotNull PropagationContext propagationContext) { - scopes.configureScope( - scope -> { - scope.withPropagationContext( - oldPropagationContext -> { - scope.setPropagationContext(propagationContext); - }); - }); + scopes.configureScope(scope -> { + scope.withPropagationContext(oldPropagationContext -> { + scope.setPropagationContext(propagationContext); + }); + }); } public static @Nullable TracingHeaders traceIfAllowed( @@ -80,7 +76,7 @@ public static void setTrace( // reads scope data such as the environment across current -> isolation -> global scopes.configureScope( ScopeType.COMBINED, - (scope) -> { + scope -> { returnValue.propagationContext = maybeUpdateBaggage(scope, sentryOptions); }); @@ -114,14 +110,13 @@ public static void setTrace( public static @NotNull PropagationContext maybeUpdateBaggage( final @NotNull IScope scope, final @NotNull SentryOptions sentryOptions) { - return scope.withPropagationContext( - propagationContext -> { - @NotNull Baggage baggage = propagationContext.getBaggage(); - if (baggage.isMutable()) { - baggage.setValuesFromScope(scope, sentryOptions); - baggage.freeze(); - } - }); + return scope.withPropagationContext(propagationContext -> { + @NotNull Baggage baggage = propagationContext.getBaggage(); + if (baggage.isMutable()) { + baggage.setValuesFromScope(scope, sentryOptions); + baggage.freeze(); + } + }); } private static boolean shouldAttachTracingHeaders( diff --git a/sentry/src/test/java/io/sentry/BaggageTest.kt b/sentry/src/test/java/io/sentry/BaggageTest.kt index 1a5ca8da418..15a4f4d7a14 100644 --- a/sentry/src/test/java/io/sentry/BaggageTest.kt +++ b/sentry/src/test/java/io/sentry/BaggageTest.kt @@ -134,7 +134,7 @@ class BaggageTest { Faker.instance() .random() .hex( - MAX_BAGGAGE_STRING_LENGTH - 16 - 12 - 1 + MAX_BAGGAGE_STRING_LENGTH - 16 - 12 - 1, ) // 8192 - "large-value=" - "otherValue=value" - "," val incomingHeaderValues = @@ -327,7 +327,7 @@ class BaggageTest { Faker.instance() .random() .hex( - MAX_BAGGAGE_STRING_LENGTH - 19 - 22 - 1 + MAX_BAGGAGE_STRING_LENGTH - 19 - 22 - 1, ) // 8192 - "sentry-mediumValue=" - "sentry-otherValue=kept" - "," val baggage = Baggage.fromHeader( @@ -352,7 +352,7 @@ class BaggageTest { Faker.instance() .random() .hex( - MAX_BAGGAGE_STRING_LENGTH - 19 - 22 + MAX_BAGGAGE_STRING_LENGTH - 19 - 22, ) // 8192 - "sentry-mediumValue=" - "sentry-otherValue=lost" val baggage = Baggage.fromHeader( @@ -642,7 +642,7 @@ class BaggageTest { listOf( "sentry-trace_id=${SentryId()},sentry-public_key=b, sentry-replay_id=${SentryId()}", "sentry-transaction=sentryTransaction, sentry-anewkey=abc", - ) + ), ) val unknown = baggage.unknown assertEquals(1, unknown.size) diff --git a/sentry/src/test/java/io/sentry/CheckInSerializationTest.kt b/sentry/src/test/java/io/sentry/CheckInSerializationTest.kt index 69c65a64c62..73f162df55b 100644 --- a/sentry/src/test/java/io/sentry/CheckInSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/CheckInSerializationTest.kt @@ -26,12 +26,12 @@ class CheckInSerializationTest { PropagationContext().also { it.traceId = SentryId("f382e3180c714217a81371f8c644aefe") it.spanId = SpanId("85694b9f567145a6") - } + }, ) .apply { data[SpanDataConvention.THREAD_ID] = 10 data[SpanDataConvention.THREAD_NAME] = "test" - } + }, ) duration = 12.3 environment = "env" diff --git a/sentry/src/test/java/io/sentry/CombinedContextsViewTest.kt b/sentry/src/test/java/io/sentry/CombinedContextsViewTest.kt index 0fb7d07c0a0..3a13ce7372c 100644 --- a/sentry/src/test/java/io/sentry/CombinedContextsViewTest.kt +++ b/sentry/src/test/java/io/sentry/CombinedContextsViewTest.kt @@ -411,10 +411,10 @@ class CombinedContextsViewTest { fun `prefers spring from current context`() { val combined = fixture.getSut() fixture.current.setSpring( - Spring().also { it.activeProfiles = listOf("current").toTypedArray() } + Spring().also { it.activeProfiles = listOf("current").toTypedArray() }, ) fixture.isolation.setSpring( - Spring().also { it.activeProfiles = listOf("isolation").toTypedArray() } + Spring().also { it.activeProfiles = listOf("isolation").toTypedArray() }, ) fixture.global.setSpring(Spring().also { it.activeProfiles = listOf("global").toTypedArray() }) @@ -425,7 +425,7 @@ class CombinedContextsViewTest { fun `uses isolation spring if current context does not have it`() { val combined = fixture.getSut() fixture.isolation.setSpring( - Spring().also { it.activeProfiles = listOf("isolation").toTypedArray() } + Spring().also { it.activeProfiles = listOf("isolation").toTypedArray() }, ) fixture.global.setSpring(Spring().also { it.activeProfiles = listOf("global").toTypedArray() }) diff --git a/sentry/src/test/java/io/sentry/CombinedScopeViewTest.kt b/sentry/src/test/java/io/sentry/CombinedScopeViewTest.kt index 9439306eec5..450711eadfd 100644 --- a/sentry/src/test/java/io/sentry/CombinedScopeViewTest.kt +++ b/sentry/src/test/java/io/sentry/CombinedScopeViewTest.kt @@ -187,7 +187,7 @@ class CombinedScopeViewTest { capturedHint = hint breadcrumb } - } + }, ) combined.addBreadcrumb( @@ -817,7 +817,7 @@ class CombinedScopeViewTest { assertEquals(ScopeType.ISOLATION, fixture.options.defaultScopeType) assertNull(fixture.scope.attachments.firstOrNull { it.filename == "someAttachment.png" }) assertNotNull( - fixture.isolationScope.attachments.firstOrNull { it.filename == "someAttachment.png" } + fixture.isolationScope.attachments.firstOrNull { it.filename == "someAttachment.png" }, ) assertNull(fixture.globalScope.attachments.firstOrNull { it.filename == "someAttachment.png" }) } @@ -835,10 +835,10 @@ class CombinedScopeViewTest { assertEquals(ScopeType.ISOLATION, fixture.options.defaultScopeType) assertNotNull(fixture.scope.attachments.firstOrNull { it.filename == "scopeAttachment.png" }) assertNull( - fixture.isolationScope.attachments.firstOrNull { it.filename == "isolationAttachment.png" } + fixture.isolationScope.attachments.firstOrNull { it.filename == "isolationAttachment.png" }, ) assertNotNull( - fixture.globalScope.attachments.firstOrNull { it.filename == "globalAttachment.png" } + fixture.globalScope.attachments.firstOrNull { it.filename == "globalAttachment.png" }, ) } diff --git a/sentry/src/test/java/io/sentry/DateUtilsTest.kt b/sentry/src/test/java/io/sentry/DateUtilsTest.kt index 97882198e62..b04d18ed197 100644 --- a/sentry/src/test/java/io/sentry/DateUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/DateUtilsTest.kt @@ -330,7 +330,7 @@ class DateUtilsTest { val threshold = 0.000001 if (diff > threshold) { throw RuntimeException( - "Expected $actual to be within $threshold of $expected but was $diff off" + "Expected $actual to be within $threshold of $expected but was $diff off", ) } } diff --git a/sentry/src/test/java/io/sentry/DeduplicateMultithreadedEventProcessorTest.kt b/sentry/src/test/java/io/sentry/DeduplicateMultithreadedEventProcessorTest.kt index eaa8f178612..e5279605e2a 100644 --- a/sentry/src/test/java/io/sentry/DeduplicateMultithreadedEventProcessorTest.kt +++ b/sentry/src/test/java/io/sentry/DeduplicateMultithreadedEventProcessorTest.kt @@ -24,7 +24,7 @@ class DeduplicateMultithreadedEventProcessorTest { this.type = type this.threadId = tid mechanism = Mechanism().apply { this.isHandled = isHandled } - } + }, ) } return event diff --git a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt index 18f08c8dcd6..ef055b9e8b2 100644 --- a/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/DefaultCompositePerformanceCollectorTest.kt @@ -237,14 +237,16 @@ class DefaultCompositePerformanceCollectorTest { val collector = fixture.getSut(null, null) assertNotNull(collector.getProperty>("snapshotCollectors")) assertTrue( - collector.getProperty>("snapshotCollectors").isEmpty() + collector.getProperty>("snapshotCollectors").isEmpty(), ) assertNotNull( - collector.getProperty>("continuousCollectors") + collector.getProperty>("continuousCollectors"), ) assertTrue( - collector.getProperty>("continuousCollectors").isEmpty() + collector + .getProperty>("continuousCollectors") + .isEmpty(), ) } diff --git a/sentry/src/test/java/io/sentry/DsnUtilTest.kt b/sentry/src/test/java/io/sentry/DsnUtilTest.kt index b3807c800ba..575b84eb090 100644 --- a/sentry/src/test/java/io/sentry/DsnUtilTest.kt +++ b/sentry/src/test/java/io/sentry/DsnUtilTest.kt @@ -45,7 +45,7 @@ class DsnUtilTest { DsnUtil.urlContainsDsnHost( optionsWithDsn("http://publicKey:secretKey@localhost:8080/path/id?sample.rate=0.1"), "localhost:8081", - ) + ), ) } @@ -55,7 +55,7 @@ class DsnUtilTest { DsnUtil.urlContainsDsnHost( optionsWithDsn("http://publicKey:secretKey@localhost:8080/path/id?sample.rate=0.1"), "localhost:8080", - ) + ), ) } diff --git a/sentry/src/test/java/io/sentry/DuplicateEventDetectionEventProcessorTest.kt b/sentry/src/test/java/io/sentry/DuplicateEventDetectionEventProcessorTest.kt index 23755678c4f..c1991a8a643 100644 --- a/sentry/src/test/java/io/sentry/DuplicateEventDetectionEventProcessorTest.kt +++ b/sentry/src/test/java/io/sentry/DuplicateEventDetectionEventProcessorTest.kt @@ -150,7 +150,7 @@ class DuplicateEventDetectionEventProcessorTest { val result = processor.process( SentryEvent( - ExceptionMechanismException(Mechanism(), event.throwable!!, Thread.currentThread()) + ExceptionMechanismException(Mechanism(), event.throwable!!, Thread.currentThread()), ), Hint(), ) @@ -162,7 +162,7 @@ class DuplicateEventDetectionEventProcessorTest { val processor = fixture.getSut() val sentryEvent = SentryEvent( - ExceptionMechanismException(Mechanism(), RuntimeException(), Thread.currentThread()) + ExceptionMechanismException(Mechanism(), RuntimeException(), Thread.currentThread()), ) processor.process(sentryEvent, Hint()) diff --git a/sentry/src/test/java/io/sentry/EnvelopeSenderTest.kt b/sentry/src/test/java/io/sentry/EnvelopeSenderTest.kt index dce7c3d5863..0f29d4f3020 100644 --- a/sentry/src/test/java/io/sentry/EnvelopeSenderTest.kt +++ b/sentry/src/test/java/io/sentry/EnvelopeSenderTest.kt @@ -73,7 +73,7 @@ class EnvelopeSenderTest { val sut = fixture.getSut() val testFile = File( - Files.createTempFile("send-cached-event-test", EnvelopeCache.SUFFIX_ENVELOPE_FILE).toUri() + Files.createTempFile("send-cached-event-test", EnvelopeCache.SUFFIX_ENVELOPE_FILE).toUri(), ) testFile.deleteOnExit() sut.processDirectory(testFile) @@ -90,7 +90,7 @@ class EnvelopeSenderTest { val sut = fixture.getSut() val testFile = File( - Files.createTempFile(tempDirectory, "send-cached-event-test", ".not-right-suffix").toUri() + Files.createTempFile(tempDirectory, "send-cached-event-test", ".not-right-suffix").toUri(), ) sut.processDirectory(File(tempDirectory.toUri())) testFile.deleteOnExit() @@ -116,7 +116,7 @@ class EnvelopeSenderTest { "send-cached-event-test", EnvelopeCache.SUFFIX_ENVELOPE_FILE, ) - .toUri() + .toUri(), ) testFile.deleteOnExit() sut.processDirectory(File(tempDirectory.toUri())) @@ -135,7 +135,7 @@ class EnvelopeSenderTest { "send-cached-event-test", EnvelopeCache.SUFFIX_ENVELOPE_FILE, ) - .toUri() + .toUri(), ) testFile.deleteOnExit() @@ -163,7 +163,7 @@ class EnvelopeSenderTest { "send-cached-event-test", EnvelopeCache.SUFFIX_ENVELOPE_FILE, ) - .toUri() + .toUri(), ) testFile.deleteOnExit() sut.processFile(testFile, Hint()) diff --git a/sentry/src/test/java/io/sentry/ExternalOptionsTest.kt b/sentry/src/test/java/io/sentry/ExternalOptionsTest.kt index 06fb29430b7..fda34716b99 100644 --- a/sentry/src/test/java/io/sentry/ExternalOptionsTest.kt +++ b/sentry/src/test/java/io/sentry/ExternalOptionsTest.kt @@ -38,7 +38,7 @@ class ExternalOptionsTest { "data-collection.graphql.variables=true", "data-collection.database-query-data=false", "data-collection.file-paths=false", - ) + ), ) { options -> val dataCollection = options.dataCollection @@ -91,7 +91,7 @@ class ExternalOptionsTest { "data-collection.graphql.variables=invalid", "data-collection.database-query-data=invalid", "data-collection.file-paths=invalid", - ) + ), ) { options -> assertThat(options.dataCollection!!.userInfo).isFalse() assertThat(options.dataCollection!!.graphql.document).isFalse() @@ -121,7 +121,7 @@ class ExternalOptionsTest { "proxy.port=9090", "proxy.user=some-user", "proxy.pass=some-pass", - ) + ), ) { assertNotNull(it.proxy) { proxy -> assertEquals("proxy.example.com", proxy.host) @@ -192,7 +192,7 @@ class ExternalOptionsTest { listOf( "in-app-includes=org.springframework,com.myapp", "in-app-excludes=org.jboss,com.microsoft", - ) + ), ) { assertEquals(listOf("org.springframework", "com.myapp"), it.inAppIncludes) assertEquals(listOf("org.jboss", "com.microsoft"), it.inAppExcludes) @@ -336,7 +336,7 @@ class ExternalOptionsTest { @Test fun `creates options with ignored errors for deduplication using external properties`() { withPropertiesFile( - "ignored-errors-for-deduplication=example.FirstException,example.SecondException" + "ignored-errors-for-deduplication=example.FirstException,example.SecondException", ) { options -> assertThat(options.ignoredErrorsForDeduplication) .containsExactly("example.FirstException", "example.SecondException") @@ -366,12 +366,12 @@ class ExternalOptionsTest { @Test fun `creates options with multiple bundle IDs using external properties`() { withPropertiesFile( - "bundle-ids=12ea7a02-46ac-44c0-a5bb-6d1fd9586411,faa3ab42-b1bd-4659-af8e-1682324aa744" + "bundle-ids=12ea7a02-46ac-44c0-a5bb-6d1fd9586411,faa3ab42-b1bd-4659-af8e-1682324aa744", ) { options -> assertTrue( options.bundleIds.containsAll( - listOf("12ea7a02-46ac-44c0-a5bb-6d1fd9586411", "faa3ab42-b1bd-4659-af8e-1682324aa744") - ) + listOf("12ea7a02-46ac-44c0-a5bb-6d1fd9586411", "faa3ab42-b1bd-4659-af8e-1682324aa744"), + ), ) } } @@ -420,7 +420,7 @@ class ExternalOptionsTest { fun `creates options with ignoredTransactions`() { withPropertiesFile("ignored-transactions=transactionName1,transactionName2") { options -> assertTrue( - options.ignoredTransactions!!.containsAll(listOf("transactionName1", "transactionName2")) + options.ignoredTransactions!!.containsAll(listOf("transactionName1", "transactionName2")), ) } } @@ -489,7 +489,7 @@ class ExternalOptionsTest { "cron.default-timezone=America/New_York", "cron.default-failure-issue-threshold=40", "cron.default-recovery-threshold=50", - ) + ), ) { options -> assertEquals(1L, options.cron?.defaultCheckinMargin) assertEquals(30L, options.cron?.defaultMaxRuntime) diff --git a/sentry/src/test/java/io/sentry/JsonObjectDeserializerTest.kt b/sentry/src/test/java/io/sentry/JsonObjectDeserializerTest.kt index f2bb1d79044..c6e10b4d96d 100644 --- a/sentry/src/test/java/io/sentry/JsonObjectDeserializerTest.kt +++ b/sentry/src/test/java/io/sentry/JsonObjectDeserializerTest.kt @@ -261,7 +261,7 @@ class JsonObjectDeserializerTest { "boolean" to true, "array" to listOf("a", "b", "c"), "object" to mapOf("key" to "value"), - ) + ), ) val actual = deserialize(json) diff --git a/sentry/src/test/java/io/sentry/JsonObjectReaderTest.kt b/sentry/src/test/java/io/sentry/JsonObjectReaderTest.kt index d4fd525a87b..42614d642fb 100644 --- a/sentry/src/test/java/io/sentry/JsonObjectReaderTest.kt +++ b/sentry/src/test/java/io/sentry/JsonObjectReaderTest.kt @@ -302,7 +302,7 @@ class JsonObjectReaderTest { fun `nextListOrNull keeps elements after a failing object followed by a primitive`() { val reader = getValuesReader( - "[{\"kind\": \"fail\", \"value\": \"bad\"}, \"oops\", {\"kind\": \"ok\", \"value\": \"two\"}]" + "[{\"kind\": \"fail\", \"value\": \"bad\"}, \"oops\", {\"kind\": \"ok\", \"value\": \"two\"}]", ) val deserializer = JsonDeserializer { objectReader, _ -> diff --git a/sentry/src/test/java/io/sentry/JsonSerializerTest.kt b/sentry/src/test/java/io/sentry/JsonSerializerTest.kt index f2113e3019f..1b33fba6b75 100644 --- a/sentry/src/test/java/io/sentry/JsonSerializerTest.kt +++ b/sentry/src/test/java/io/sentry/JsonSerializerTest.kt @@ -395,7 +395,7 @@ class JsonSerializerTest { val jsonEnvelope = FileFromResources.invoke("envelope_session.txt") val envelope = fixture.serializer.deserializeEnvelope( - ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)) + ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)), ) assertEnvelopeData(envelope) } @@ -405,7 +405,7 @@ class JsonSerializerTest { val jsonEnvelope = FileFromResources.invoke("envelope_session_sdkversion.txt") val envelope = fixture.serializer.deserializeEnvelope( - ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)) + ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)), )!! assertNotNull(envelope.header.sdkVersion) val sdkInfo = envelope.header.sdkVersion!! @@ -418,7 +418,7 @@ class JsonSerializerTest { assertTrue( sdkInfo.packageSet.any { it.name == "io.sentry:maven:sentry-android-core" && it.version == "4.5.6" - } + }, ) } @@ -431,7 +431,7 @@ class JsonSerializerTest { // reversing it so we can assert the values val envelope = fixture.serializer.deserializeEnvelope( - ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)) + ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)), ) assertEnvelopeData(envelope) } @@ -450,7 +450,7 @@ class JsonSerializerTest { // reversing it so we can assert the values val envelope = fixture.serializer.deserializeEnvelope( - ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)) + ByteArrayInputStream(jsonEnvelope.toByteArray(Charsets.UTF_8)), )!! assertNotNull(envelope.header.sdkVersion) @@ -628,7 +628,7 @@ class JsonSerializerTest { ProfileMeasurement.UNIT_PERCENT, listOf(ProfileMeasurementValue(5, 10.52, measurementNow)), ), - ) + ), ) profilingTraceData.sampledProfile = "sampled profile in base 64" @@ -685,7 +685,7 @@ class JsonSerializerTest { "value" to 60.1, "elapsed_since_start_ns" to "1", "timestamp" to measurementNowSeconds, - ) + ), ), ), ProfileMeasurement.ID_MEMORY_FOOTPRINT to @@ -697,7 +697,7 @@ class JsonSerializerTest { "value" to 100.52, "elapsed_since_start_ns" to "2", "timestamp" to measurementNowSeconds, - ) + ), ), ), ProfileMeasurement.ID_MEMORY_NATIVE_FOOTPRINT to @@ -709,7 +709,7 @@ class JsonSerializerTest { "value" to 104.52, "elapsed_since_start_ns" to "3", "timestamp" to measurementNowSeconds, - ) + ), ), ), ProfileMeasurement.ID_CPU_USAGE to @@ -721,7 +721,7 @@ class JsonSerializerTest { "value" to 10.52, "elapsed_since_start_ns" to "5", "timestamp" to measurementNowSeconds, - ) + ), ), ), ), @@ -999,7 +999,7 @@ class JsonSerializerTest { ProfileMeasurement.UNIT_PERCENT, listOf(ProfileMeasurementValue(5, 10.52, measurementNow)), ), - ) + ), ) val actual = serializeToString(profileChunk) @@ -1030,7 +1030,7 @@ class JsonSerializerTest { "value" to 60.1, "elapsed_since_start_ns" to "1", "timestamp" to measurementNowSeconds, - ) + ), ), ), ProfileMeasurement.ID_MEMORY_FOOTPRINT to @@ -1042,7 +1042,7 @@ class JsonSerializerTest { "value" to 100.52, "elapsed_since_start_ns" to "2", "timestamp" to measurementNowSeconds, - ) + ), ), ), ProfileMeasurement.ID_MEMORY_NATIVE_FOOTPRINT to @@ -1054,7 +1054,7 @@ class JsonSerializerTest { "value" to 104.52, "elapsed_since_start_ns" to "3", "timestamp" to measurementNowSeconds, - ) + ), ), ), ProfileMeasurement.ID_CPU_USAGE to @@ -1066,7 +1066,7 @@ class JsonSerializerTest { "value" to 10.52, "elapsed_since_start_ns" to "5", "timestamp" to measurementNowSeconds, - ) + ), ), ), ), @@ -1207,7 +1207,7 @@ class JsonSerializerTest { val jsonTrace = (element["contexts"] as Map<*, *>)["trace"] as Map<*, *> assertEquals("dataValue", (jsonTrace["data"] as Map<*, *>)["dataKey"] as String) assertTrue( - (jsonTrace["data"] as Map<*, *>)["flag.evaluation.transaction-feature-flag"] as Boolean + (jsonTrace["data"] as Map<*, *>)["flag.evaluation.transaction-feature-flag"] as Boolean, ) assertNotNull(jsonTrace["trace_id"] as String) assertNotNull(jsonTrace["span_id"] as String) @@ -1590,7 +1590,7 @@ class JsonSerializerTest { listOf( Breadcrumb(timestamp).apply { message = "test" }, Breadcrumb(timestamp).apply { category = "navigation" }, - ) + ), ) val deserializedCollection = @@ -1714,7 +1714,7 @@ class JsonSerializerTest { private fun generateEmptySentryEvent(date: Date = Date()): SentryEvent = SentryEvent(date) private fun createSessionMockData( - sessionId: String = "c81d4e2e-bcf2-11e6-869b-7df92533d2db" + sessionId: String = "c81d4e2e-bcf2-11e6-869b-7df92533d2db", ): Session = Session( Session.State.Ok, diff --git a/sentry/src/test/java/io/sentry/JsonUnknownSerializationTest.kt b/sentry/src/test/java/io/sentry/JsonUnknownSerializationTest.kt index 6231bd2ecfb..ca698f1b909 100644 --- a/sentry/src/test/java/io/sentry/JsonUnknownSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/JsonUnknownSerializationTest.kt @@ -72,7 +72,7 @@ class JsonUnknownSerializationTest( SentryPackage( "b59a1949-9950-4203-b394-ddd8d02c9633", "3d7790f3-7f32-43f7-b82f-9f5bc85205a8", - ) + ), ) val sentryRuntime = givenJsonUnknown(SentryRuntime()) val sentrySpan = givenJsonUnknown(SentrySpanSerializationTest.Fixture().getSut()) @@ -85,7 +85,10 @@ class JsonUnknownSerializationTest( val session = givenJsonUnknown(SessionSerializationTest.Fixture().getSut()) val skdVersion = givenJsonUnknown( - SdkVersion("3e934135-3f2b-49bc-8756-9f025b55143e", "3e31738e-4106-42d0-8be2-4a3a1bc648d3") + SdkVersion( + "3e934135-3f2b-49bc-8756-9f025b55143e", + "3e31738e-4106-42d0-8be2-4a3a1bc648d3", + ), ) val spanContext = givenJsonUnknown(SpanContext("c2fb8fee2e2b49758bcb67cda0f713c7")) val traceContext = givenJsonUnknown(TraceContextSerializationTest.Fixture().getSut()) diff --git a/sentry/src/test/java/io/sentry/NoOpConnectionStatusProviderTest.kt b/sentry/src/test/java/io/sentry/NoOpConnectionStatusProviderTest.kt index b412d7c27ed..aad1b68e1dd 100644 --- a/sentry/src/test/java/io/sentry/NoOpConnectionStatusProviderTest.kt +++ b/sentry/src/test/java/io/sentry/NoOpConnectionStatusProviderTest.kt @@ -23,7 +23,7 @@ class NoOpConnectionStatusProviderTest { fun `adding a listener is a no-op and returns false`() { val result = provider.addConnectionStatusObserver( - mock() + mock(), ) assertFalse(result) } @@ -31,7 +31,7 @@ class NoOpConnectionStatusProviderTest { @Test fun `removing a listener is a no-op`() { provider.addConnectionStatusObserver( - mock() + mock(), ) } } diff --git a/sentry/src/test/java/io/sentry/OptionsContainerTest.kt b/sentry/src/test/java/io/sentry/OptionsContainerTest.kt index 7d168e2660a..716b1609189 100644 --- a/sentry/src/test/java/io/sentry/OptionsContainerTest.kt +++ b/sentry/src/test/java/io/sentry/OptionsContainerTest.kt @@ -7,7 +7,7 @@ class OptionsContainerTest { @Test fun `When passing class to OptionsContainer, instance is created based on the type`() { assertTrue( - (OptionsContainer.create(SentryOptions::class.java)).createInstance() is SentryOptions + (OptionsContainer.create(SentryOptions::class.java)).createInstance() is SentryOptions, ) } } diff --git a/sentry/src/test/java/io/sentry/OutboxSenderTest.kt b/sentry/src/test/java/io/sentry/OutboxSenderTest.kt index f133bbb5a61..b817d28c503 100644 --- a/sentry/src/test/java/io/sentry/OutboxSenderTest.kt +++ b/sentry/src/test/java/io/sentry/OutboxSenderTest.kt @@ -17,7 +17,6 @@ import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue import org.mockito.kotlin.any -import org.mockito.kotlin.anyVararg import org.mockito.kotlin.argWhere import org.mockito.kotlin.check import org.mockito.kotlin.eq @@ -311,7 +310,13 @@ class OutboxSenderTest { sut.processEnvelopeFile(path, hints) // Additionally make sure we have no errors logged - verify(fixture.logger).log(eq(SentryLevel.ERROR), any(), anyVararg()) + verify(fixture.logger) + .log( + eq(SentryLevel.ERROR), + eq("Item %d of type %s returned null by the parser."), + any(), + any(), + ) verify(fixture.scopes, never()).captureEvent(any()) assertFalse(File(path).exists()) } @@ -329,7 +334,13 @@ class OutboxSenderTest { sut.processEnvelopeFile(path, hints) // Additionally make sure we have no errors logged - verify(fixture.logger).log(eq(SentryLevel.ERROR), any(), anyVararg()) + verify(fixture.logger) + .log( + eq(SentryLevel.ERROR), + eq("Item %d of type %s returned null by the parser."), + any(), + any(), + ) verify(fixture.scopes, never()).captureEvent(any()) assertFalse(File(path).exists()) } diff --git a/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt b/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt index 4fb74690c37..f9a3097ec7d 100644 --- a/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt +++ b/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt @@ -13,7 +13,6 @@ import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.mockito.kotlin.any -import org.mockito.kotlin.anyVararg import org.mockito.kotlin.argThat import org.mockito.kotlin.mock import org.mockito.kotlin.never @@ -119,7 +118,7 @@ class PreviousSessionFinalizerTest { val sessionCreationToFinalizerInterval = 20000 val sessionCreationTimestamp = DateUtils.getDateTime( - DateUtils.getCurrentDateTime().time - sessionCreationToFinalizerInterval + DateUtils.getCurrentDateTime().time - sessionCreationToFinalizerInterval, ) val finalizer = @@ -155,7 +154,7 @@ class PreviousSessionFinalizerTest { captureTimestamp - session.started!!.time > sessionCreationToFinalizerInterval && session.timestamp!!.time != sessionCreationTimestamp.time && captureTimestamp - session.timestamp!!.time < 1000 - } + }, ) } @@ -178,7 +177,7 @@ class PreviousSessionFinalizerTest { argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && session.timestamp!! == abnormalEndDate - } + }, ) } @@ -197,7 +196,7 @@ class PreviousSessionFinalizerTest { argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && session.status == Crashed - } + }, ) } @@ -220,7 +219,7 @@ class PreviousSessionFinalizerTest { session.release == "io.sentry.sample@1.0" && session.status == Session.State.Unhandled && session.hasNonTerminatingUnhandledError() - } + }, ) } @@ -242,7 +241,7 @@ class PreviousSessionFinalizerTest { argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && session.status == Crashed - } + }, ) } @@ -278,10 +277,9 @@ class PreviousSessionFinalizerTest { any(), argThat { startsWith( - "Timed out waiting to flush previous session to its own file in session finalizer." + "Timed out waiting to flush previous session to its own file in session finalizer.", ) }, - anyVararg(), ) verify(fixture.scopes, never()).captureEnvelope(any()) } diff --git a/sentry/src/test/java/io/sentry/ScopeTest.kt b/sentry/src/test/java/io/sentry/ScopeTest.kt index b768cf41cc9..536f869ebc8 100644 --- a/sentry/src/test/java/io/sentry/ScopeTest.kt +++ b/sentry/src/test/java/io/sentry/ScopeTest.kt @@ -211,7 +211,7 @@ class ScopeTest { request.method = "post" scope.setTransaction( - SentryTracer(TransactionContext("newTransaction", "op"), NoOpScopes.getInstance()) + SentryTracer(TransactionContext("newTransaction", "op"), NoOpScopes.getInstance()), ) // because you can only set a new list to scope @@ -1187,7 +1187,7 @@ class ScopeTest { Scope(options).apply { screen = "MainActivity" } verify(observer) .setContexts( - check { contexts -> assertEquals("MainActivity", contexts.app?.viewNames?.first()) } + check { contexts -> assertEquals("MainActivity", contexts.app?.viewNames?.first()) }, ) } @@ -1325,7 +1325,7 @@ class ScopeTest { SentryAttributes.of( SentryAttribute.stringAttribute("key1", "value1"), SentryAttribute.integerAttribute("key2", 42), - ) + ), ) val attrs = scope.attributes assertEquals(2, attrs.size) diff --git a/sentry/src/test/java/io/sentry/ScopesTest.kt b/sentry/src/test/java/io/sentry/ScopesTest.kt index 05647d544b5..15e1d82941d 100644 --- a/sentry/src/test/java/io/sentry/ScopesTest.kt +++ b/sentry/src/test/java/io/sentry/ScopesTest.kt @@ -1510,7 +1510,7 @@ class ScopesTest { anyOrNull(), anyOrNull(), anyOrNull(), - ) + ), ) .thenReturn(SentryId()) @@ -2248,7 +2248,7 @@ class ScopesTest { scopes.continueTrace( "$traceId-$parentSpanId-1", listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET", ), ) @@ -2270,7 +2270,7 @@ class ScopesTest { scopes.continueTrace( "$traceId-$parentSpanId", listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET", ), ) @@ -2297,7 +2297,7 @@ class ScopesTest { scopes.continueTrace( "invalid", listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET", ), ) @@ -2321,7 +2321,7 @@ class ScopesTest { scopes.continueTrace( "$traceId-$parentSpanId-1", listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET", ), ) @@ -2346,7 +2346,7 @@ class ScopesTest { scopes.continueTrace( "invalid", listOf( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET", ), ) @@ -2500,7 +2500,7 @@ class ScopesTest { .log( eq(SentryLevel.WARNING), eq( - "Continuous Profiling is not enabled. Set profilesSampleRate and profilesSampler to null to enable it." + "Continuous Profiling is not enabled. Set profilesSampleRate and profilesSampler to null to enable it.", ), ) } @@ -2554,7 +2554,7 @@ class ScopesTest { .log( eq(SentryLevel.WARNING), eq( - "Continuous Profiling is not enabled. Set profilesSampleRate and profilesSampler to null to enable it." + "Continuous Profiling is not enabled. Set profilesSampleRate and profilesSampler to null to enable it.", ), ) } @@ -2878,7 +2878,7 @@ class ScopesTest { SentryAttribute.named("namedintattr", 18), SentryAttribute.named("nameddoubleattr", 4.9), SentryAttribute.named("namedarrayattr", listOf("x", "y")), - ) + ), ), "log message", ) @@ -3623,7 +3623,7 @@ class ScopesTest { SentryAttribute.named("namedintattr", 18), SentryAttribute.named("nameddoubleattr", 4.9), SentryAttribute.named("namedarrayattr", listOf("x", "y")), - ) + ), ), ) @@ -3802,7 +3802,7 @@ class ScopesTest { SentryAttribute.named("namedintattr", 18), SentryAttribute.named("nameddoubleattr", 4.9), SentryAttribute.named("namedarrayattr", listOf("x", "y")), - ) + ), ), ) @@ -3981,7 +3981,7 @@ class ScopesTest { SentryAttribute.named("namedintattr", 18), SentryAttribute.named("nameddoubleattr", 4.9), SentryAttribute.named("namedarrayattr", listOf("x", "y")), - ) + ), ), ) @@ -4454,7 +4454,7 @@ class ScopesTest { private val dsnTest = "https://key@sentry.io/proj" private fun generateScopes( - optionsConfiguration: Sentry.OptionsConfiguration? = null + optionsConfiguration: Sentry.OptionsConfiguration? = null, ): IScopes { val options = SentryOptions().apply { @@ -4468,7 +4468,7 @@ class ScopesTest { } private fun getEnabledScopes( - optionsConfiguration: Sentry.OptionsConfiguration? = null + optionsConfiguration: Sentry.OptionsConfiguration? = null, ): Triple { val logger = mock() diff --git a/sentry/src/test/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegrationTest.kt b/sentry/src/test/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegrationTest.kt index 677f32441e4..fa45da5cad1 100644 --- a/sentry/src/test/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegrationTest.kt +++ b/sentry/src/test/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegrationTest.kt @@ -101,7 +101,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { .log( eq(SentryLevel.ERROR), eq( - "Failed to call the executor. Cached events will not be sent. Did you call Sentry.close()?" + "Failed to call the executor. Cached events will not be sent. Did you call Sentry.close()?", ), any(), ) diff --git a/sentry/src/test/java/io/sentry/SentryClientTest.kt b/sentry/src/test/java/io/sentry/SentryClientTest.kt index c95e116fe1c..c1e96f842b7 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTest.kt @@ -461,7 +461,7 @@ class SentryClientTest { scope.addEventProcessor( object : EventProcessor { override fun process(event: SentryLogEvent): SentryLogEvent? = null - } + }, ) val sut = fixture.getSut() @@ -624,7 +624,7 @@ class SentryClientTest { scope.addEventProcessor( object : EventProcessor { override fun process(event: SentryMetricsEvent, hint: Hint): SentryMetricsEvent? = null - } + }, ) val sut = fixture.getSut() @@ -1524,7 +1524,7 @@ class SentryClientTest { transaction.spans.removeIf { it.description != "span2" } return transaction } - } + }, ) fixture.getSut().captureTransaction(transaction, scope, null) @@ -2184,7 +2184,7 @@ class SentryClientTest { assertEquals(1, images.size) assertEquals(DebugImage.PROGUARD, images[0].type) assertEquals("current-uuid", images[0].uuid) - } + }, ) } @@ -2198,7 +2198,7 @@ class SentryClientTest { DebugImage().apply { type = DebugImage.PROGUARD uuid = "previous-uuid" - } + }, ) } @@ -2214,7 +2214,7 @@ class SentryClientTest { assertEquals(1, images.size) assertEquals(DebugImage.PROGUARD, images[0].type) assertEquals("previous-uuid", images[0].uuid) - } + }, ) } @@ -2465,7 +2465,7 @@ class SentryClientTest { } override fun registerSegmentName(segmentName: String) {} - } + }, ) val sut = fixture.getSut() val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) @@ -2482,7 +2482,7 @@ class SentryClientTest { override fun registerSegmentName(segmentName: String) { registeredSegmentName = segmentName } - } + }, ) val sut = fixture.getSut() val sentryTracer = @@ -3059,7 +3059,7 @@ class SentryClientTest { override fun process(transaction: SentryTransaction, hint: Hint): SentryTransaction? { return transaction } - } + }, ) } @@ -3083,7 +3083,7 @@ class SentryClientTest { override fun process(transaction: SentryTransaction, hint: Hint): SentryTransaction? { return transaction } - } + }, ) } @@ -3148,7 +3148,7 @@ class SentryClientTest { hint.addAttachment(fixture.attachment3) return transaction } - } + }, ) } @@ -3182,7 +3182,7 @@ class SentryClientTest { hint.replaceAttachments(listOf(fixture.attachment3)) return transaction } - } + }, ) } @@ -3761,7 +3761,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3778,7 +3778,7 @@ class SentryClientTest { terminated = isTerminating return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3786,7 +3786,7 @@ class SentryClientTest { SentryEvent().apply { exceptions = listOf(SentryException().apply { mechanism = Mechanism().apply { isHandled = false } }) - } + }, ) assertTrue(terminated == true) } @@ -3797,7 +3797,7 @@ class SentryClientTest { fixture.sentryOptions.setReplayController( object : ReplayController by NoOpReplayController.getInstance() { override fun captureReplay(isTerminating: Boolean?): SentryId = replayId - } + }, ) val sut = fixture.getSut() @@ -3858,7 +3858,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3881,7 +3881,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3922,7 +3922,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) fixture.sentryOptions.sessionReplay.beforeErrorSampling = SentryReplayOptions.BeforeErrorSamplingCallback { _, _ -> @@ -3943,7 +3943,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) fixture.sentryOptions.sessionReplay.beforeErrorSampling = SentryReplayOptions.BeforeErrorSamplingCallback { _, _ -> @@ -3964,7 +3964,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -3991,7 +3991,7 @@ class SentryClientTest { SentryEvent().apply { exceptions = listOf( - SentryException().apply { mechanism = Mechanism().apply { isHandled = handled } } + SentryException().apply { mechanism = Mechanism().apply { isHandled = handled } }, ) } } @@ -4054,7 +4054,7 @@ class SentryClientTest { fixture.sentryOptions.setReplayController( object : ReplayController by NoOpReplayController.getInstance() { override fun captureReplay(isTerminating: Boolean?): SentryId = SentryId.EMPTY_ID - } + }, ) fixture.sentryOptions.sessionReplay.beforeErrorSampling = SentryReplayOptions.BeforeErrorSamplingCallback { event, hint -> @@ -4080,7 +4080,7 @@ class SentryClientTest { called = true return SentryId.EMPTY_ID } - } + }, ) val sut = fixture.getSut() @@ -4359,7 +4359,7 @@ class SentryClientTest { assertClientReport( fixture.sentryOptions.clientReportRecorder, listOf( - DiscardedEvent(DiscardReason.CALLBACK_ERROR.reason, DataCategory.Feedback.category, 1) + DiscardedEvent(DiscardReason.CALLBACK_ERROR.reason, DataCategory.Feedback.category, 1), ), ) @@ -4378,7 +4378,7 @@ class SentryClientTest { assertClientReport( fixture.sentryOptions.clientReportRecorder, listOf( - DiscardedEvent(DiscardReason.EVENT_PROCESSOR.reason, DataCategory.Feedback.category, 1) + DiscardedEvent(DiscardReason.EVENT_PROCESSOR.reason, DataCategory.Feedback.category, 1), ), ) @@ -4407,7 +4407,7 @@ class SentryClientTest { assertClientReport( fixture.sentryOptions.clientReportRecorder, listOf( - DiscardedEvent(DiscardReason.CALLBACK_ERROR.reason, DataCategory.Feedback.category, 1) + DiscardedEvent(DiscardReason.CALLBACK_ERROR.reason, DataCategory.Feedback.category, 1), ), ) verify(onDiscard).execute(DiscardReason.CALLBACK_ERROR, DataCategory.Feedback, 1) @@ -4518,7 +4518,7 @@ class SentryClientTest { val bytesTooBig = ByteArray((fixture.maxAttachmentSize + 1).toInt()) { 0 } addAttachment( - Attachment(bytesTooBig, "will_get_dropped.txt", "application/octet-stream", true) + Attachment(bytesTooBig, "will_get_dropped.txt", "application/octet-stream", true), ) } } @@ -4622,7 +4622,7 @@ class SentryClientTest { val attachmentItemTooBig = attachmentItems.last() assertFailsWith( "Getting data from attachment should" + - "throw an exception, because the attachment is too big." + "throw an exception, because the attachment is too big.", ) { attachmentItemTooBig.data } @@ -4654,7 +4654,7 @@ class SentryClientTest { val profilingTraceItem = actual.items.firstOrNull { item -> item.header.type == SentryItemType.ProfileChunk } assertNotNull(profilingTraceItem?.data) - } + }, ) } diff --git a/sentry/src/test/java/io/sentry/SentryClientTransactionProfileTest.kt b/sentry/src/test/java/io/sentry/SentryClientTransactionProfileTest.kt index 24761837516..b176ec0328e 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTransactionProfileTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTransactionProfileTest.kt @@ -72,7 +72,7 @@ class SentryClientTransactionProfileTest( ) if (hasProfile) { expected.add( - DiscardedEvent(DiscardReason.CALLBACK_ERROR.reason, DataCategory.Profile.category, 1) + DiscardedEvent(DiscardReason.CALLBACK_ERROR.reason, DataCategory.Profile.category, 1), ) verify(onDiscard).execute(DiscardReason.CALLBACK_ERROR, DataCategory.Profile, 1) } diff --git a/sentry/src/test/java/io/sentry/SentryEndToEndTest.kt b/sentry/src/test/java/io/sentry/SentryEndToEndTest.kt index 742f4462b2b..3c627902428 100644 --- a/sentry/src/test/java/io/sentry/SentryEndToEndTest.kt +++ b/sentry/src/test/java/io/sentry/SentryEndToEndTest.kt @@ -41,7 +41,7 @@ class SentryEndToEndTest { addBreadcrumb(Breadcrumb("Processed by the event processor")) } } - } + }, ) } @@ -62,11 +62,11 @@ class SentryEndToEndTest { message = Message().apply { message = "Detailed event" } fingerprints = listOf("NewClientDebug") level = SentryLevel.DEBUG - } + }, ) repeat(10) { i -> Sentry.captureEvent( - SentryEvent().apply { message = Message().apply { message = "event $i" } } + SentryEvent().apply { message = Message().apply { message = "event $i" } }, ) } val transaction = Sentry.startTransaction("transaction name", "op") diff --git a/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt b/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt index 9f006ed94e9..561d12a26c2 100644 --- a/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt +++ b/sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt @@ -193,7 +193,7 @@ class SentryEnvelopeItemTest { assertFailsWith( "Reading the attachment ${attachment.pathname} failed, because the file located at " + - "the path is not a file." + "the path is not a file.", ) { item.data } @@ -218,7 +218,7 @@ class SentryEnvelopeItemTest { ) assertFailsWith( - "Reading the attachment ${attachment.pathname} failed, " + "because can't read the file." + "Reading the attachment ${attachment.pathname} failed, " + "because can't read the file.", ) { item.data } @@ -272,7 +272,7 @@ class SentryEnvelopeItemTest { assertFailsWith( "Couldn't attach the attachment ${attachment.filename}.\n" + - "Please check that either bytes or a path is set." + "Please check that either bytes or a path is set.", ) { item.data } @@ -385,7 +385,7 @@ class SentryEnvelopeItemTest { assertFailsWith( "Couldn't attach the attachment ${attachment.filename}.\n" + - "Please check that either bytes or a path is set." + "Please check that either bytes or a path is set.", ) { item.data } @@ -427,7 +427,7 @@ class SentryEnvelopeItemTest { val profilingTraceData = mock { whenever(it.traceFile).thenReturn(file) } assertFailsWith( - "Dropping profiling trace data, because the file ${file.path} doesn't exists" + "Dropping profiling trace data, because the file ${file.path} doesn't exists", ) { SentryEnvelopeItem.fromProfilingTrace(profilingTraceData, fixture.maxAttachmentSize, mock()) .data @@ -445,7 +445,7 @@ class SentryEnvelopeItemTest { file.writeBytes(fixture.bytes) file.setReadable(false) assertFailsWith( - "Dropping profiling trace data, because the file ${file.path} doesn't exists" + "Dropping profiling trace data, because the file ${file.path} doesn't exists", ) { SentryEnvelopeItem.fromProfilingTrace(profilingTraceData, fixture.maxAttachmentSize, mock()) .data @@ -538,7 +538,7 @@ class SentryEnvelopeItemTest { } assertFailsWith( - "Dropping profiling trace data, because the file ${file.path} doesn't exists" + "Dropping profiling trace data, because the file ${file.path} doesn't exists", ) { SentryEnvelopeItem.fromProfileChunk(profileChunk, mock()).data } @@ -555,7 +555,7 @@ class SentryEnvelopeItemTest { file.writeBytes(fixture.bytes) file.setReadable(false) assertFailsWith( - "Dropping profiling trace data, because the file ${file.path} doesn't exists" + "Dropping profiling trace data, because the file ${file.path} doesn't exists", ) { SentryEnvelopeItem.fromProfileChunk(profileChunk, mock()).data } diff --git a/sentry/src/test/java/io/sentry/SentryEventTest.kt b/sentry/src/test/java/io/sentry/SentryEventTest.kt index 70514a6b72d..cf113611ba5 100644 --- a/sentry/src/test/java/io/sentry/SentryEventTest.kt +++ b/sentry/src/test/java/io/sentry/SentryEventTest.kt @@ -27,7 +27,7 @@ class SentryEventTest { assertTrue( Instant.now() .plus(1, ChronoUnit.HOURS) - .isAfter(Instant.parse(DateUtils.getTimestamp(SentryEvent().timestamp))) + .isAfter(Instant.parse(DateUtils.getTimestamp(SentryEvent().timestamp))), ) @Test @@ -35,7 +35,7 @@ class SentryEventTest { assertTrue( Instant.now() .minus(1, ChronoUnit.HOURS) - .isBefore(Instant.parse(DateUtils.getTimestamp(SentryEvent().timestamp))) + .isBefore(Instant.parse(DateUtils.getTimestamp(SentryEvent().timestamp))), ) @Test @@ -201,7 +201,7 @@ class SentryEventTest { try { event.set( JsonSerializer(SentryOptions()) - .deserialize(StringReader(json), SentryEvent::class.java) + .deserialize(StringReader(json), SentryEvent::class.java), ) } catch (throwable: Throwable) { error.set(throwable) diff --git a/sentry/src/test/java/io/sentry/SentryExceptionFactoryTest.kt b/sentry/src/test/java/io/sentry/SentryExceptionFactoryTest.kt index 55472ae6738..191d681c219 100644 --- a/sentry/src/test/java/io/sentry/SentryExceptionFactoryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryExceptionFactoryTest.kt @@ -19,7 +19,7 @@ import org.mockito.kotlin.whenever class SentryExceptionFactoryTest { private class Fixture { fun getSut( - stackTraceFactory: SentryStackTraceFactory = SentryStackTraceFactory(SentryOptions()) + stackTraceFactory: SentryStackTraceFactory = SentryStackTraceFactory(SentryOptions()), ): SentryExceptionFactory = SentryExceptionFactory(stackTraceFactory) } @@ -155,7 +155,7 @@ class SentryExceptionFactoryTest { assertTrue( queue.first.stacktrace!!.frames!!.any { it.module != null && it.module!!.startsWith("io.sentry") - } + }, ) } @@ -183,7 +183,7 @@ class SentryExceptionFactoryTest { lineno = 777 module = "io.sentry.samples.MainActivity" function = "run" - } + }, ) } } diff --git a/sentry/src/test/java/io/sentry/SentryOptionsTest.kt b/sentry/src/test/java/io/sentry/SentryOptionsTest.kt index be4fd499c09..222f5a21fd5 100644 --- a/sentry/src/test/java/io/sentry/SentryOptionsTest.kt +++ b/sentry/src/test/java/io/sentry/SentryOptionsTest.kt @@ -344,7 +344,7 @@ class SentryOptionsTest { assertTrue( sdkVersion.packageSet.any { it.name == "maven:io.sentry:sentry" && it.version == BuildConfig.VERSION_NAME - } + }, ) } @@ -563,7 +563,7 @@ class SentryOptionsTest { externalOptions.shutdownTimeoutMillis = 1499L externalOptions.sessionFlushTimeoutMillis = 1498L externalOptions.bundleIds.addAll( - listOf("12ea7a02-46ac-44c0-a5bb-6d1fd9586411 ", " faa3ab42-b1bd-4659-af8e-1682324aa744") + listOf("12ea7a02-46ac-44c0-a5bb-6d1fd9586411 ", " faa3ab42-b1bd-4659-af8e-1682324aa744"), ) externalOptions.isEnabled = false externalOptions.isEnablePrettySerializationOutput = false @@ -852,11 +852,11 @@ class SentryOptionsTest { override fun getConnectionType(): String? = null override fun addConnectionStatusObserver( - observer: IConnectionStatusProvider.IConnectionStatusObserver + observer: IConnectionStatusProvider.IConnectionStatusObserver, ) = false override fun removeConnectionStatusObserver( - observer: IConnectionStatusProvider.IConnectionStatusObserver + observer: IConnectionStatusProvider.IConnectionStatusObserver, ) { // no-op } diff --git a/sentry/src/test/java/io/sentry/SentryStackTraceFactoryTest.kt b/sentry/src/test/java/io/sentry/SentryStackTraceFactoryTest.kt index d93d7f6f027..507181eeaaa 100644 --- a/sentry/src/test/java/io/sentry/SentryStackTraceFactoryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryStackTraceFactoryTest.kt @@ -134,7 +134,7 @@ class SentryStackTraceFactoryTest { SentryOptions().apply { addInAppExclude("io.mysentry") addInAppInclude("io.mysentry") - } + }, ) val sentryElements = sentryStackTraceFactory.getStackFrames(elements, false) @@ -148,7 +148,7 @@ class SentryStackTraceFactoryTest { SentryOptions().apply { addInAppExclude("io.mysentry.not") addInAppInclude("io.mysentry.inApp") - } + }, ) assertTrue(sentryStackTraceFactory.isInApp("io.mysentry.inApp.ClassName")!!) assertTrue(sentryStackTraceFactory.isInApp("io.mysentry.inApp.somePackage.ClassName")!!) @@ -172,7 +172,7 @@ class SentryStackTraceFactoryTest { assertNull( sut.getStackFrames(stacktrace, false)!!.find { it.module != null && it.module!!.startsWith("io.sentry") - } + }, ) } @@ -185,7 +185,7 @@ class SentryStackTraceFactoryTest { assertTrue( sut.getStackFrames(stacktrace, true)!!.any { it.module != null && it.module!!.startsWith("io.sentry") - } + }, ) } @@ -198,7 +198,7 @@ class SentryStackTraceFactoryTest { assertNotNull( sut.getStackFrames(stacktrace, false)!!.find { it.module != null && it.module!!.startsWith("io.sentry") - } + }, ) } @@ -211,7 +211,7 @@ class SentryStackTraceFactoryTest { assertNotNull( sut.getStackFrames(stacktrace, false)!!.find { it.module != null && it.module!!.startsWith("io.sentry") - } + }, ) } diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index b65dda88c46..9fb60f6922f 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -638,7 +638,7 @@ class SentryTest { assertNotNull(currentScopesEvent) assertNotNull( - currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbMainClone" } + currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbMainClone" }, ) assertNotNull(currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbCurrent" }) assertNull(currentScopesEvent.breadcrumbs?.firstOrNull { it.message == "breadcrumbNoOp" }) @@ -825,7 +825,7 @@ class SentryTest { .log( eq(SentryLevel.ERROR), eq( - "Failed to call the executor. Old profiles will not be deleted. Did you call Sentry.close()?" + "Failed to call the executor. Old profiles will not be deleted. Did you call Sentry.close()?", ), any(), ) @@ -1216,7 +1216,7 @@ class SentryTest { assertEquals("app.launch", it.transactionContext.name) assertEquals("profile", it.transactionContext.operation) assertTrue(it.transactionContext.isForNextAppStart) - } + }, ) verify(mockProfilesSampler) .sample( @@ -1224,7 +1224,7 @@ class SentryTest { assertEquals("app.launch", it.transactionContext.name) assertEquals("profile", it.transactionContext.operation) assertTrue(it.transactionContext.isForNextAppStart) - } + }, ) } diff --git a/sentry/src/test/java/io/sentry/SentryThreadFactoryTest.kt b/sentry/src/test/java/io/sentry/SentryThreadFactoryTest.kt index c2eda19efc4..7f89c56448d 100644 --- a/sentry/src/test/java/io/sentry/SentryThreadFactoryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryThreadFactoryTest.kt @@ -12,7 +12,7 @@ class SentryThreadFactoryTest { class Fixture { internal fun getSut() = SentryThreadFactory( - SentryStackTraceFactory(SentryOptions().apply { addInAppExclude("io.sentry") }) + SentryStackTraceFactory(SentryOptions().apply { addInAppExclude("io.sentry") }), ) } @@ -53,7 +53,7 @@ class SentryThreadFactoryTest { sut .getCurrentThreads(null, true)!! .filter { it.stacktrace != null } - .any { it.stacktrace!!.frames!!.count() > 0 } + .any { it.stacktrace!!.frames!!.count() > 0 }, ) } @@ -64,7 +64,7 @@ class SentryThreadFactoryTest { sut .getCurrentThreads(null, true)!! .filter { it.stacktrace != null } - .any { it.stacktrace!!.snapshot == true } + .any { it.stacktrace!!.snapshot == true }, ) } @@ -75,7 +75,7 @@ class SentryThreadFactoryTest { sut .getCurrentThreads(null, false)!! .filter { it.stacktrace != null } - .any { it.stacktrace!!.frames!!.count() > 0 } + .any { it.stacktrace!!.frames!!.count() > 0 }, ) } diff --git a/sentry/src/test/java/io/sentry/SentryTracerTest.kt b/sentry/src/test/java/io/sentry/SentryTracerTest.kt index d0333beea0e..f1b76c6fecc 100644 --- a/sentry/src/test/java/io/sentry/SentryTracerTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTracerTest.kt @@ -175,11 +175,13 @@ class SentryTracerTest { @Test fun `does not create child span if origin is ignored`() { val tracer = - fixture.getSut({ - it.setDebug(true) - it.setLogger(SystemOutLogger()) - it.setIgnoredSpanOrigins(listOf("ignored")) - }) + fixture.getSut( + { + it.setDebug(true) + it.setLogger(SystemOutLogger()) + it.setIgnoredSpanOrigins(listOf("ignored")) + }, + ) tracer.startChild("child1", null, SpanOptions().also { it.origin = "ignored" }) tracer.startChild("child2") assertEquals(1, tracer.children.size) @@ -188,11 +190,13 @@ class SentryTracerTest { @Test fun `does not add more spans than configured in options`() { val tracer = - fixture.getSut({ - it.maxSpans = 2 - it.setDebug(true) - it.setLogger(SystemOutLogger()) - }) + fixture.getSut( + { + it.maxSpans = 2 + it.setDebug(true) + it.setLogger(SystemOutLogger()) + }, + ) tracer.startChild("child1") tracer.startChild("child2") tracer.startChild("child3") @@ -202,11 +206,13 @@ class SentryTracerTest { @Test fun `when span limit is reached, startChild returns NoOpSpan`() { val tracer = - fixture.getSut({ - it.maxSpans = 2 - it.setDebug(true) - it.setLogger(SystemOutLogger()) - }) + fixture.getSut( + { + it.maxSpans = 2 + it.setDebug(true) + it.setLogger(SystemOutLogger()) + }, + ) tracer.startChild("child1") tracer.startChild("child2") assertTrue(tracer.startChild("child3") is NoOpSpan) @@ -291,7 +297,7 @@ class SentryTracerTest { optionsConfiguration = { it.profilesSampleRate = 0.0 it.setTransactionProfiler(transactionProfiler) - } + }, ) tracer.finish() verify(transactionProfiler, never()).onTransactionFinish(any(), anyOrNull(), anyOrNull()) @@ -534,7 +540,7 @@ class SentryTracerTest { fun `when continuous profiler is not running, profile context is not set`() { val tracer = fixture.getSut( - optionsConfiguration = { it.setContinuousProfiler(NoOpContinuousProfiler.getInstance()) } + optionsConfiguration = { it.setContinuousProfiler(NoOpContinuousProfiler.getInstance()) }, ) tracer.finish() verify(fixture.scopes) @@ -582,7 +588,7 @@ class SentryTracerTest { fixture.getSut( optionsConfiguration = { options -> options.setContinuousProfiler(NoOpContinuousProfiler.getInstance()) - } + }, ) val span = tracer.startChild("span.op") assertNull(span.getData(SpanDataConvention.PROFILER_ID)) @@ -984,9 +990,11 @@ class SentryTracerTest { @Test fun `returns trace state`() { val transaction = - fixture.getSut({ - it.isSendDefaultPii = true - }) + fixture.getSut( + { + it.isSendDefaultPii = true + }, + ) fixture.scopes.setUser(User().apply { id = "user-id" }) val replayId = SentryId() fixture.scopes.configureScope { it.replayId = replayId } @@ -1058,11 +1066,13 @@ class SentryTracerTest { @Test fun `returns baggage header`() { val transaction = - fixture.getSut({ - it.environment = "production" - it.release = "1.0.99-rc.7" - it.isSendDefaultPii = true - }) + fixture.getSut( + { + it.environment = "production" + it.release = "1.0.99-rc.7" + it.isSendDefaultPii = true + }, + ) fixture.scopes.setUser(User().apply { id = "userId12345" }) val replayId = SentryId() @@ -1086,10 +1096,12 @@ class SentryTracerTest { @Test fun `returns baggage header without userId if not send pii`() { val transaction = - fixture.getSut({ - it.environment = "production" - it.release = "1.0.99-rc.7" - }) + fixture.getSut( + { + it.environment = "production" + it.release = "1.0.99-rc.7" + }, + ) fixture.scopes.setUser(User().apply { id = "userId12345" }) @@ -1110,11 +1122,13 @@ class SentryTracerTest { @Test fun `returns baggage header without userId if send pii and null user`() { val transaction = - fixture.getSut({ - it.environment = "production" - it.release = "1.0.99-rc.7" - it.isSendDefaultPii = true - }) + fixture.getSut( + { + it.environment = "production" + it.release = "1.0.99-rc.7" + it.isSendDefaultPii = true + }, + ) fixture.scopes.setUser(null) @@ -1910,7 +1924,7 @@ class SentryTracerTest { transactionFinishedCallback = { assertFalse(it.isFinished) assertNotNull(it.finishDate) - } + }, ) assertFalse(transaction.isFinished) assertNull(transaction.finishDate) diff --git a/sentry/src/test/java/io/sentry/SentryWrapperTest.kt b/sentry/src/test/java/io/sentry/SentryWrapperTest.kt index 0ed46d8fa38..db52c54fb30 100644 --- a/sentry/src/test/java/io/sentry/SentryWrapperTest.kt +++ b/sentry/src/test/java/io/sentry/SentryWrapperTest.kt @@ -135,7 +135,7 @@ class SentryWrapperTest { Sentry.addBreadcrumb("MyClonedBreadcrumb") Sentry.captureMessage("ClonedMessage") "Result 1" - } + }, ) val future2 = @@ -145,7 +145,7 @@ class SentryWrapperTest { Sentry.addBreadcrumb("MyClonedBreadcrumb2") Sentry.captureMessage("ClonedMessage2") "Result 2" - } + }, ) Sentry.addBreadcrumb("MyOriginalBreadcrumb") @@ -180,7 +180,7 @@ class SentryWrapperTest { assertNotEquals(mainScopes, Sentry.getCurrentScopes()) assertNotEquals(threadedScopes, Sentry.getCurrentScopes()) "Result 1" - } + }, ) callableFuture.get() @@ -216,7 +216,7 @@ class SentryWrapperTest { Sentry.addBreadcrumb("MyClonedBreadcrumb") Sentry.captureMessage("ClonedMessage") "Result 1" - } + }, ) val future2 = @@ -226,7 +226,7 @@ class SentryWrapperTest { Sentry.addBreadcrumb("MyClonedBreadcrumb2") Sentry.captureMessage("ClonedMessage2") "Result 2" - } + }, ) Sentry.addBreadcrumb("MyOriginalBreadcrumb") @@ -261,7 +261,7 @@ class SentryWrapperTest { assertNotEquals(mainScopes, Sentry.getCurrentScopes()) assertNotEquals(threadedScopes, Sentry.getCurrentScopes()) "Result 1" - } + }, ) runnableFuture.get() diff --git a/sentry/src/test/java/io/sentry/SpanTest.kt b/sentry/src/test/java/io/sentry/SpanTest.kt index e65984e82fd..0f5f3d69e3d 100644 --- a/sentry/src/test/java/io/sentry/SpanTest.kt +++ b/sentry/src/test/java/io/sentry/SpanTest.kt @@ -28,7 +28,7 @@ class SpanTest { .thenReturn( SentryOptions().apply { dsn = "https://key@sentry.io/proj" - } + }, ) } @@ -395,7 +395,7 @@ class SpanTest { SpanOptions().apply { isTrimStart = true isTrimEnd = true - } + }, ) // and two child spans are started @@ -430,7 +430,7 @@ class SpanTest { TransactionOptions().apply { isTrimStart = true isTrimEnd = true - } + }, ) // and two child spans are started @@ -595,7 +595,7 @@ class SpanTest { } private fun getTransaction( - transactionContext: TransactionContext = TransactionContext("name", "op") + transactionContext: TransactionContext = TransactionContext("name", "op"), ): SentryTracer = SentryTracer(transactionContext, fixture.scopes) private fun startChildFromSpan(): Span { diff --git a/sentry/src/test/java/io/sentry/StackTest.kt b/sentry/src/test/java/io/sentry/StackTest.kt index 0c0a8d6c866..38fc567e0ad 100644 --- a/sentry/src/test/java/io/sentry/StackTest.kt +++ b/sentry/src/test/java/io/sentry/StackTest.kt @@ -68,10 +68,10 @@ class StackTest { fun `cloning stack clones stack items`() { val stack = fixture.getSut( - fixture.createStackItem(Scope(fixture.options).apply { this.setTag("rootTag", "value") }) + fixture.createStackItem(Scope(fixture.options).apply { this.setTag("rootTag", "value") }), ) stack.push( - fixture.createStackItem(Scope(fixture.options).apply { this.setTag("childTag", "value") }) + fixture.createStackItem(Scope(fixture.options).apply { this.setTag("childTag", "value") }), ) val clone = Stack(stack) diff --git a/sentry/src/test/java/io/sentry/TracesSamplerTest.kt b/sentry/src/test/java/io/sentry/TracesSamplerTest.kt index 9b8f0666854..28a3c4e52c7 100644 --- a/sentry/src/test/java/io/sentry/TracesSamplerTest.kt +++ b/sentry/src/test/java/io/sentry/TracesSamplerTest.kt @@ -111,7 +111,7 @@ class TracesSamplerTest { val sampler = fixture.getSut(tracesSamplerCallback = { 0.2 }, profilesSamplerCallback = { 0.2 }) val samplingDecision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null) + SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null), ) assertTrue(samplingDecision.sampled) assertEquals(0.2, samplingDecision.sampleRate) @@ -123,7 +123,7 @@ class TracesSamplerTest { val sampler = fixture.getSut(tracesSampleRate = 1.0, profilesSamplerCallback = { 0.2 }) val samplingDecision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null) + SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null), ) assertTrue(samplingDecision.sampled) assertTrue(samplingDecision.profileSampled) @@ -136,7 +136,7 @@ class TracesSamplerTest { val sampler = fixture.getSut(tracesSamplerCallback = { 0.2 }) val samplingDecision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.9, null) + SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.9, null), ) assertFalse(samplingDecision.sampled) assertEquals(0.2, samplingDecision.sampleRate) @@ -148,7 +148,7 @@ class TracesSamplerTest { val sampler = fixture.getSut(tracesSampleRate = 1.0, profilesSamplerCallback = { 0.2 }) val samplingDecision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.9, null) + SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.9, null), ) assertTrue(samplingDecision.sampled) assertFalse(samplingDecision.profileSampled) @@ -185,7 +185,7 @@ class TracesSamplerTest { transactionContextParentSampled.parentSampled = true val samplingDecision = sampler.sample( - SamplingContext(transactionContextParentSampled, CustomSamplingContext(), 0.1, null) + SamplingContext(transactionContextParentSampled, CustomSamplingContext(), 0.1, null), ) assertTrue(samplingDecision.sampled) assertNull(samplingDecision.sampleRate) @@ -199,7 +199,7 @@ class TracesSamplerTest { transactionContextParentSampled.setParentSampled(true, true) val samplingDecision = sampler.sample( - SamplingContext(transactionContextParentSampled, CustomSamplingContext(), 0.1, null) + SamplingContext(transactionContextParentSampled, CustomSamplingContext(), 0.1, null), ) assertTrue(samplingDecision.sampled) assertTrue(samplingDecision.profileSampled) @@ -212,7 +212,7 @@ class TracesSamplerTest { val sampler = fixture.getSut(tracesSampleRate = 0.2, tracesSamplerCallback = { null }) val samplingDecision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null) + SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null), ) assertTrue(samplingDecision.sampled) assertEquals(0.2, samplingDecision.sampleRate) @@ -229,7 +229,7 @@ class TracesSamplerTest { ) val samplingDecision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null) + SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null), ) assertTrue(samplingDecision.sampled) assertTrue(samplingDecision.profileSampled) @@ -241,7 +241,7 @@ class TracesSamplerTest { val sampler = fixture.getSut() val samplingDecision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null) + SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null), ) assertFalse(samplingDecision.sampled) assertNull(samplingDecision.sampleRate) @@ -253,7 +253,7 @@ class TracesSamplerTest { val sampler = fixture.getSut(tracesSampleRate = 1.0) val samplingDecision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null) + SamplingContext(TransactionContext("name", "op"), CustomSamplingContext(), 0.1, null), ) assertTrue(samplingDecision.sampled) assertFalse(samplingDecision.profileSampled) @@ -268,7 +268,7 @@ class TracesSamplerTest { transactionContextParentNotSampled.parentSampled = false val samplingDecision = sampler.sample( - SamplingContext(transactionContextParentNotSampled, CustomSamplingContext(), 0.1, null) + SamplingContext(transactionContextParentNotSampled, CustomSamplingContext(), 0.1, null), ) assertFalse(samplingDecision.sampled) assertNull(samplingDecision.sampleRate) @@ -280,7 +280,7 @@ class TracesSamplerTest { transactionContextParentSampled.setParentSampled(true, true) val samplingDecisionParentSampled = sampler.sample( - SamplingContext(transactionContextParentSampled, CustomSamplingContext(), 0.1, null) + SamplingContext(transactionContextParentSampled, CustomSamplingContext(), 0.1, null), ) assertTrue(samplingDecisionParentSampled.sampled) assertNull(samplingDecisionParentSampled.sampleRate) @@ -309,7 +309,7 @@ class TracesSamplerTest { transactionContextNotSampled.sampled = false val samplingDecision = sampler.sample( - SamplingContext(transactionContextNotSampled, CustomSamplingContext(), 0.1, null) + SamplingContext(transactionContextNotSampled, CustomSamplingContext(), 0.1, null), ) assertFalse(samplingDecision.sampled) assertNull(samplingDecision.sampleRate) @@ -331,7 +331,7 @@ class TracesSamplerTest { transactionContextUnsampledWithProfile.setSampled(false, true) val samplingDecisionContextUnsampledWithProfile = sampler.sample( - SamplingContext(transactionContextUnsampledWithProfile, CustomSamplingContext(), 0.1, null) + SamplingContext(transactionContextUnsampledWithProfile, CustomSamplingContext(), 0.1, null), ) assertFalse(samplingDecisionContextUnsampledWithProfile.sampled) assertNull(samplingDecisionContextUnsampledWithProfile.sampleRate) @@ -585,11 +585,11 @@ class TracesSamplerTest { tracesSamplerCallback = { samplingContext -> attributeValue = samplingContext.getAttribute("attr") 1.0 - } + }, ) val decision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), null, 0.0, mapOf("attr" to "123")) + SamplingContext(TransactionContext("name", "op"), null, 0.0, mapOf("attr" to "123")), ) assertTrue(decision.sampled) assertEquals("123", attributeValue) @@ -603,11 +603,11 @@ class TracesSamplerTest { tracesSamplerCallback = { samplingContext -> attributeValue = samplingContext.getAttribute("i-do-not-exist") 1.0 - } + }, ) val decision = sampler.sample( - SamplingContext(TransactionContext("name", "op"), null, 0.0, mapOf("attr" to "123")) + SamplingContext(TransactionContext("name", "op"), null, 0.0, mapOf("attr" to "123")), ) assertTrue(decision.sampled) assertNull(attributeValue) @@ -621,7 +621,7 @@ class TracesSamplerTest { tracesSamplerCallback = { samplingContext -> attributeValue = samplingContext.getAttribute("i-do-not-exist") 1.0 - } + }, ) val decision = sampler.sample(SamplingContext(TransactionContext("name", "op"), null, 0.0, null)) diff --git a/sentry/src/test/java/io/sentry/UncaughtExceptionHandlerIntegrationTest.kt b/sentry/src/test/java/io/sentry/UncaughtExceptionHandlerIntegrationTest.kt index 02da3b9a335..f12b01a88fc 100644 --- a/sentry/src/test/java/io/sentry/UncaughtExceptionHandlerIntegrationTest.kt +++ b/sentry/src/test/java/io/sentry/UncaughtExceptionHandlerIntegrationTest.kt @@ -175,10 +175,10 @@ class UncaughtExceptionHandlerIntegrationTest { assertTrue( outputStreamCaptor .toString() - .contains("java.lang.RuntimeException: This should be printed!") + .contains("java.lang.RuntimeException: This should be printed!"), ) assertTrue( - outputStreamCaptor.toString().contains("UncaughtExceptionHandlerIntegrationTest.kt:") + outputStreamCaptor.toString().contains("UncaughtExceptionHandlerIntegrationTest.kt:"), ) } finally { System.setErr(standardErr) @@ -258,7 +258,7 @@ class UncaughtExceptionHandlerIntegrationTest { any(), argThat { (HintUtils.getSentrySdkHint(this) as UncaughtExceptionHint).isFlushable( - eventCaptor.firstValue.eventId + eventCaptor.firstValue.eventId, ) }, ) @@ -281,7 +281,7 @@ class UncaughtExceptionHandlerIntegrationTest { any(), argThat { !(HintUtils.getSentrySdkHint(this) as UncaughtExceptionHint).isFlushable( - eventCaptor.firstValue.eventId + eventCaptor.firstValue.eventId, ) }, ) @@ -295,7 +295,7 @@ class UncaughtExceptionHandlerIntegrationTest { whenever(handler.defaultUncaughtExceptionHandler).thenAnswer { currentDefaultHandler } whenever( - handler.setDefaultUncaughtExceptionHandler(anyOrNull()) + handler.setDefaultUncaughtExceptionHandler(anyOrNull()), ) .then { currentDefaultHandler = it.getArgument(0) @@ -324,7 +324,7 @@ class UncaughtExceptionHandlerIntegrationTest { whenever(handler.defaultUncaughtExceptionHandler).thenAnswer { currentDefaultHandler } whenever( - handler.setDefaultUncaughtExceptionHandler(anyOrNull()) + handler.setDefaultUncaughtExceptionHandler(anyOrNull()), ) .then { currentDefaultHandler = it.getArgument(0) @@ -354,7 +354,7 @@ class UncaughtExceptionHandlerIntegrationTest { whenever(handler.defaultUncaughtExceptionHandler).thenAnswer { currentDefaultHandler } whenever( - handler.setDefaultUncaughtExceptionHandler(anyOrNull()) + handler.setDefaultUncaughtExceptionHandler(anyOrNull()), ) .then { currentDefaultHandler = it.getArgument(0) @@ -390,7 +390,7 @@ class UncaughtExceptionHandlerIntegrationTest { whenever(handler.defaultUncaughtExceptionHandler).thenAnswer { currentDefaultHandler } whenever( - handler.setDefaultUncaughtExceptionHandler(anyOrNull()) + handler.setDefaultUncaughtExceptionHandler(anyOrNull()), ) .then { currentDefaultHandler = it.getArgument(0) @@ -433,7 +433,7 @@ class UncaughtExceptionHandlerIntegrationTest { whenever(handler.defaultUncaughtExceptionHandler).thenAnswer { currentDefaultHandler } whenever( - handler.setDefaultUncaughtExceptionHandler(anyOrNull()) + handler.setDefaultUncaughtExceptionHandler(anyOrNull()), ) .then { currentDefaultHandler = it.getArgument(0) @@ -487,7 +487,7 @@ class UncaughtExceptionHandlerIntegrationTest { whenever(handler.defaultUncaughtExceptionHandler).thenAnswer { currentDefaultHandler } whenever( - handler.setDefaultUncaughtExceptionHandler(anyOrNull()) + handler.setDefaultUncaughtExceptionHandler(anyOrNull()), ) .then { currentDefaultHandler = it.getArgument(0) diff --git a/sentry/src/test/java/io/sentry/cache/PersistingScopeObserverBatchingTest.kt b/sentry/src/test/java/io/sentry/cache/PersistingScopeObserverBatchingTest.kt index d893e52d4ce..6f337e80807 100644 --- a/sentry/src/test/java/io/sentry/cache/PersistingScopeObserverBatchingTest.kt +++ b/sentry/src/test/java/io/sentry/cache/PersistingScopeObserverBatchingTest.kt @@ -97,7 +97,7 @@ class PersistingScopeObserverBatchingTest { SerializerHook(options.serializer) { sut.setBreadcrumbs(emptyList()) sut.addBreadcrumb(Breadcrumb().apply { message = "kept" }) - } + }, ) sut = getSut(executor) diff --git a/sentry/src/test/java/io/sentry/cache/PersistingScopeObserverTest.kt b/sentry/src/test/java/io/sentry/cache/PersistingScopeObserverTest.kt index b98c5b8a319..147aa5a3e21 100644 --- a/sentry/src/test/java/io/sentry/cache/PersistingScopeObserverTest.kt +++ b/sentry/src/test/java/io/sentry/cache/PersistingScopeObserverTest.kt @@ -235,7 +235,7 @@ class PersistingScopeObserverTest( appStartTime = DateUtils.getCurrentDateTime() buildType = "debug" appVersion = "2021" - } + }, ) setBrowser(Browser().apply { name = "Chrome" }) setDevice( @@ -262,13 +262,13 @@ class PersistingScopeObserverTest( batteryTemperature = 37.0f batteryLevel = 92.0f locale = "en-US" - } + }, ) setGpu( Gpu().apply { vendorName = "GeForce" memorySize = 1000 - } + }, ) setOperatingSystem( OperatingSystem().apply { @@ -276,7 +276,7 @@ class PersistingScopeObserverTest( build = "2021.123_alpha" name = "Android" version = "12" - } + }, ) }, StoreScopeValue { contexts, _ -> setContexts(contexts) }, diff --git a/sentry/src/test/java/io/sentry/cache/tape/QueueFileTest.kt b/sentry/src/test/java/io/sentry/cache/tape/QueueFileTest.kt index f288a1b7c56..d025bf907ab 100644 --- a/sentry/src/test/java/io/sentry/cache/tape/QueueFileTest.kt +++ b/sentry/src/test/java/io/sentry/cache/tape/QueueFileTest.kt @@ -672,8 +672,8 @@ class QueueFileTest { .contains( "zero=true, length=4096," + " size=15," + - " first=Element[position=32, length=0], last=Element[position=179, length=14]}" - ) + " first=Element[position=32, length=0], last=Element[position=179, length=14]}", + ), ) } diff --git a/sentry/src/test/java/io/sentry/clientreport/ClientReportMultiThreadingTest.kt b/sentry/src/test/java/io/sentry/clientreport/ClientReportMultiThreadingTest.kt index 7f14c987438..46c532a8036 100644 --- a/sentry/src/test/java/io/sentry/clientreport/ClientReportMultiThreadingTest.kt +++ b/sentry/src/test/java/io/sentry/clientreport/ClientReportMultiThreadingTest.kt @@ -54,7 +54,7 @@ class ClientReportMultiThreadingTest { (1..numberOfIncrementsPerThread).forEach { clientReportRecorder.recordLostEvent(randomReason(), randomCategory()) } - } + }, ) } @@ -97,7 +97,7 @@ class ClientReportMultiThreadingTest { (1..numberOfIncrementsPerThread).forEach { clientReportRecorder.recordLostEvent(randomReason(), randomCategory()) } - } + }, ) } @@ -109,7 +109,7 @@ class ClientReportMultiThreadingTest { clientReportRecorder.resetCountsAndGenerateClientReport()?.let { clientReports.add(it) } Thread.sleep(20) } - } + }, ) futures.forEach { completionService.take().get() } @@ -152,7 +152,7 @@ class ClientReportMultiThreadingTest { (1..numberOfIncrementsPerThread).forEach { clientReportRecorder.recordLostEvent(randomReason(), randomCategory()) } - } + }, ) } @@ -170,7 +170,7 @@ class ClientReportMultiThreadingTest { clientReportRecorder.recordLostEnvelope(DiscardReason.NETWORK_ERROR, envelope) } } - } + }, ) futures.forEach { completionService.take().get() } diff --git a/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt b/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt index 3408198b657..d02c9e61a54 100644 --- a/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt +++ b/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt @@ -199,7 +199,7 @@ class ClientReportTest { val envelope = testHelper.newEnvelope( - SentryEnvelopeItem.fromEvent(opts.serializer, SentryTransaction(transaction)) + SentryEnvelopeItem.fromEvent(opts.serializer, SentryTransaction(transaction)), ) clientReportRecorder.recordLostEnvelope(DiscardReason.NETWORK_ERROR, envelope) @@ -319,7 +319,7 @@ class ClientReportTest { ChronoUnit.MILLIS.between( LocalDateTime.now(), envelopeReport.timestamp.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), - ) < 10000 + ) < 10000, ) } @@ -340,7 +340,7 @@ class ClientReportTest { // Counts restored from an attached client report were already reported once, so replaying them // must not fire onDiscard a second time. Both public entry points have to hold the property. private fun assertRestoringCountsDoesNotFireOnDiscard( - recordLost: (ClientReportRecorder, SentryEnvelope) -> Unit + recordLost: (ClientReportRecorder, SentryEnvelope) -> Unit, ) { val onDiscardMock = mock() givenClientReportRecorder { options -> options.onDiscard = onDiscardMock } @@ -374,9 +374,9 @@ class ClientReportTest { listOf( SentryLogEvent(SentryId(), SentryLongDate(1), "log message 1", SentryLogLevel.ERROR), SentryLogEvent(SentryId(), SentryLongDate(2), "log message 2", SentryLogLevel.WARN), - ) + ), ), - ) + ), ) clientReportRecorder.recordLostEnvelopeItem(DiscardReason.NETWORK_ERROR, envelope.items.first()) @@ -406,9 +406,9 @@ class ClientReportTest { SentryMetricsEvent(SentryId(), SentryLongDate(1), "metric1", "counter", 1.0), SentryMetricsEvent(SentryId(), SentryLongDate(2), "metric2", "gauge", 2.0), SentryMetricsEvent(SentryId(), SentryLongDate(3), "metric3", "distribution", 3.0), - ) + ), ), - ) + ), ) clientReportRecorder.recordLostEnvelopeItem(DiscardReason.NETWORK_ERROR, envelope.items.first()) @@ -576,7 +576,7 @@ class ClientReportTest { this!!.discardedEvents!!.first { it.category == category.category }.quantity private fun givenClientReportRecorder( - callback: Sentry.OptionsConfiguration? = null + callback: Sentry.OptionsConfiguration? = null, ) { setupSentry { options -> callback?.configure(options) } clientReportRecorder = opts.clientReportRecorder as ClientReportRecorder diff --git a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileInputStreamTest.kt b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileInputStreamTest.kt index bb4c24e927f..36c1787d9ec 100644 --- a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileInputStreamTest.kt +++ b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileInputStreamTest.kt @@ -47,7 +47,7 @@ class SentryFileInputStreamTest { isSendDefaultPii = sendDefaultPii threadChecker = ThreadChecker.getInstance() addInAppInclude("org.junit") - } + }, ) sentryTracer = SentryTracer(TransactionContext("name", "op"), scopes) if (activeTransaction) { diff --git a/sentry/src/test/java/io/sentry/internal/debugmeta/ResourcesDebugMetaLoaderTest.kt b/sentry/src/test/java/io/sentry/internal/debugmeta/ResourcesDebugMetaLoaderTest.kt index 59bc9012348..2861f9f8c56 100644 --- a/sentry/src/test/java/io/sentry/internal/debugmeta/ResourcesDebugMetaLoaderTest.kt +++ b/sentry/src/test/java/io/sentry/internal/debugmeta/ResourcesDebugMetaLoaderTest.kt @@ -57,8 +57,8 @@ class ResourcesDebugMetaLoaderTest { io.sentry.bundle-ids=88ba82db-cd26-4c09-8b31-21461d286b68 io.sentry.build-tool=maven """ - .trimIndent() - ) + .trimIndent(), + ), ) val options = SentryOptions() @@ -82,8 +82,8 @@ class ResourcesDebugMetaLoaderTest { io.sentry.bundle-ids=88ba82db-cd26-4c09-8b31-21461d286b68,8d11a44a-facd-46c1-a49b-87d256227101 io.sentry.build-tool=maven """ - .trimIndent() - ) + .trimIndent(), + ), ) val options = SentryOptions() @@ -119,7 +119,7 @@ class ResourcesDebugMetaLoaderTest { io.sentry.build-tool=maven """ .trimIndent(), - ) + ), ) val options = SentryOptions() @@ -158,8 +158,8 @@ class ResourcesDebugMetaLoaderTest { io.sentry.build-tool=maven io.sentry.build-tool-version=1.0 """ - .trimIndent() - ) + .trimIndent(), + ), ) val options = SentryOptions() @@ -182,8 +182,8 @@ class ResourcesDebugMetaLoaderTest { io.sentry.bundle-ids=88ba82db-cd26-4c09-8b31-21461d286b68 io.sentry.build-tool=maven """ - .trimIndent() - ) + .trimIndent(), + ), ) val options = SentryOptions() @@ -205,8 +205,8 @@ class ResourcesDebugMetaLoaderTest { io.sentry.ProguardUuids=34077988-a0e5-4839-9618-7400e1616d1b io.sentry.bundle-ids=88ba82db-cd26-4c09-8b31-21461d286b68 """ - .trimIndent() - ) + .trimIndent(), + ), ) val options = SentryOptions() diff --git a/sentry/src/test/java/io/sentry/internal/modules/ManifestModulesLoaderTest.kt b/sentry/src/test/java/io/sentry/internal/modules/ManifestModulesLoaderTest.kt index c960902f7bc..dbf35c4b115 100644 --- a/sentry/src/test/java/io/sentry/internal/modules/ManifestModulesLoaderTest.kt +++ b/sentry/src/test/java/io/sentry/internal/modules/ManifestModulesLoaderTest.kt @@ -23,23 +23,23 @@ class ManifestModulesLoaderTest { Collections.enumeration( listOf( URL( - "jar:file:/Users/sentry/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-security/3.0.0/efe7ffae5c9875e2019c6a701759ea524cb331ee/spring-boot-starter-security-3.0.0.jar!/META-INF/MANIFEST.MF" + "jar:file:/Users/sentry/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-security/3.0.0/efe7ffae5c9875e2019c6a701759ea524cb331ee/spring-boot-starter-security-3.0.0.jar!/META-INF/MANIFEST.MF", ), URL( - "jar:file:/Users/sentry/.gradle/caches/modules-2/files-2.1/org.yaml/snakeyaml/1.33/2cd0a87ff7df953f810c344bdf2fe3340b954c69/snakeyaml-1.33.jar!/META-INF/MANIFEST.MF" + "jar:file:/Users/sentry/.gradle/caches/modules-2/files-2.1/org.yaml/snakeyaml/1.33/2cd0a87ff7df953f810c344bdf2fe3340b954c69/snakeyaml-1.33.jar!/META-INF/MANIFEST.MF", ), URL( - "jar:file:/usr/local/tomcat/webapps/ROOT/WEB-INF/lib/aspectjweaver-1.9.9.1.jar!/META-INF/MANIFEST.MF" + "jar:file:/usr/local/tomcat/webapps/ROOT/WEB-INF/lib/aspectjweaver-1.9.9.1.jar!/META-INF/MANIFEST.MF", ), URL( - "jar:file:/Users/sentry/repos/sentry-java/sentry-samples/sentry-samples-spring-boot-jakarta/build/libs/sentry-samples-spring-boot-jakarta-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/kotlin-stdlib-jdk8-1.6.10.jar!/META-INF/MANIFEST.MF" + "jar:file:/Users/sentry/repos/sentry-java/sentry-samples/sentry-samples-spring-boot-jakarta/build/libs/sentry-samples-spring-boot-jakarta-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/kotlin-stdlib-jdk8-1.6.10.jar!/META-INF/MANIFEST.MF", ), URL("http://sentry.io"), URL( - "jar:file:/Users/sentry/repos/sentry-java/sentry-samples/sentry-samples-spring-boot-jakarta/build/libs/sentry-samples-spring-boot-jakarta-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/hello-world.jar!/META-INF/MANIFEST.MF" + "jar:file:/Users/sentry/repos/sentry-java/sentry-samples/sentry-samples-spring-boot-jakarta/build/libs/sentry-samples-spring-boot-jakarta-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/hello-world.jar!/META-INF/MANIFEST.MF", ), - ) - ) + ), + ), ) val sut = ManifestModulesLoader(classLoader, logger) diff --git a/sentry/src/test/java/io/sentry/internal/modules/ResourcesModulesLoaderTest.kt b/sentry/src/test/java/io/sentry/internal/modules/ResourcesModulesLoaderTest.kt index 290fc0d0c0b..55e87d3a924 100644 --- a/sentry/src/test/java/io/sentry/internal/modules/ResourcesModulesLoaderTest.kt +++ b/sentry/src/test/java/io/sentry/internal/modules/ResourcesModulesLoaderTest.kt @@ -38,7 +38,7 @@ class ResourcesModulesLoaderTest { com.squareup.okhttp3:okhttp:3.14.9 com.squareup.okio:okio:1.17.2 """ - .trimIndent() + .trimIndent(), ) assertEquals( @@ -56,7 +56,7 @@ class ResourcesModulesLoaderTest { com.squareup.okhttp3:okhttp:3.14.9 com.squareup.okio:okio:1.17.2 """ - .trimIndent() + .trimIndent(), ) // first, call method to get modules cached @@ -86,7 +86,7 @@ class ResourcesModulesLoaderTest { """ com.squareup.okhttp3;3.14.9 """ - .trimIndent() + .trimIndent(), ) assertTrue(sut.orLoadModules!!.isEmpty()) diff --git a/sentry/src/test/java/io/sentry/protocol/BreadcrumbSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/BreadcrumbSerializationTest.kt index a33ddb91a2b..babe48366cc 100644 --- a/sentry/src/test/java/io/sentry/protocol/BreadcrumbSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/BreadcrumbSerializationTest.kt @@ -88,8 +88,8 @@ class BreadcrumbSerializationTest { mapOf( "data" to mapOf( - 123 to 456 // Invalid key type - ) + 123 to 456, // Invalid key type + ), ) val actual = Breadcrumb.fromMap(map, SentryOptions()) assertTrue(actual.data.isEmpty()) diff --git a/sentry/src/test/java/io/sentry/protocol/DebugMetaSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/DebugMetaSerializationTest.kt index eef5041dcb2..2dca7942212 100644 --- a/sentry/src/test/java/io/sentry/protocol/DebugMetaSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/DebugMetaSerializationTest.kt @@ -36,7 +36,7 @@ class DebugMetaSerializationTest { imageAddr = "8a258c81-641d-4e54-b06e-a0f56b1ee2ef" imageSize = -7905338721846826571L arch = "d00d5bea-fb5c-43c9-85f0-dc1350d957a4" - } + }, ) } } diff --git a/sentry/src/test/java/io/sentry/protocol/DebugMetaTest.kt b/sentry/src/test/java/io/sentry/protocol/DebugMetaTest.kt index a1c2f4edb05..8b8b0351c2b 100644 --- a/sentry/src/test/java/io/sentry/protocol/DebugMetaTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/DebugMetaTest.kt @@ -68,7 +68,7 @@ class DebugMetaTest { DebugImage().apply { type = DebugImage.PROGUARD uuid = "existing-id" - } + }, ) }, options, @@ -98,7 +98,7 @@ class DebugMetaTest { DebugImage().apply { type = DebugImage.PROGUARD uuid = "existing-id" - } + }, ) }, options, @@ -130,7 +130,7 @@ class DebugMetaTest { DebugImage().apply { type = "elf" debugId = "native-id" - } + }, ) }, options, @@ -190,7 +190,7 @@ class DebugMetaTest { DebugImage().apply { type = DebugImage.JVM debugId = "id1" - } + }, ) }, options, diff --git a/sentry/src/test/java/io/sentry/protocol/SentryExceptionSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/SentryExceptionSerializationTest.kt index ca80b34b0b9..a416133b10b 100644 --- a/sentry/src/test/java/io/sentry/protocol/SentryExceptionSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/SentryExceptionSerializationTest.kt @@ -41,11 +41,11 @@ class SentryExceptionSerializationTest { symbolAddr = "180e12cd-1fa8-405d-8dd8-e87b33fa2eb0" instructionAddr = "19864a78-2466-461f-9f0b-93a5c9ae7622" rawFunction = "f33035a4-0cf0-453d-b6f4-d7c27e9af924" - } + }, ) registers = mapOf( - "160eef70-2b1f-4ad8-8449-902bf7bef11b" to "6000b565-2a55-4337-99be-edf8a2668d1b" + "160eef70-2b1f-4ad8-8449-902bf7bef11b" to "6000b565-2a55-4337-99be-edf8a2668d1b", ) snapshot = true } @@ -57,11 +57,11 @@ class SentryExceptionSerializationTest { isHandled = false meta = mapOf( - "91e0d6d4-0818-403e-9826-6e4443f2b54e" to "11707d85-3cae-4a4c-8157-7a9b717cbe1e" + "91e0d6d4-0818-403e-9826-6e4443f2b54e" to "11707d85-3cae-4a4c-8157-7a9b717cbe1e", ) data = mapOf( - "0275caba-1fd8-4de3-9ead-b6c8dcdd5666" to "669cc6ad-1435-4233-b199-2800f901bbcd" + "0275caba-1fd8-4de3-9ead-b6c8dcdd5666" to "669cc6ad-1435-4233-b199-2800f901bbcd", ) synthetic = false } diff --git a/sentry/src/test/java/io/sentry/protocol/SentryLogsSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/SentryLogsSerializationTest.kt index ade038a408b..64d09f34371 100644 --- a/sentry/src/test/java/io/sentry/protocol/SentryLogsSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/SentryLogsSerializationTest.kt @@ -50,8 +50,8 @@ class SentryLogsSerializationTest { "custom.integer" to SentryLogEventAttributeValue("integer", 10), ) it.severityNumber = 10 - } - ) + }, + ), ) } diff --git a/sentry/src/test/java/io/sentry/protocol/SentryMetricsSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/SentryMetricsSerializationTest.kt index 2ce89e0af4b..07364105920 100644 --- a/sentry/src/test/java/io/sentry/protocol/SentryMetricsSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/SentryMetricsSerializationTest.kt @@ -49,8 +49,8 @@ class SentryMetricsSerializationTest { "custom.point" to SentryLogEventAttributeValue("string", Point(20, 30)), "custom.integer" to SentryLogEventAttributeValue("integer", 10), ) - } - ) + }, + ), ) } diff --git a/sentry/src/test/java/io/sentry/protocol/SentryProfileSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/SentryProfileSerializationTest.kt index b605a4a53dd..6ae478647b0 100644 --- a/sentry/src/test/java/io/sentry/protocol/SentryProfileSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/SentryProfileSerializationTest.kt @@ -73,7 +73,7 @@ class SentryProfileSerializationTest { SentryThreadMetadata().apply { name = "http-nio-8080-Acceptor" priority = 0 - } + }, ) } } diff --git a/sentry/src/test/java/io/sentry/protocol/SentryStackTraceSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/SentryStackTraceSerializationTest.kt index fc48446e5e4..8f7c15174b4 100644 --- a/sentry/src/test/java/io/sentry/protocol/SentryStackTraceSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/SentryStackTraceSerializationTest.kt @@ -36,7 +36,7 @@ class SentryStackTraceSerializationTest { symbolAddr = "180e12cd-1fa8-405d-8dd8-e87b33fa2eb0" instructionAddr = "19864a78-2466-461f-9f0b-93a5c9ae7622" rawFunction = "f33035a4-0cf0-453d-b6f4-d7c27e9af924" - } + }, ) registers = mapOf("160eef70-2b1f-4ad8-8449-902bf7bef11b" to "6000b565-2a55-4337-99be-edf8a2668d1b") diff --git a/sentry/src/test/java/io/sentry/protocol/SentryThreadSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/SentryThreadSerializationTest.kt index 674d10aa41e..cd1ef4b8129 100644 --- a/sentry/src/test/java/io/sentry/protocol/SentryThreadSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/SentryThreadSerializationTest.kt @@ -46,7 +46,7 @@ class SentryThreadSerializationTest { symbolAddr = "180e12cd-1fa8-405d-8dd8-e87b33fa2eb0" instructionAddr = "19864a78-2466-461f-9f0b-93a5c9ae7622" rawFunction = "f33035a4-0cf0-453d-b6f4-d7c27e9af924" - } + }, ) registers = mapOf( @@ -63,7 +63,7 @@ class SentryThreadSerializationTest { packageName = "java.lang" type = SentryLockReason.BLOCKED threadId = 11 - } + }, ) } } diff --git a/sentry/src/test/java/io/sentry/protocol/UserSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/UserSerializationTest.kt index 958382b8f68..b2098840940 100644 --- a/sentry/src/test/java/io/sentry/protocol/UserSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/UserSerializationTest.kt @@ -91,8 +91,8 @@ class UserSerializationTest { mapOf( "data" to mapOf( - 123 to 456 // Invalid key type - ) + 123 to 456, // Invalid key type + ), ) val actual = User.fromMap(map, SentryOptions()) assertTrue(actual?.data?.isEmpty() ?: false) diff --git a/sentry/src/test/java/io/sentry/protocol/ViewHierarchyNodeSerializationTest.kt b/sentry/src/test/java/io/sentry/protocol/ViewHierarchyNodeSerializationTest.kt index eb2f9e32e44..4e9f2e8205a 100644 --- a/sentry/src/test/java/io/sentry/protocol/ViewHierarchyNodeSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/ViewHierarchyNodeSerializationTest.kt @@ -24,7 +24,7 @@ class ViewHierarchyNodeSerializationTest { ViewHierarchyNode().apply { renderingSystem = "compose" type = "Clickable" - } + }, ) width = 100.0 height = 200.0 diff --git a/sentry/src/test/java/io/sentry/rrweb/RRWebInteractionMoveEventSerializationTest.kt b/sentry/src/test/java/io/sentry/rrweb/RRWebInteractionMoveEventSerializationTest.kt index f0baa59b980..d3bbc3c3021 100644 --- a/sentry/src/test/java/io/sentry/rrweb/RRWebInteractionMoveEventSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/rrweb/RRWebInteractionMoveEventSerializationTest.kt @@ -21,7 +21,7 @@ class RRWebInteractionMoveEventSerializationTest { x = 1.0f y = 2.0f timeOffset = 100 - } + }, ) pointerId = 1 } diff --git a/sentry/src/test/java/io/sentry/rrweb/RRWebOptionsEventSerializationTest.kt b/sentry/src/test/java/io/sentry/rrweb/RRWebOptionsEventSerializationTest.kt index 32dbd9a7d47..a1883fb5d47 100644 --- a/sentry/src/test/java/io/sentry/rrweb/RRWebOptionsEventSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/rrweb/RRWebOptionsEventSerializationTest.kt @@ -25,7 +25,7 @@ class RRWebOptionsEventSerializationTest { sessionReplay.quality = LOW sessionReplay.unmaskViewClasses.add("com.example.MyClass") sessionReplay.maskViewClasses.clear() - } + }, ) .apply { timestamp = 12345678901 } } diff --git a/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportClientReportTest.kt b/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportClientReportTest.kt index 6877d521d26..367f1776665 100644 --- a/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportClientReportTest.kt +++ b/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportClientReportTest.kt @@ -79,7 +79,7 @@ class AsyncHttpTransportClientReportTest { // given givenSetup(TransportResult.error(500)) whenever( - fixture.envelopeCache.storeEnvelope(eq(fixture.envelopeBeforeAttachingClientReport), any()) + fixture.envelopeCache.storeEnvelope(eq(fixture.envelopeBeforeAttachingClientReport), any()), ) .thenReturn(true) @@ -130,7 +130,7 @@ class AsyncHttpTransportClientReportTest { // given givenSetup(TransportResult.error(400)) whenever( - fixture.envelopeCache.storeEnvelope(eq(fixture.envelopeBeforeAttachingClientReport), any()) + fixture.envelopeCache.storeEnvelope(eq(fixture.envelopeBeforeAttachingClientReport), any()), ) .thenReturn(true) @@ -180,7 +180,7 @@ class AsyncHttpTransportClientReportTest { // given givenSetup(TransportResult.error(413)) whenever( - fixture.envelopeCache.storeEnvelope(eq(fixture.envelopeBeforeAttachingClientReport), any()) + fixture.envelopeCache.storeEnvelope(eq(fixture.envelopeBeforeAttachingClientReport), any()), ) .thenReturn(true) @@ -431,8 +431,8 @@ class AsyncHttpTransportClientReportTest { whenever( fixture.clientReportRecorder.attachReportToEnvelope( - eq(fixture.envelopeBeforeAttachingClientReport) - ) + eq(fixture.envelopeBeforeAttachingClientReport), + ), ) .thenReturn(fixture.envelopeAfterAttachingClientReport) } diff --git a/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportTest.kt b/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportTest.kt index 6f711cfedbf..cc14d0ad663 100644 --- a/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportTest.kt +++ b/sentry/src/test/java/io/sentry/transport/AsyncHttpTransportTest.kt @@ -527,7 +527,7 @@ class AsyncHttpTransportTest { override fun markEnqueued() { called = true } - } + }, ) fixture.getSUT().send(envelope, hint) diff --git a/sentry/src/test/java/io/sentry/transport/DistrustedCertificatesTest.kt b/sentry/src/test/java/io/sentry/transport/DistrustedCertificatesTest.kt index 994a0a438e7..b50cd113c38 100644 --- a/sentry/src/test/java/io/sentry/transport/DistrustedCertificatesTest.kt +++ b/sentry/src/test/java/io/sentry/transport/DistrustedCertificatesTest.kt @@ -66,7 +66,7 @@ class DistrustedCertificatesTest { @Test fun `accepts a chain without distrusted CAs`() { DistrustedCertificates.check( - arrayOf(leafIssuedBy(trustedCa).certificate, trustedCa.certificate) + arrayOf(leafIssuedBy(trustedCa).certificate, trustedCa.certificate), ) } diff --git a/sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt b/sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt index 63a297d950c..610b70803c9 100644 --- a/sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt +++ b/sentry/src/test/java/io/sentry/transport/HttpConnectionTest.kt @@ -199,7 +199,7 @@ class HttpConnectionTest { ) = println(String.format(message)) override fun isEnabled(level: SentryLevel?): Boolean = true - } + }, ) // when error message contains funky formatting symbols @@ -236,7 +236,7 @@ class HttpConnectionTest { check { assertEquals("some-user", it.user) assertEquals("some-password", it.password) - } + }, ) } diff --git a/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt b/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt index 721c8202a83..19eceaa0bf9 100644 --- a/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt +++ b/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt @@ -489,7 +489,7 @@ class RateLimiterTest { SentryEnvelopeItem.fromLogs( fixture.serializer, SentryLogEvents( - listOf(SentryLogEvent(SentryId(), SentryLongDate(0), "hello", SentryLogLevel.INFO)) + listOf(SentryLogEvent(SentryId(), SentryLongDate(0), "hello", SentryLogLevel.INFO)), ), ) val envelope = SentryEnvelope(SentryEnvelopeHeader(null), arrayListOf(logEventItem)) @@ -514,7 +514,7 @@ class RateLimiterTest { SentryEnvelopeItem.fromLogs( fixture.serializer, SentryLogEvents( - listOf(SentryLogEvent(SentryId(), SentryLongDate(0), "hello", SentryLogLevel.INFO)) + listOf(SentryLogEvent(SentryId(), SentryLongDate(0), "hello", SentryLogLevel.INFO)), ), ) val envelope = SentryEnvelope(SentryEnvelopeHeader(null), arrayListOf(logEventItem)) diff --git a/sentry/src/test/java/io/sentry/util/CheckInUtilsTest.kt b/sentry/src/test/java/io/sentry/util/CheckInUtilsTest.kt index 02f69bf0e4e..0c6ae14893f 100644 --- a/sentry/src/test/java/io/sentry/util/CheckInUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/CheckInUtilsTest.kt @@ -89,14 +89,14 @@ class CheckInUtilsTest { check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) - } + }, ) verify(scopes) .captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.OK.apiName(), it.status) - } + }, ) verify(lifecycleToken).close() } @@ -129,7 +129,7 @@ class CheckInUtilsTest { assertEquals("monitor-1", it.monitorSlug) assertEquals("environment-1", it.environment) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) - } + }, ) verify(scopes) .captureCheckIn( @@ -137,7 +137,7 @@ class CheckInUtilsTest { assertEquals("monitor-1", it.monitorSlug) assertEquals("environment-1", it.environment) assertEquals(CheckInStatus.OK.apiName(), it.status) - } + }, ) verify(lifecycleToken).close() } @@ -171,14 +171,14 @@ class CheckInUtilsTest { check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) - } + }, ) verify(scopes) .captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.ERROR.apiName(), it.status) - } + }, ) verify(lifecycleToken).close() } @@ -209,14 +209,14 @@ class CheckInUtilsTest { assertEquals("monitor-1", it.monitorSlug) assertSame(monitorConfig, it.monitorConfig) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) - } + }, ) verify(scopes) .captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.OK.apiName(), it.status) - } + }, ) verify(lifecycleToken).close() } @@ -251,14 +251,14 @@ class CheckInUtilsTest { assertEquals("monitor-1", it.monitorSlug) assertSame(monitorConfig, it.monitorConfig) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) - } + }, ) verify(scopes) .captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.OK.apiName(), it.status) - } + }, ) verify(lifecycleToken).close() } @@ -281,7 +281,7 @@ class CheckInUtilsTest { defaultFailureIssueThreshold = 40 defaultRecoveryThreshold = 50 } - } + }, ) val monitorConfig = MonitorConfig(MonitorSchedule.interval(7, MonitorScheduleUnit.DAY)) @@ -308,7 +308,7 @@ class CheckInUtilsTest { defaultMaxRuntime = 50 defaultTimezone = "America/New_York" } - } + }, ) val monitorConfig = diff --git a/sentry/src/test/java/io/sentry/util/CookieUtilsTest.kt b/sentry/src/test/java/io/sentry/util/CookieUtilsTest.kt index 0c000d31e41..9873cbb6d63 100644 --- a/sentry/src/test/java/io/sentry/util/CookieUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/CookieUtilsTest.kt @@ -60,7 +60,7 @@ class CookieUtilsTest { "name=value", KeyValueCollectionBehavior.off(), emptyList(), - ) + ), ) .isNull() } @@ -72,10 +72,10 @@ class CookieUtilsTest { "name=value; sessionId=secret; customerId=123; frameworkSession=456", KeyValueCollectionBehavior.denyList("customer"), listOf("frameworkSession"), - ) + ), ) .isEqualTo( - "name=value; sessionId=[Filtered]; customerId=[Filtered]; frameworkSession=[Filtered]" + "name=value; sessionId=[Filtered]; customerId=[Filtered]; frameworkSession=[Filtered]", ) } @@ -86,7 +86,7 @@ class CookieUtilsTest { "theme=dark; sessionId=secret; language=en", KeyValueCollectionBehavior.allowList("theme", "session"), emptyList(), - ) + ), ) .isEqualTo("theme=dark; sessionId=[Filtered]; language=[Filtered]") } @@ -98,7 +98,7 @@ class CookieUtilsTest { "empty=; data=YWJjZA==", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("empty=; data=YWJjZA==") } @@ -110,7 +110,7 @@ class CookieUtilsTest { "theme=dark=contrast; token=abc=123", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("theme=dark=contrast; token=[Filtered]") } @@ -122,7 +122,7 @@ class CookieUtilsTest { "theme=dark; opaque; =secret; empty=; sessionId=secret", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("theme=dark;[Filtered];[Filtered]; empty=; sessionId=[Filtered]") } @@ -134,7 +134,7 @@ class CookieUtilsTest { "theme=dark, sessionId=secret", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("[Filtered]") } @@ -146,7 +146,7 @@ class CookieUtilsTest { "theme=dark sessionId=secret", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("[Filtered]") } @@ -161,7 +161,7 @@ class CookieUtilsTest { cookies, KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo(cookies) } @@ -173,7 +173,7 @@ class CookieUtilsTest { "theme=dark ", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("theme=dark ") } @@ -185,7 +185,7 @@ class CookieUtilsTest { "theme=dark;", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("theme=dark;") assertThat( @@ -193,7 +193,7 @@ class CookieUtilsTest { "theme=dark; ", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("theme=dark; ") } @@ -205,7 +205,7 @@ class CookieUtilsTest { "theme=\"dark, sessionId=secret\"", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("[Filtered]") } @@ -217,7 +217,7 @@ class CookieUtilsTest { "theme=\"dark sessionId=secret\"", KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .isEqualTo("[Filtered]") } @@ -229,7 +229,7 @@ class CookieUtilsTest { "theme=dark; opaque; =secret", KeyValueCollectionBehavior.allowList("theme", "opaque"), emptyList(), - ) + ), ) .isEqualTo("theme=dark;[Filtered];[Filtered]") } @@ -240,7 +240,7 @@ class CookieUtilsTest { CookieUtils.filterSetCookie( "sessionId=secret; Path=/; HttpOnly; SameSite=Lax", KeyValueCollectionBehavior.denyList(), - ) + ), ) .isEqualTo("sessionId=[Filtered]; Path=/; HttpOnly; SameSite=Lax") } @@ -251,16 +251,16 @@ class CookieUtilsTest { CookieUtils.filterSetCookie( "data=YWJjZA==; Expires=Wed, 09 Jun 2021 10:18:14 GMT; Max-Age=3600; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax", KeyValueCollectionBehavior.denyList(), - ) + ), ) .isEqualTo( - "data=YWJjZA==; Expires=Wed, 09 Jun 2021 10:18:14 GMT; Max-Age=3600; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax" + "data=YWJjZA==; Expires=Wed, 09 Jun 2021 10:18:14 GMT; Max-Age=3600; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax", ) assertThat( CookieUtils.filterSetCookie( "empty=; Path=/", KeyValueCollectionBehavior.denyList(), - ) + ), ) .isEqualTo("empty=; Path=/") } @@ -271,7 +271,7 @@ class CookieUtilsTest { CookieUtils.filterSetCookie( "theme=dark; Path=/; Secure", KeyValueCollectionBehavior.allowList("theme"), - ) + ), ) .isEqualTo("theme=dark; Path=/; Secure") } @@ -282,14 +282,14 @@ class CookieUtilsTest { CookieUtils.filterSetCookie( "opaque; Path=/; HttpOnly", KeyValueCollectionBehavior.denyList(), - ) + ), ) .isEqualTo("[Filtered]") assertThat( CookieUtils.filterSetCookie( "=secret; Path=/; HttpOnly", KeyValueCollectionBehavior.denyList(), - ) + ), ) .isEqualTo("[Filtered]") } @@ -300,7 +300,7 @@ class CookieUtilsTest { CookieUtils.filterSetCookie( "opaque; Path=/; HttpOnly", KeyValueCollectionBehavior.allowList("opaque"), - ) + ), ) .isEqualTo("[Filtered]") } @@ -311,7 +311,7 @@ class CookieUtilsTest { CookieUtils.filterSetCookie( "theme=dark; Path=/", KeyValueCollectionBehavior.off(), - ) + ), ) .isNull() } @@ -323,7 +323,7 @@ class CookieUtilsTest { listOf("theme=dark; SID=secret", "language=en"), KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .containsExactly("theme=dark; SID=[Filtered]", "language=en") .inOrder() @@ -336,7 +336,7 @@ class CookieUtilsTest { java.util.Arrays.asList("theme=dark", null), KeyValueCollectionBehavior.denyList(), emptyList(), - ) + ), ) .containsExactly("theme=dark") } diff --git a/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt b/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt index 624f94a2ef0..c0791642b5c 100644 --- a/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/HttpUtilsTest.kt @@ -16,7 +16,7 @@ class HttpUtilsTest { HttpUtils.filterQueryParams( "name=value&access_token=secret&customerId=123", KeyValueCollectionBehavior.denyList("customer"), - ) + ), ) .isEqualTo("name=value&access_token=[Filtered]&customerId=[Filtered]") } @@ -27,7 +27,7 @@ class HttpUtilsTest { HttpUtils.filterQueryParams( "name=value&access_token=secret&customerId=123", KeyValueCollectionBehavior.allowList("name", "access_token"), - ) + ), ) .isEqualTo("name=value&access_token=[Filtered]&customerId=[Filtered]") } @@ -38,7 +38,7 @@ class HttpUtilsTest { HttpUtils.filterQueryParams( "access%5Ftoken=secret&display%20name=Jane+Doe", KeyValueCollectionBehavior.denyList(), - ) + ), ) .isEqualTo("access%5Ftoken=[Filtered]&display%20name=Jane+Doe") } @@ -49,7 +49,7 @@ class HttpUtilsTest { HttpUtils.filterQueryParams( "name=&flag&&token", KeyValueCollectionBehavior.denyList(), - ) + ), ) .isEqualTo("name=&flag&&token=[Filtered]") } diff --git a/sentry/src/test/java/io/sentry/util/InitUtilTest.kt b/sentry/src/test/java/io/sentry/util/InitUtilTest.kt index f72eb74a64c..dd12a5879ce 100644 --- a/sentry/src/test/java/io/sentry/util/InitUtilTest.kt +++ b/sentry/src/test/java/io/sentry/util/InitUtilTest.kt @@ -71,7 +71,7 @@ class InitUtilTest { SentryOptions().also { it.initPriority = InitPriority.LOWEST it.isForceInit = true - } + }, ) givenClientEnabled() diff --git a/sentry/src/test/java/io/sentry/util/JsonSerializationUtilsTest.kt b/sentry/src/test/java/io/sentry/util/JsonSerializationUtilsTest.kt index 170ad4646f4..4a1d80d5b1e 100644 --- a/sentry/src/test/java/io/sentry/util/JsonSerializationUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/JsonSerializationUtilsTest.kt @@ -51,7 +51,7 @@ class JsonSerializationUtilsTest { fun `serializes AtomicIntegerArray to list`() { val actual = JsonSerializationUtils.atomicIntegerArrayToList( - AtomicIntegerArray(arrayOf(1, 2, 3).toIntArray()) + AtomicIntegerArray(arrayOf(1, 2, 3).toIntArray()), ) assertEquals(listOf(1, 2, 3), actual) } diff --git a/sentry/src/test/java/io/sentry/util/LoadClassTest.kt b/sentry/src/test/java/io/sentry/util/LoadClassTest.kt index 4cb921feff8..f73c6edd16d 100644 --- a/sentry/src/test/java/io/sentry/util/LoadClassTest.kt +++ b/sentry/src/test/java/io/sentry/util/LoadClassTest.kt @@ -24,7 +24,7 @@ class LoadClassTest { loadClass.isClassAvailable( "io.sentry.ThisClassDoesNotExist", null as io.sentry.ILogger?, - ) + ), ) .isTrue() assertThat(loadClass.isClassAvailable("io.sentry.Sentry", null as io.sentry.ILogger?)) @@ -49,7 +49,7 @@ class LoadClassTest { val loadClass = LoadClass() assertNotNull(loadClass.loadClass("io.sentry.SentryEvent", null)) assertFalse( - loadClass.isClassAvailable("io.sentry.ThisClassDoesNotExist", null as io.sentry.ILogger?) + loadClass.isClassAvailable("io.sentry.ThisClassDoesNotExist", null as io.sentry.ILogger?), ) } diff --git a/sentry/src/test/java/io/sentry/util/MapObjectReaderTest.kt b/sentry/src/test/java/io/sentry/util/MapObjectReaderTest.kt index e7ad9bc61e3..0981841a33c 100644 --- a/sentry/src/test/java/io/sentry/util/MapObjectReaderTest.kt +++ b/sentry/src/test/java/io/sentry/util/MapObjectReaderTest.kt @@ -18,7 +18,7 @@ import org.junit.Test class MapObjectReaderTest { enum class BasicEnum { - A + A, } data class BasicSerializable(var test: String = "string") : JsonSerializable { @@ -216,7 +216,7 @@ class MapObjectReaderTest { partialSerializableValue("fail", "bad"), "oops", partialSerializableValue("ok", "two"), - ) + ), ) val actual = reader.nextListOrNull(logger, partiallyFailingDeserializer) @@ -286,7 +286,7 @@ class MapObjectReaderTest { linkedMapOf( "bad" to serializableValue("fail"), "good" to listOf(serializableValue("one")), - ) + ), ) .nextMapOfListOrNull(logger, BasicSerializable.Deserializer()) @@ -300,7 +300,7 @@ class MapObjectReaderTest { linkedMapOf( "good" to listOf(serializableValue("two")), "bad" to serializableValue("fail"), - ) + ), ) .nextMapOfListOrNull(logger, BasicSerializable.Deserializer()) @@ -311,7 +311,7 @@ class MapObjectReaderTest { fun `nextListOrNull keeps elements after a partially consumed failing element`() { val actual = getValuesReader( - listOf(partialSerializableValue("fail", "bad"), partialSerializableValue("ok", "two")) + listOf(partialSerializableValue("fail", "bad"), partialSerializableValue("ok", "two")), ) .nextListOrNull(logger, partiallyFailingDeserializer) @@ -325,7 +325,7 @@ class MapObjectReaderTest { linkedMapOf( "bad" to partialSerializableValue("fail", "bad"), "good" to partialSerializableValue("ok", "two"), - ) + ), ) .nextMapOrNull(logger, partiallyFailingDeserializer) @@ -339,7 +339,7 @@ class MapObjectReaderTest { linkedMapOf( "bad" to listOf(partialSerializableValue("fail", "bad")), "good" to listOf(partialSerializableValue("ok", "two")), - ) + ), ) .nextMapOfListOrNull(logger, partiallyFailingDeserializer) diff --git a/sentry/src/test/java/io/sentry/util/MapObjectWriterTest.kt b/sentry/src/test/java/io/sentry/util/MapObjectWriterTest.kt index 1a5c1d22a7e..665e093b9ae 100644 --- a/sentry/src/test/java/io/sentry/util/MapObjectWriterTest.kt +++ b/sentry/src/test/java/io/sentry/util/MapObjectWriterTest.kt @@ -21,7 +21,7 @@ import kotlin.test.assertTrue class MapObjectWriterTest { enum class BasicEnum { - A + A, } class BasicSerializable : JsonSerializable { diff --git a/sentry/src/test/java/io/sentry/util/MonitorConfigUtilsTest.kt b/sentry/src/test/java/io/sentry/util/MonitorConfigUtilsTest.kt index e882b3ed070..830818c1bd3 100644 --- a/sentry/src/test/java/io/sentry/util/MonitorConfigUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/MonitorConfigUtilsTest.kt @@ -62,7 +62,7 @@ class MonitorConfigUtilsTest { .thenReturn( SentryOptions().apply { cron = SentryOptions.Cron().apply { defaultCheckinMargin = margin } - } + }, ) block() } @@ -316,7 +316,7 @@ class MonitorConfigUtilsTest { null, null, TimeUnit.MINUTES.toMillis(Int.MAX_VALUE.toLong() + 1), - ) + ), ) .isNull() } @@ -350,7 +350,7 @@ class MonitorConfigUtilsTest { ) for ((cron, crontab) in expected) { assertThat( - MonitorConfigUtils.fromSpringScheduled(cron, "UTC", null, null, false)?.schedule?.value + MonitorConfigUtils.fromSpringScheduled(cron, "UTC", null, null, false)?.schedule?.value, ) .isEqualTo(crontab) } @@ -362,11 +362,11 @@ class MonitorConfigUtilsTest { TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo")) try { assertThat( - MonitorConfigUtils.fromSpringScheduled("0 0 2 * * *", null, null, null, false)?.timezone + MonitorConfigUtils.fromSpringScheduled("0 0 2 * * *", null, null, null, false)?.timezone, ) .isEqualTo("Asia/Tokyo") assertThat( - MonitorConfigUtils.fromSpringScheduled("0 0 2 * * *", "", null, null, false)?.timezone + MonitorConfigUtils.fromSpringScheduled("0 0 2 * * *", "", null, null, false)?.timezone, ) .isEqualTo("Asia/Tokyo") } finally { @@ -388,7 +388,7 @@ class MonitorConfigUtilsTest { assertThat(MonitorConfigUtils.fromSpringScheduled(cron, "UTC", null, null, false)).isNull() } assertThat( - MonitorConfigUtils.fromSpringScheduled("0 0 2 * * *", "GMT+05:30", null, null, false) + MonitorConfigUtils.fromSpringScheduled("0 0 2 * * *", "GMT+05:30", null, null, false), ) .isNull() assertThat(MonitorConfigUtils.fromSpringScheduled(null, null, 30_000L, null, false)).isNull() @@ -433,7 +433,7 @@ class MonitorConfigUtilsTest { ) for ((cron, crontab) in expected) { assertThat( - MonitorConfigUtils.fromSpringScheduled(cron, "UTC", null, null, true)?.schedule?.value + MonitorConfigUtils.fromSpringScheduled(cron, "UTC", null, null, true)?.schedule?.value, ) .isEqualTo(crontab) } @@ -453,7 +453,7 @@ class MonitorConfigUtilsTest { TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo")) try { assertThat( - MonitorConfigUtils.fromSpringScheduled("0 0 2 * * *", null, null, null, true)?.timezone + MonitorConfigUtils.fromSpringScheduled("0 0 2 * * *", null, null, null, true)?.timezone, ) .isEqualTo("Asia/Tokyo") } finally { diff --git a/sentry/src/test/java/io/sentry/util/SpanUtilsTest.kt b/sentry/src/test/java/io/sentry/util/SpanUtilsTest.kt index 481700533a2..262892d92ef 100644 --- a/sentry/src/test/java/io/sentry/util/SpanUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/SpanUtilsTest.kt @@ -13,7 +13,7 @@ class SpanUtilsTest { assertThat(SpanUtils.ignoredSpanOriginsForOpenTelemetry(SentryOpenTelemetryMode.AGENT)) .contains("auto.http.okhttp") assertThat( - SpanUtils.ignoredSpanOriginsForOpenTelemetry(SentryOpenTelemetryMode.AGENTLESS_SPRING) + SpanUtils.ignoredSpanOriginsForOpenTelemetry(SentryOpenTelemetryMode.AGENTLESS_SPRING), ) .doesNotContain("auto.http.okhttp") } diff --git a/sentry/src/test/java/io/sentry/util/TracingUtilsTest.kt b/sentry/src/test/java/io/sentry/util/TracingUtilsTest.kt index 7e67bc6e53e..3a956562b9a 100644 --- a/sentry/src/test/java/io/sentry/util/TracingUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/TracingUtilsTest.kt @@ -81,7 +81,7 @@ class TracingUtilsTest { assertTrue( headers.baggageHeader!! .value - .contains("sentry-trace_id=${fixture.scope.propagationContext.traceId}") + .contains("sentry-trace_id=${fixture.scope.propagationContext.traceId}"), ) assertFalse(fixture.scope.propagationContext.baggage!!.isMutable) } @@ -181,7 +181,7 @@ class TracingUtilsTest { SpanId(), null, Baggage.fromHeader( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ) .also { it.freeze() }, true, @@ -202,12 +202,12 @@ class TracingUtilsTest { assertEquals(fixture.scope.propagationContext.traceId, headers.sentryTraceHeader.traceId) assertTrue(headers.baggageHeader!!.value.contains("some-baggage-key=some-baggage-value")) assertTrue( - headers.baggageHeader!!.value.contains("sentry-trace_id=2722d9f6ec019ade60c776169d9a8904") + headers.baggageHeader!!.value.contains("sentry-trace_id=2722d9f6ec019ade60c776169d9a8904"), ) assertFalse( headers.baggageHeader!! .value - .contains("sentry-trace_id=${fixture.scope.propagationContext.traceId}") + .contains("sentry-trace_id=${fixture.scope.propagationContext.traceId}"), ) } @@ -323,7 +323,7 @@ class TracingUtilsTest { SpanId(), null, Baggage.fromHeader( - "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET" + "sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET", ), true, ) diff --git a/sentry/src/test/java/io/sentry/util/UrlUtilsTest.kt b/sentry/src/test/java/io/sentry/util/UrlUtilsTest.kt index f7bdbcbcfb1..de8829f7efc 100644 --- a/sentry/src/test/java/io/sentry/util/UrlUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/UrlUtilsTest.kt @@ -258,7 +258,7 @@ class UrlUtilsTest { fun `does not filter email address in path`() { val urlDetails = UrlUtils.parseNullable( - "https://staging.server.com/api/v4/auth/password/reset/email@example.com" + "https://staging.server.com/api/v4/auth/password/reset/email@example.com", )!! assertEquals( "https://staging.server.com/api/v4/auth/password/reset/email@example.com", @@ -272,7 +272,7 @@ class UrlUtilsTest { fun `does not filter email address in path with fragment`() { val urlDetails = UrlUtils.parseNullable( - "https://staging.server.com/api/v4/auth/password/reset/email@example.com#top" + "https://staging.server.com/api/v4/auth/password/reset/email@example.com#top", )!! assertEquals( "https://staging.server.com/api/v4/auth/password/reset/email@example.com", @@ -286,7 +286,7 @@ class UrlUtilsTest { fun `does not filter email address in path with query and fragment`() { val urlDetails = UrlUtils.parseNullable( - "https://staging.server.com/api/v4/auth/password/reset/email@example.com?a=b&c=d#top" + "https://staging.server.com/api/v4/auth/password/reset/email@example.com?a=b&c=d#top", )!! assertEquals( "https://staging.server.com/api/v4/auth/password/reset/email@example.com", diff --git a/settings.gradle.kts b/settings.gradle.kts index b57f28a2654..4770877b7a2 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -50,6 +50,7 @@ include( "sentry-android-distribution", "sentry-android-core", "sentry-android-ndk", + "sentry-android-ndk-outproc", "sentry-android", "sentry-android-timber", "sentry-android-fragment",